qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
190,738
<p>With the following piece of code:</p> <pre><code>typedef struct { char fileName[ 1024]; time_t deleteTime; } file_item_t; .... .... setEntry(char *fileName) { file_item_t file; memset( &amp;file, 0x00, sizeof( file_item_t )); memcpy( file.fileName, fileName, sizeof( file.fileName ) - 1 ); ... ... </code></pre> <p>When the function is called, it runs OK on a SPARC machine but segfaults on an i386 both running Solaris 10. <code>fileName</code> is a nul-terminated string about 30 chars let's say. It appears that an attempt to read beyond the range of the <code>fileName</code> using <code>memcpy()</code> triggers a segmentation fault on some systems.</p> <p>It's legacy code and easily correctable. But what I would like to know is about the underlying characteristics that can result in this failing or not. Is it related to read violation on the stack? Some boundary crossing? It is related to memory segmentation and is it just a case of chance (depending on how memory segmentation/paging is done by memory management and OS.) that it can fail or not.</p>
[ { "answer_id": 190744, "author": "Timbo", "author_id": 1810, "author_profile": "https://Stackoverflow.com/users/1810", "pm_score": 1, "selected": false, "text": "fileName" }, { "answer_id": 191710, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 1, "selected": false, "text": "char *filename" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/190738", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
190,740
<p>I thought I understood what the default method does to a hash... </p> <p>Give a default value for a key if it doesn't exist:</p> <pre><code>irb(main):001:0&gt; a = {} =&gt; {} irb(main):002:0&gt; a.default = 4 =&gt; 4 irb(main):003:0&gt; a[8] =&gt; 4 irb(main):004:0&gt; a[9] += 1 =&gt; 5 irb(main):005:0&gt; a =&gt; {9=&gt;5} </code></pre> <p>All good.</p> <p>But if I set the default to be a empty list, or empty hash, I don't understand it's behaviour at <strong>all</strong>....</p> <pre><code>irb(main):001:0&gt; a = {} =&gt; {} irb(main):002:0&gt; a.default = [] =&gt; [] irb(main):003:0&gt; a[8] &lt;&lt; 9 =&gt; [9] # great! irb(main):004:0&gt; a =&gt; {} # ?! would have expected {8=&gt;[9]} irb(main):005:0&gt; a[8] =&gt; [9] # awesome! irb(main):006:0&gt; a[9] =&gt; [9] # unawesome! shouldn't this be [] ?? </code></pre> <p>I was hoping/expecting the same behaviour as if I had used the ||= operator...</p> <pre><code>irb(main):001:0&gt; a = {} =&gt; {} irb(main):002:0&gt; a[8] ||= [] =&gt; [] irb(main):003:0&gt; a[8] &lt;&lt; 9 =&gt; [9] irb(main):004:0&gt; a =&gt; {8=&gt;[9]} irb(main):005:0&gt; a[9] =&gt; nil </code></pre> <p>Can anyone explain what is going on?</p>
[ { "answer_id": 190801, "author": "Aaron Hinni", "author_id": 12086, "author_profile": "https://Stackoverflow.com/users/12086", "pm_score": 7, "selected": true, "text": "Hash.default default a = {}\na.default = [] # set default to a new empty Array\na[8] << 9 # a[8] doesn't exist, so the Array instance is returned, and 9 appended to it\na.default # => [9]\na[9] # a[9] doesn't exist, so default is returned\n" }, { "answer_id": 190832, "author": "Simon Howard", "author_id": 24806, "author_profile": "https://Stackoverflow.com/users/24806", "pm_score": 3, "selected": false, "text": "irb(main):002:0> a.default = []\n=> []\nirb(main):003:0> a[8] << 9\n=> [9] # great!\n irb(main):002:0> a.default = [9]\n=> [9]\n irb(main):006:0> a[9]\n=> [9] # unawesome! shouldn't this be [] ??\n irb(main):004:0> a\n=> {} # ?! would have expected {8=>[9]}\n # Time to add a new entry to the hash table; this might be \n# the first entry for this key..\nmyhash[key] ||= []\nmyhash[key] << value\n" }, { "answer_id": 192478, "author": "glenn mcdonald", "author_id": 7919, "author_profile": "https://Stackoverflow.com/users/7919", "pm_score": 6, "selected": false, "text": "(myhash[key] ||= []) << value\n ((myhash[key1] ||= {})[key2] ||= []) << value\n myhash = Hash.new {|hash,key| hash[key] = []}\n" }, { "answer_id": 192622, "author": "Daniel Beardsley", "author_id": 13216, "author_profile": "https://Stackoverflow.com/users/13216", "pm_score": -1, "selected": false, "text": "h = Hash.new { [] }\nh[:missing]\n => []\n\n#But, you should never modify the empty array because it isn't stored anywhere\n#A new, empty array is returned every time\nh[:missing] << 'entry'\nh[:missing]\n => []\n" }, { "answer_id": 194297, "author": "Turp", "author_id": 24856, "author_profile": "https://Stackoverflow.com/users/24856", "pm_score": 5, "selected": false, "text": "irb(main):001:0> h = Hash.new{|h, k| h[k] = []}\n=> {}\nirb(main):002:0> h[1] << \"ABC\"\n=> [\"ABC\"]\nirb(main):003:0> h[3]\n=> []\nirb(main):004:0> h\n=> {1=>[\"ABC\"], 3=>[]}\n" }, { "answer_id": 2582076, "author": "jrochkind", "author_id": 307106, "author_profile": "https://Stackoverflow.com/users/307106", "pm_score": 3, "selected": false, "text": "irb(main):004:0> a = Hash.new {|hash,key| hash[key] = []}\n=> {}\nirb(main):005:0> a.has_key?(:key)\n=> false\nirb(main):006:0> a[:key]\n=> []\nirb(main):007:0> a.has_key?(:key)\n=> true\n" }, { "answer_id": 4251779, "author": "migbar", "author_id": 515480, "author_profile": "https://Stackoverflow.com/users/515480", "pm_score": 3, "selected": false, "text": "endless = Hash.new { |h, k| h[k] = Hash.new(&h.default_proc) }\nendless[\"deep\"][\"in\"][\"here\"] = \"hello\"\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/190740", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26094/" ]
190,748
<p>You can, obviously, put a variable declaration in a for loop:</p> <pre><code>for (int i = 0; ... </code></pre> <p>and I've noticed that you can do the same thing in if and switch statements as well:</p> <pre><code>if ((int i = f()) != 0) ... switch (int ch = stream.get()) ... </code></pre> <p>But when I try to do the same thing in a while loop:</p> <pre><code>while ((int ch = stream.get()) != -1) ... </code></pre> <p>The compiler (VC++ 9.0) does not like it at all.</p> <p>Is this compliant behavior? Is there a reason for it?</p> <p><strong>EDIT</strong>: I found I can do this:</p> <pre><code>while (int ch = stream.get() != -1) ... </code></pre> <p>but because of precedence rules, that's interpreted as:</p> <pre><code>while (int ch = (stream.get() != -1)) ... </code></pre> <p>which is not what I want.</p>
[ { "answer_id": 190768, "author": "workmad3", "author_id": 16035, "author_profile": "https://Stackoverflow.com/users/16035", "pm_score": 4, "selected": false, "text": "label:\n{ //start of condition scope\n T t = x;\n if (t) {\n statement\n goto label;\n }\n}\n" }, { "answer_id": 191550, "author": "MSalters", "author_id": 15416, "author_profile": "https://Stackoverflow.com/users/15416", "pm_score": 2, "selected": false, "text": "int i = f() (a) int i=f() (int i=f()) while (int i = foo()) while ((int i = foo())) \"(\" expr \")\"" }, { "answer_id": 191737, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 0, "selected": false, "text": "while (int ch = stream.get(), ch != -1) ...\n" }, { "answer_id": 191876, "author": "Richard Corden", "author_id": 11698, "author_profile": "https://Stackoverflow.com/users/11698", "pm_score": 5, "selected": true, "text": "condition:\n expression\n type-specifier-seq declarator = assignment-expression\n if ( i && j && k ) {}\nif ( (i = j) ==0 ) {}\nif ( int i = j ) {}\n if for while switch" }, { "answer_id": 193051, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "while(int i = 1) {\n}\n while ( (int i = 1) + 3) {\n}\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/190748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4086/" ]
190,755
<p>Any suggestion how I can document my Perl code? What do you use and what tools are available to help me?</p> <p>Which module do you use to convert pod to html?</p>
[ { "answer_id": 190903, "author": "brian d foy", "author_id": 2766176, "author_profile": "https://Stackoverflow.com/users/2766176", "pm_score": 7, "selected": true, "text": "-m perldoc -m Foo::Bar\n -l perldoc -l Foo::Bar\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/190755", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10523/" ]
190,759
<p>I'm looking for way to PHP to detect if a script was run from a manual invocation on a shell (me logging in and running it), or if it was run from the crontab entry.</p> <p>I have various maintenance type scripts written in php that i have set to run in my crontab. Occasionally, and I need to run them manually ahead of schedule or if something failed/broken, i need to run them a couple times.</p> <p>The problem with this is that I also have some external notifications set into the tasks (posting to twitter, sending an email, etc) that I DONT want to happen everytime I run the script manually.</p> <p>I'm using php5 (if it matters), its a fairly standard linux server environment.</p> <p>Any ideas?</p>
[ { "answer_id": 190778, "author": "Till", "author_id": 2859, "author_profile": "https://Stackoverflow.com/users/2859", "pm_score": 3, "selected": false, "text": "$_ENV" }, { "answer_id": 190790, "author": "Adam Hopkinson", "author_id": 12280, "author_profile": "https://Stackoverflow.com/users/12280", "pm_score": 2, "selected": false, "text": "?source=cron $_GET['source'] php script.php arg1 arg2 $argv" }, { "answer_id": 190796, "author": "Matthew Scharley", "author_id": 15537, "author_profile": "https://Stackoverflow.com/users/15537", "pm_score": 5, "selected": false, "text": "CRON=running\n" }, { "answer_id": 190862, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 3, "selected": false, "text": "ps -ef | grep pid UID PID PPID C STIME TTY TIME CMD\nroot 1 0 0 16:21 ? 00:00:00 /sbin/init\nallan 6386 1 0 19:04 ? 00:00:00 gnome-terminal --geom...\nallan 6390 6386 0 19:04 pts/0 00:00:00 bash\nallan 6408 6390 0 19:04 pts/0 00:00:00 ps -ef\n UID PID PPID C STIME TTY TIME CMD\nroot 1 0 0 16:21 ? 00:00:00 /sbin/init\nroot 5704 1 0 16:22 ? 00:00:00 /usr/sbin/cron\nallan 6390 5704 0 19:04 pts/0 00:00:00 bash\nallan 6408 6390 0 19:04 pts/0 00:00:00 ps -ef\n" }, { "answer_id": 191284, "author": "Paul Stone", "author_id": 25757, "author_profile": "https://Stackoverflow.com/users/25757", "pm_score": 7, "selected": true, "text": "$cron = !isset($_ENV['SSH_CLIENT']);" }, { "answer_id": 471295, "author": "Bouke", "author_id": 58107, "author_profile": "https://Stackoverflow.com/users/58107", "pm_score": 1, "selected": false, "text": "$_SERVER['SESSIONNAME'] Console" }, { "answer_id": 497017, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "if(!$_SERVER['HTTP_HOST']) {\n blabla();\n}\n" }, { "answer_id": 794610, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "command ext_updates=1\n command \n" }, { "answer_id": 813643, "author": "Drew Stephens", "author_id": 17339, "author_profile": "https://Stackoverflow.com/users/17339", "pm_score": 2, "selected": false, "text": "TERM $_SERVER if (isset($_SERVER{'TERM'}))\n{\n class::doStuffShell();\n}\nelse\n{\n class::doStuffWeb();\n}\n" }, { "answer_id": 2429105, "author": "Wouter Bolsterlee", "author_id": 291947, "author_profile": "https://Stackoverflow.com/users/291947", "pm_score": 4, "selected": false, "text": "if (posix_isatty(STDOUT))\n /* do interactive terminal stuff here */\n" }, { "answer_id": 4089150, "author": "Daniel", "author_id": 496170, "author_profile": "https://Stackoverflow.com/users/496170", "pm_score": 0, "selected": false, "text": "posix_isatty(STDOUT) return FALSE" }, { "answer_id": 4577400, "author": "Kurausu", "author_id": 560182, "author_profile": "https://Stackoverflow.com/users/560182", "pm_score": -1, "selected": false, "text": "count($_SERVER['argc']) $_SERVER['argv'] \"CronJob\"=true;" }, { "answer_id": 5672581, "author": "PeterDerMeter", "author_id": 709181, "author_profile": "https://Stackoverflow.com/users/709181", "pm_score": 3, "selected": false, "text": "if (!isset($_SERVER['HTTP_USER_AGENT'])) {\n" }, { "answer_id": 7207133, "author": "davethebrave", "author_id": 801652, "author_profile": "https://Stackoverflow.com/users/801652", "pm_score": 5, "selected": false, "text": "$sapi_type = php_sapi_name();\nif(substr($sapi_type, 0, 3) == 'cli' || empty($_SERVER['REMOTE_ADDR'])) {\n echo \"shell\";\n} else {\n echo \"webserver\";\n}\n php_sapi_name() $_SERVER['REMOTE_ADDR']" }, { "answer_id": 7868700, "author": "agi", "author_id": 1009886, "author_profile": "https://Stackoverflow.com/users/1009886", "pm_score": 4, "selected": false, "text": "\"/usr/bin/php -q /var/www/vhosts/myuser/index.php\"\n \"CRON_MODE=1 /usr/bin/php -q /var/www/vhosts/myuser/index.php\"\n if (!getenv('CRON_MODE'))\n print \"Sorry, only CRON can access this script\";\n" }, { "answer_id": 9765564, "author": "MingalevME", "author_id": 1046909, "author_profile": "https://Stackoverflow.com/users/1046909", "pm_score": 6, "selected": false, "text": "if (php_sapi_name() == 'cli') { \n if (isset($_SERVER['TERM'])) { \n echo \"The script was run from a manual invocation on a shell\"; \n } else { \n echo \"The script was run from the crontab entry\"; \n } \n} else { \n echo \"The script was run from a webserver, or something else\"; \n}\n" }, { "answer_id": 11167244, "author": "Gabor Garami", "author_id": 182474, "author_profile": "https://Stackoverflow.com/users/182474", "pm_score": 0, "selected": false, "text": "MAILTO" }, { "answer_id": 18411288, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "getenv('TERM')\n" }, { "answer_id": 22151236, "author": "eosphere", "author_id": 417206, "author_profile": "https://Stackoverflow.com/users/417206", "pm_score": 2, "selected": false, "text": "if (isset($_ENV[\"APACHE_RUN_DIR\"])) {\n // I'm called by a web user\n}\nelse {\n // I'm called by crontab\n} \n <?php var_dump($_ENV); ?>\n /usr/bin/php /var/www/yourpath/dummy.php\n" }, { "answer_id": 68491272, "author": "iaps", "author_id": 986719, "author_profile": "https://Stackoverflow.com/users/986719", "pm_score": 0, "selected": false, "text": "(array) $argv $argv php /path/to/file.php first second third [\"/path/to/file.php\", \"first\", \"second\", \"third\"] if (isset($argv) && is_array($argv) && in_array('first', $argv)) { /* do something */ }" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/190759", "https://Stackoverflow.com", "https://Stackoverflow.com/users/314/" ]
190,775
<p>I need to take a paragraph of text and extract from it a list of "tags". Most of this is quite straight forward. However I need some help now stemming the resulting word list to avoid duplicates. Example: Community / Communities</p> <p>I've used an implementation of Porter Stemmer algorithm (I'm writing in PHP by the way):</p> <p><a href="http://tartarus.org/~martin/PorterStemmer/php.txt" rel="noreferrer">http://tartarus.org/~martin/PorterStemmer/php.txt</a></p> <p>This works, up to a point, but doesn't return "real" words. The example above is stemmed to "commun".</p> <p>I've tried "Snowball" (suggested within another Stack Overflow thread).</p> <p><a href="http://snowball.tartarus.org/demo.php" rel="noreferrer">http://snowball.tartarus.org/demo.php</a></p> <p>For my example (community / communities), Snowball stems to "communiti".</p> <p><strong>Question</strong></p> <p>Are there any other stemming algorithms that will do this? Has anyone else solved this problem?</p> <p><em>My current thinking is that I could use a stemming algorithm to avoid duplicates and then pick the shortest word I encounter to be the actual word to display.</em></p>
[ { "answer_id": 615251, "author": "Kaarel", "author_id": 12547, "author_profile": "https://Stackoverflow.com/users/12547", "pm_score": 6, "selected": false, "text": "morpha $ cat test.txt \nCommunity\nCommunities\n$ cat test.txt | ./morpha -uc\nCommunity\nCommunity\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/190775", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15318/" ]
190,776
<p>How do you build and use dynamic sql in a MySQL stored procedure?</p>
[ { "answer_id": 190962, "author": "Jason Stevenson", "author_id": 13368, "author_profile": "https://Stackoverflow.com/users/13368", "pm_score": 7, "selected": true, "text": "mysql> PREPARE stmt FROM \n -> 'select count(*) \n -> from information_schema.schemata \n -> where schema_name = ? or schema_name = ?'\n;\nQuery OK, 0 rows affected (0.00 sec)\nStatement prepared\nmysql> EXECUTE stmt \n -> USING @schema1,@schema2\n+----------+\n| count(*) |\n+----------+\n| 2 |\n+----------+\n1 row in set (0.00 sec)\nmysql> DEALLOCATE PREPARE stmt;\n stmt" }, { "answer_id": 5728155, "author": "TimoSolo", "author_id": 253096, "author_profile": "https://Stackoverflow.com/users/253096", "pm_score": 7, "selected": false, "text": "delimiter // \nCREATE PROCEDURE dynamic(IN tbl CHAR(64), IN col CHAR(64))\nBEGIN\n SET @s = CONCAT('SELECT ',col,' FROM ',tbl );\n PREPARE stmt FROM @s;\n EXECUTE stmt;\n DEALLOCATE PREPARE stmt;\nEND\n//\ndelimiter ;\n" }, { "answer_id": 34313647, "author": "Elcio", "author_id": 5686921, "author_profile": "https://Stackoverflow.com/users/5686921", "pm_score": 2, "selected": false, "text": "Server version: 5.6.25-log MySQL Community Server (GPL)\n\nmysql> PREPARE stmt FROM 'select \"AAAA\" into @a';\nQuery OK, 0 rows affected (0.01 sec)\nStatement prepared\n\nmysql> EXECUTE stmt;\nQuery OK, 1 row affected (0.01 sec)\n\nDEALLOCATE prepare stmt;\nQuery OK, 0 rows affected (0.01 sec)\n\nmysql> select @a;\n+------+\n| @a |\n+------+\n|AAAA |\n+------+\n1 row in set (0.01 sec)\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/190776", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3747/" ]
190,813
<p>Does anyone know if dbunit has the power to export specific data from multiple tables at once based on a sql statement, as can be done by using dbunit's QueryDataSet class to export data from a single table based on a sql statement, <a href="http://www.dbunit.org/faq.html#extract" rel="nofollow noreferrer">as can been seen here</a>.</p> <p>James</p>
[ { "answer_id": 47978860, "author": "Ilya Tkachev", "author_id": 6318650, "author_profile": "https://Stackoverflow.com/users/6318650", "pm_score": 0, "selected": false, "text": "QueryDataSet partialDataSet = new QueryDataSet(connection);\npartialDataSet.addTable(tableName1, \"select * from \" + tableName1);\npartialDataSet.addTable(tableName2, \"select * from \" + tableName2);\npartialDataSet.addTable(tableName3, \"select * from \" + tableName3);\n\nFileOutputStream fos = new FileOutputStream(\"Noname.dataset\");\nFlatXmlDataSet.write(ratingDataSet, fos);\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/190813", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
190,818
<p>I want to create an <code>NSOpenPanel</code> that can select any kind of file, so I do this</p> <pre><code>NSOpenPanel* panel = [NSOpenPanel openPanel]; if([panel runModalForTypes:nil] == NSOKButton) { // process files here } </code></pre> <p>which lets me select all files <em>except</em> symbolic links.<br> They're simply not selectable and the obvious <code>setResolvesAliases</code><br> does nothing.</p> <p>What gives?</p> <p><b>Update 1:</b> I did some more testing and found that this strangeness<br> is present in Leopard (10.5.5) but not in Tiger (10.4.8). </p> <p><b>Update 2:</b> The code above can select mac aliases (persistent path<br> data that lives in the resource fork) but not symlinks (files created with ln -s).</p>
[ { "answer_id": 191978, "author": "Mecki", "author_id": 15809, "author_profile": "https://Stackoverflow.com/users/15809", "pm_score": 1, "selected": false, "text": "NSOpenPanel * panel = [NSOpenPanel openPanel];\n[panel setCanChooseDirectories:YES];\nif ([panel runModalForTypes:nil] == NSOKButton) {\n NSLog(@\"%@\", [panel filenames]);\n}\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/190818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22147/" ]
190,819
<p>For a new project with Flash I was looking for something along the lines of standard libraries for basic programming needs, along the lines of Python or Ruby standard libraries. But the only thing I found was a dead project on Sourceforge.</p> <p>Thus is there no standard library for flash? Does everyone reinvent the wheel each time?</p>
[ { "answer_id": 190856, "author": "hasseg", "author_id": 4111, "author_profile": "https://Stackoverflow.com/users/4111", "pm_score": 2, "selected": false, "text": "flash.* mx.*" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/190819", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15124/" ]
190,830
<p>I am responsible for the User Interface of an application written completely in Visual C++ using MFC and some third-part controls. I would like to use C# (WinForms or even better WPF) to improve the application look&amp;feel.</p> <p>I would like some advices about how to do it. Links, articles, examples...</p> <p>Right now the user interface is isolated in a single project and I don't want to compile the whole module with CLR. So how do I have to manage that from the architectural point of view?</p> <p>I have already looked at the Internet for the subject and read MSDN information. I would like more detailed information...is it convinient? pros/cons? have you used this approach successfully in a "big" application? I don't want to compile the whole ui project with CLR...can I just have all the .NET code in a isolated project and call it from the ui project? what's the best way to do it?</p> <p>Thanks in advance.</p>
[ { "answer_id": 190856, "author": "hasseg", "author_id": 4111, "author_profile": "https://Stackoverflow.com/users/4111", "pm_score": 2, "selected": false, "text": "flash.* mx.*" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/190830", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14053/" ]
190,833
<p>I want to intercept a request in a filter/servlet and add a few parameters to it. However, the request does not expose a 'setParameter' method and the parameter map when manipulated throws an error saying it is locked. Is there an alternative I can try?</p>
[ { "answer_id": 190859, "author": "Panagiotis Korros", "author_id": 19331, "author_profile": "https://Stackoverflow.com/users/19331", "pm_score": 3, "selected": false, "text": "public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {\n HttpServletRequest httpRequest = (HttpServletRequest) request;\n HttpServletRequest customRequest = new CustomHttpServletRequest(httpRequest);\n customRequest.addParameter(xxx, \"xxx\");\n chain.doFilter(customRequest, response);\n}\n" }, { "answer_id": 190865, "author": "Bruno De Fraine", "author_id": 6918, "author_profile": "https://Stackoverflow.com/users/6918", "pm_score": 5, "selected": true, "text": "HttpServletRequestWrapper getParameter" }, { "answer_id": 33677297, "author": "kolobok", "author_id": 751200, "author_profile": "https://Stackoverflow.com/users/751200", "pm_score": 1, "selected": false, "text": "public class MyFilter implements Filter {\n...\n@Override\npublic void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {\n if (request instanceof HttpServletRequest) {\n HttpServletRequest httprequest = (HttpServletRequest) request;\n Map<String, String[]> extraParams = new HashMap<String, String[]>();\n extraParams.put(\"myparamname\", String[] { \"myparamvalue\" });\n request = new WrappedRequestWithParameter(httprequest, extraParams);\n }\n chain.doFilter(request, response);\n}\n...\n\nclass WrappedRequestWithParameter extends HttpServletRequestWrapper {\n private final Map<String, String[]> modifiableParameters;\n private Map<String, String[]> allParameters = null;\n\n public WrappedRequestWithParameter(final HttpServletRequest request, final Map<String, String[]> additionalParams) {\n super(request);\n modifiableParameters = new TreeMap<String, String[]>();\n modifiableParameters.putAll(additionalParams);\n }\n\n @Override\n public String getParameter(final String name) {\n String[] strings = getParameterMap().get(name);\n if (strings != null) {\n return strings[0];\n }\n return super.getParameter(name);\n }\n\n @Override\n public Map<String, String[]> getParameterMap() {\n if (allParameters == null) {\n allParameters = new TreeMap<String, String[]>();\n allParameters.putAll(super.getParameterMap());\n allParameters.putAll(modifiableParameters);\n }\n // Return an unmodifiable collection because we need to uphold the interface contract.\n return Collections.unmodifiableMap(allParameters);\n }\n\n @Override\n public Enumeration<String> getParameterNames() {\n return Collections.enumeration(getParameterMap().keySet());\n }\n\n @Override\n public String[] getParameterValues(final String name) {\n return getParameterMap().get(name);\n }\n}\n}\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/190833", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16485/" ]
190,840
<p>I have found some libraries or web services in PHP that does the job. The problem is that the conversion is done when the page is fully loaded, I would like to <strong>convert the page to PDF</strong> <strong>after some content dynamically added via AJAX</strong> in onload event. </p> <p>Thank you very much, Omar</p>
[ { "answer_id": 190889, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 3, "selected": false, "text": "document.getElementsByTagName('html')[0].innerHTML" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/190840", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26779/" ]
190,852
<p>See code: </p> <pre><code>var file1 = "50.xsl"; var file2 = "30.doc"; getFileExtension(file1); //returns xsl getFileExtension(file2); //returns doc function getFileExtension(filename) { /*TODO*/ } </code></pre>
[ { "answer_id": 190864, "author": "p4bl0", "author_id": 12043, "author_profile": "https://Stackoverflow.com/users/12043", "pm_score": 2, "selected": false, "text": "return filename.replace(/\\.([a-zA-Z0-9]+)$/, \"$1\");\n $1" }, { "answer_id": 190878, "author": "Tom", "author_id": 23746, "author_profile": "https://Stackoverflow.com/users/23746", "pm_score": 11, "selected": true, "text": "return filename.split('.').pop();\n return /[^.]+$/.exec(filename);\n return (/[.]/.exec(filename)) ? /[^.]+$/.exec(filename) : undefined;\n" }, { "answer_id": 190879, "author": "Randy Sugianto 'Yuku'", "author_id": 11238, "author_profile": "https://Stackoverflow.com/users/11238", "pm_score": 3, "selected": false, "text": "var parts = filename.split('.');\nreturn parts[parts.length-1];\n" }, { "answer_id": 190933, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 5, "selected": false, "text": "function getFileExtension(filename)\n{\n var ext = /^.+\\.([^.]+)$/.exec(filename);\n return ext == null ? \"\" : ext[1];\n}\n \"a.b\" (=> \"b\") \n\"a\" (=> \"\") \n\".hidden\" (=> \"\") \n\"\" (=> \"\") \nnull (=> \"\") \n \"a.b.c.d\" (=> \"d\")\n\".a.b\" (=> \"b\")\n\"a..b\" (=> \"b\")\n" }, { "answer_id": 191380, "author": "Joe Scylla", "author_id": 25771, "author_profile": "https://Stackoverflow.com/users/25771", "pm_score": 3, "selected": false, "text": "function file_get_ext(filename)\n {\n return typeof filename != \"undefined\" ? filename.substring(filename.lastIndexOf(\".\")+1, filename.length).toLowerCase() : false;\n }\n" }, { "answer_id": 191504, "author": "roenving", "author_id": 23142, "author_profile": "https://Stackoverflow.com/users/23142", "pm_score": 2, "selected": false, "text": "return filename.replace(/^.*?\\.([a-zA-Z0-9]+)$/, \"$1\");\n" }, { "answer_id": 194301, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "function extension(fname) {\n var pos = fname.lastIndexOf(\".\");\n var strlen = fname.length;\n if (pos != -1 && strlen != pos + 1) {\n var ext = fname.split(\".\");\n var len = ext.length;\n var extension = ext[len - 1].toLowerCase();\n } else {\n extension = \"No extension found\";\n }\n return extension;\n}\n" }, { "answer_id": 450308, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "function func() {\n var val = document.frm.filename.value;\n var arr = val.split(\".\");\n alert(arr[arr.length - 1]);\n var arr1 = val.split(\"\\\\\");\n alert(arr1[arr1.length - 2]);\n if (arr[1] == \"gif\" || arr[1] == \"bmp\" || arr[1] == \"jpeg\") {\n alert(\"this is an image file \");\n } else {\n alert(\"this is not an image file\");\n }\n}\n" }, { "answer_id": 1203361, "author": "wallacer", "author_id": 147458, "author_profile": "https://Stackoverflow.com/users/147458", "pm_score": 10, "selected": false, "text": "return filename.split('.').pop();\n return filename.substring(filename.lastIndexOf('.')+1, filename.length) || filename;\n .htaccess \"\" var a = filename.split(\".\");\nif( a.length === 1 || ( a[0] === \"\" && a.length === 2 ) ) {\n return \"\";\n}\nreturn a.pop(); // feel free to tack .toLowerCase() here if you want\n a.length a[0] === \"\" a.length === 2" }, { "answer_id": 5584260, "author": "Justin Bull", "author_id": 229787, "author_profile": "https://Stackoverflow.com/users/229787", "pm_score": 2, "selected": false, "text": "return /[^.]+$/.exec(filename);\n image.jpg?foo=bar\n var trueFileName = parse_url('image.jpg?foo=bar').file;\n" }, { "answer_id": 5973162, "author": "Edward", "author_id": 749852, "author_profile": "https://Stackoverflow.com/users/749852", "pm_score": 2, "selected": false, "text": "function getFileExtension(filename) {\n var fileinput = document.getElementById(filename);\n if (!fileinput)\n return \"\";\n var filename = fileinput.value;\n if (filename.length == 0)\n return \"\";\n var dot = filename.lastIndexOf(\".\");\n if (dot == -1)\n return \"\";\n var extension = filename.substr(dot, filename.length);\n return extension;\n}\n" }, { "answer_id": 7908718, "author": "Dima", "author_id": 1015402, "author_profile": "https://Stackoverflow.com/users/1015402", "pm_score": 5, "selected": false, "text": "function getExt(filename)\n{\n var ext = filename.split('.').pop();\n if(ext == filename) return \"\";\n return ext;\n}\n" }, { "answer_id": 8246456, "author": "Pono", "author_id": 591939, "author_profile": "https://Stackoverflow.com/users/591939", "pm_score": 4, "selected": false, "text": "var extension = fileName.substring(fileName.lastIndexOf('.')+1);\n" }, { "answer_id": 12900504, "author": "VisioN", "author_id": 1249581, "author_profile": "https://Stackoverflow.com/users/1249581", "pm_score": 9, "selected": false, "text": " return fname.slice((fname.lastIndexOf(\".\") - 1 >>> 0) + 2);\n return fname.slice((Math.max(0, fname.lastIndexOf(\".\")) || Infinity) + 1);\n . \"\" --> \"\"\n \"name\" --> \"\"\n \"name.txt\" --> \"txt\"\n \".htpasswd\" --> \"\"\n \"name.with.many.dots.myext\" --> \"myext\"\n String.lastIndexOf \".\" fname -1 -1 0 \"name\" \".htaccess\" >>> -1 4294967295 -2 4294967294 String.prototype.slice \"\" function getExtension(path) {\n var basename = path.split(/[\\\\/]/).pop(), // extract file name from full path ...\n // (supports `\\\\` and `/` separators)\n pos = basename.lastIndexOf(\".\"); // get last position of `.`\n\n if (basename === \"\" || pos < 1) // if file name is empty or ...\n return \"\"; // `.` not found (-1) or comes first (0)\n\n return basename.slice(pos + 1); // extract extension ignoring `.`\n}\n\nconsole.log( getExtension(\"/path/to/file.ext\") );\n// >> \"ext\"\n" }, { "answer_id": 15237857, "author": "crab", "author_id": 899829, "author_profile": "https://Stackoverflow.com/users/899829", "pm_score": 1, "selected": false, "text": "return ( filename.indexOf('.') > 0 ) ? filename.split('.').pop().toLowerCase() : 'undefined';\n" }, { "answer_id": 16518830, "author": "Tamás Pap", "author_id": 240324, "author_profile": "https://Stackoverflow.com/users/240324", "pm_score": 1, "selected": false, "text": "var parts = filename.split('.');\nreturn (parts.length > 1) ? parts.pop() : '';\n" }, { "answer_id": 19086634, "author": "mrbrdo", "author_id": 364812, "author_profile": "https://Stackoverflow.com/users/364812", "pm_score": 3, "selected": false, "text": "(filename.match(/[^\\\\\\/]\\.([^.\\\\\\/]+)$/) || [null]).pop()\n /path/.htaccess => null\n/dir.with.dot/file => null\n" }, { "answer_id": 19185883, "author": "Hussein Nazzal", "author_id": 1743214, "author_profile": "https://Stackoverflow.com/users/1743214", "pm_score": 3, "selected": false, "text": "fileName.slice(fileName.lastIndexOf('.'))\n function getExtention(fileName){\n var i = fileName.lastIndexOf('.');\n if(i === -1 ) return false;\n return fileName.slice(i)\n }\n" }, { "answer_id": 20427027, "author": "Chathuranga", "author_id": 1386503, "author_profile": "https://Stackoverflow.com/users/1386503", "pm_score": 0, "selected": false, "text": "var filetypeArray = (file.type).split(\"/\");\nvar filetype = filetypeArray[1];\n" }, { "answer_id": 25483772, "author": "Krisztián Balla", "author_id": 434742, "author_profile": "https://Stackoverflow.com/users/434742", "pm_score": 2, "selected": false, "text": "var file1 = \"50.xsl\";\n\nif (file1.substr(-4) == '.xsl') {\n // do something\n}\n" }, { "answer_id": 31223829, "author": "DzSoundNirvana", "author_id": 2510099, "author_profile": "https://Stackoverflow.com/users/2510099", "pm_score": 2, "selected": false, "text": "var fileName = \"I.Am.FileName.docx\";\nvar nameLen = fileName.length;\nvar lastDotPos = fileName.lastIndexOf(\".\");\nvar fileNameSub = false;\nif(lastDotPos === -1)\n{\n fileNameSub = false;\n}\nelse\n{\n //Remove +1 if you want the \".\" left too\n fileNameSub = fileName.substr(lastDotPos + 1, nameLen);\n}\ndocument.getElementById(\"showInMe\").innerHTML = fileNameSub; <div id=\"showInMe\"></div>" }, { "answer_id": 31649732, "author": "Jibesh Patra", "author_id": 1849454, "author_profile": "https://Stackoverflow.com/users/1849454", "pm_score": 1, "selected": false, "text": "var file1 =\"50.xsl\";\nvar path = require('path');\nconsole.log(path.parse(file1).name);\n" }, { "answer_id": 35526475, "author": "Labithiotis", "author_id": 1872133, "author_profile": "https://Stackoverflow.com/users/1872133", "pm_score": 2, "selected": false, "text": "string.match(/(.*)\\??/i).shift().replace(/\\?.*/, '').split('.').pop()\n\n// Example\n// some.url.com/with.in/&ot.s/files/file.jpg?spec=1&.ext=jpg\n// jpg\n" }, { "answer_id": 36464585, "author": "NSD", "author_id": 3476304, "author_profile": "https://Stackoverflow.com/users/3476304", "pm_score": 1, "selected": false, "text": "var file = \"hello.txt\";\nvar ext = (function(file, lio) { \n return lio === -1 ? undefined : file.substring(lio+1); \n})(file, file.lastIndexOf(\".\"));\n\n// hello.txt -> txt\n// hello.dolly.txt -> txt\n// hello -> undefined\n// .hello -> hello\n" }, { "answer_id": 38285146, "author": "Jack", "author_id": 1492329, "author_profile": "https://Stackoverflow.com/users/1492329", "pm_score": 3, "selected": false, "text": "/**\n * Extract file extension from URL.\n * @param {String} url\n * @returns {String} File extension or empty string if no extension is present.\n */\nvar getFileExtension = function (url) {\n \"use strict\";\n if (url === null) {\n return \"\";\n }\n var index = url.lastIndexOf(\"/\");\n if (index !== -1) {\n url = url.substring(index + 1); // Keep path without its segments\n }\n index = url.indexOf(\"?\");\n if (index !== -1) {\n url = url.substring(0, index); // Remove query\n }\n index = url.indexOf(\"#\");\n if (index !== -1) {\n url = url.substring(0, index); // Remove fragment\n }\n index = url.lastIndexOf(\".\");\n return index !== -1\n ? url.substring(index + 1) // Only keep file extension\n : \"\"; // No extension found\n};\n \"https://www.example.com:8080/segment1/segment2/page.html?foo=bar#fragment\" --> \"html\"\n\"https://www.example.com:8080/segment1/segment2/page.html#fragment\" --> \"html\"\n\"https://www.example.com:8080/segment1/segment2/.htaccess?foo=bar#fragment\" --> \"htaccess\"\n\"https://www.example.com:8080/segment1/segment2/page?foo=bar#fragment\" --> \"\"\n\"https://www.example.com:8080/segment1/segment2/?foo=bar#fragment\" --> \"\"\n\"\" --> \"\"\nnull --> \"\"\n\"a.b.c.d\" --> \"d\"\n\".a.b\" --> \"b\"\n\".a.b.\" --> \"\"\n\"a...b\" --> \"b\"\n\"...\" --> \"\"\n" }, { "answer_id": 45925016, "author": "Vitim.us", "author_id": 938822, "author_profile": "https://Stackoverflow.com/users/938822", "pm_score": 3, "selected": false, "text": "function extension(filename) {\n var r = /.+\\.(.+)$/.exec(filename);\n return r ? r[1] : null;\n}\n /* tests */\ntest('cat.gif', 'gif');\ntest('main.c', 'c');\ntest('file.with.multiple.dots.zip', 'zip');\ntest('.htaccess', null);\ntest('noextension.', null);\ntest('noextension', null);\ntest('', null);\n\n// test utility function\nfunction test(input, expect) {\n var result = extension(input);\n if (result === expect)\n console.log(result, input);\n else\n console.error(result, input);\n}\n\nfunction extension(filename) {\n var r = /.+\\.(.+)$/.exec(filename);\n return r ? r[1] : null;\n}" }, { "answer_id": 47523422, "author": "James Anderson Jr.", "author_id": 2690928, "author_profile": "https://Stackoverflow.com/users/2690928", "pm_score": 3, "selected": false, "text": "# ? function \"\" function getFileExtension(fileNameOrURL, showUnixDotFiles)\n {\n /* First, let's declare some preliminary variables we'll need later on. */\n var fileName;\n var fileExt;\n \n /* Now we'll create a hidden anchor ('a') element (Note: No need to append this element to the document). */\n var hiddenLink = document.createElement('a');\n \n /* Just for fun, we'll add a CSS attribute of [ style.display = \"none\" ]. Remember: You can never be too sure! */\n hiddenLink.style.display = \"none\";\n \n /* Set the 'href' attribute of the hidden link we just created, to the 'fileNameOrURL' argument received by this function. */\n hiddenLink.setAttribute('href', fileNameOrURL);\n \n /* Now, let's take advantage of the browser's built-in parser, to remove elements from the original 'fileNameOrURL' argument received by this function, without actually modifying our newly created hidden 'anchor' element.*/ \n fileNameOrURL = fileNameOrURL.replace(hiddenLink.protocol, \"\"); /* First, let's strip out the protocol, if there is one. */\n fileNameOrURL = fileNameOrURL.replace(hiddenLink.hostname, \"\"); /* Now, we'll strip out the host-name (i.e. domain-name) if there is one. */\n fileNameOrURL = fileNameOrURL.replace(\":\" + hiddenLink.port, \"\"); /* Now finally, we'll strip out the port number, if there is one (Kinda overkill though ;-)). */ \n \n /* Now, we're ready to finish processing the 'fileNameOrURL' variable by removing unnecessary parts, to isolate the file name. */\n \n /* Operations for working with [relative, root-relative, and absolute] URL's ONLY [BEGIN] */ \n \n /* Break the possible URL at the [ '?' ] and take first part, to shave of the entire query string ( everything after the '?'), if it exist. */\n fileNameOrURL = fileNameOrURL.split('?')[0];\n\n /* Sometimes URL's don't have query's, but DO have a fragment [ # ](i.e 'reference anchor'), so we should also do the same for the fragment tag [ # ]. */\n fileNameOrURL = fileNameOrURL.split('#')[0];\n\n /* Now that we have just the URL 'ALONE', Let's remove everything to the last slash in URL, to isolate the file name. */\n fileNameOrURL = fileNameOrURL.substr(1 + fileNameOrURL.lastIndexOf(\"/\"));\n\n /* Operations for working with [relative, root-relative, and absolute] URL's ONLY [END] */ \n\n /* Now, 'fileNameOrURL' should just be 'fileName' */\n fileName = fileNameOrURL;\n \n /* Now, we check if we should show UNIX dot-files, or not. This should be either 'true' or 'false'. */ \n if ( showUnixDotFiles == false )\n {\n /* If not ('false'), we should check if the filename starts with a period (indicating it's a UNIX dot-file). */\n if ( fileName.startsWith(\".\") )\n {\n /* If so, we return a blank string to the function caller. Our job here, is done! */\n return \"\";\n };\n };\n \n /* Now, let's get everything after the period in the filename (i.e. the correct 'file extension'). */\n fileExt = fileName.substr(1 + fileName.lastIndexOf(\".\"));\n\n /* Now that we've discovered the correct file extension, let's return it to the function caller. */\n return fileExt;\n };\n" }, { "answer_id": 47734420, "author": "Jakob Sternberg", "author_id": 1576463, "author_profile": "https://Stackoverflow.com/users/1576463", "pm_score": 4, "selected": false, "text": "function getExt(filepath){\n return filepath.split(\"?\")[0].split(\"#\")[0].split('.').pop();\n}\n\ngetExt(\"../js/logic.v2.min.js\") // js\ngetExt(\"http://example.net/site/page.php?id=16548\") // php\ngetExt(\"http://example.net/site/page.html#welcome.to.me\") // html\ngetExt(\"c:\\\\logs\\\\yesterday.log\"); // log\n" }, { "answer_id": 49506631, "author": "GauRang Omar", "author_id": 6653785, "author_profile": "https://Stackoverflow.com/users/6653785", "pm_score": 2, "selected": false, "text": "fetchFileExtention(fileName) {\n return fileName.slice((fileName.lastIndexOf(\".\") - 1 >>> 0) + 2);\n}\n" }, { "answer_id": 50826632, "author": "omarjebari", "author_id": 2867894, "author_profile": "https://Stackoverflow.com/users/2867894", "pm_score": 0, "selected": false, "text": "function getExtensionFromFilename(filename) {\n let extension = '';\n if (filename > '') {\n let parts = _.split(filename, '.');\n if (parts.length >= 2) {\n extension = _.last(parts);\n }\n return extension;\n}\n" }, { "answer_id": 52738209, "author": "sdgfsdh", "author_id": 1256041, "author_profile": "https://Stackoverflow.com/users/1256041", "pm_score": 5, "selected": false, "text": "path import path from 'path';\n\nconsole.log(path.extname('abc.txt'));\n path.extname('abc.txt').slice(1) // 'txt'\n path.extname('abc') // ''\n path path" }, { "answer_id": 53048066, "author": "boehm_s", "author_id": 4756304, "author_profile": "https://Stackoverflow.com/users/4756304", "pm_score": 3, "selected": false, "text": "reduce var str = \"filename.with_dot.png\";\nvar [filename, extension] = str.split('.').reduce((acc, val, i, arr) => (i == arr.length - 1) ? [acc[0].substring(1), val] : [[acc[0], val].join('.')], [])\n\nconsole.log({filename, extension}); var str = \"filename.with_dot.png\";\nvar [filename, extension] = str.split('.')\n .reduce((acc, val, i, arr) => (i == arr.length - 1) \n ? [acc[0].substring(1), val] \n : [[acc[0], val].join('.')], [])\n\n\nconsole.log({filename, extension});\n\n// {\n// \"filename\": \"filename.with_dot\",\n// \"extension\": \"png\"\n// }\n" }, { "answer_id": 53590524, "author": "山茶树和葡萄树", "author_id": 5819157, "author_profile": "https://Stackoverflow.com/users/5819157", "pm_score": 3, "selected": false, "text": "// 获取文件后缀名\nfunction getFileExtension(file) {\n var regexp = /\\.([0-9a-z]+)(?:[\\?#]|$)/i;\n var extension = file.match(regexp);\n return extension && extension[1];\n}\n\nconsole.log(getFileExtension(\"https://www.example.com:8080/path/name/foo\"));\nconsole.log(getFileExtension(\"https://www.example.com:8080/path/name/foo.BAR\"));\nconsole.log(getFileExtension(\"https://www.example.com:8080/path/name/.quz/foo.bar?key=value#fragment\"));\nconsole.log(getFileExtension(\"https://www.example.com:8080/path/name/.quz.bar?key=value#fragment\"));" }, { "answer_id": 58954791, "author": "Josh", "author_id": 7066622, "author_profile": "https://Stackoverflow.com/users/7066622", "pm_score": 1, "selected": false, "text": "function getFileExtension(path: string): string {\n var regexp = /\\.([0-9a-z]+)(?:[\\?#]|$)/i\n var extension = path.match(regexp)\n return extension && extension[1]\n}\n" }, { "answer_id": 61666295, "author": "manoj patel", "author_id": 11984368, "author_profile": "https://Stackoverflow.com/users/11984368", "pm_score": 1, "selected": false, "text": "var filename = \"my.filehere.txt\";\n\nfile_name = filename.replace('.'+filename.split('.').pop(),'');\n\nconsole.log(\"Filename =>\"+file_name);\n extension = filename.split('.').pop();\nconsole.log(\"Extension =>\"+extension);\n" }, { "answer_id": 62803788, "author": "Mateja Petrovic", "author_id": 8809024, "author_profile": "https://Stackoverflow.com/users/8809024", "pm_score": 3, "selected": false, "text": "const path = 'hello.world.txt'\nconst [extension, ...nameParts] = path.split('.').reverse();\nconsole.log('extension:', extension);" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/190852", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2138/" ]
190,876
<p>I have a few combo-boxes and double spin boxes on my Qt Dialog. Now I need a "ResetToDefault" item on a menu that comes up when you right click on the widget (spin box or combo box).</p> <p>How do i get it. Is there some way I can have a custom menu that comes up on right click or Is there a way i can add items to the menu that comes on right click.</p>
[ { "answer_id": 190895, "author": "PierreBdR", "author_id": 7136, "author_profile": "https://Stackoverflow.com/users/7136", "pm_score": 4, "selected": true, "text": "addAction contextMenuPolicy Qt::ActionsContextMenu QAction *reset_act = new QAction(\"Reset to default\");\nmywidget->addAction(reset_act);\nmywidget->setContextMenuPolicy(Qt::ActionsContextMenu);\n// here connect the 'triggered' signal to some slot\n QWidget::childAt" }, { "answer_id": 191228, "author": "David Dibben", "author_id": 5022, "author_profile": "https://Stackoverflow.com/users/5022", "pm_score": 1, "selected": false, "text": "class MyLineEdit : public QLineEdit\n{\n Q_OBJECT\npublic:\n\n MyLineEdit(QWidget* parent = 0) : QLineEdit(parent){}\n\n void contextMenuEvent(QContextMenuEvent *event)\n {\n QPointer<QMenu> menu = createStandardContextMenu();\n //add your actions here\n menu->exec(event->globalPos());\n delete menu;\n }\n\n};\n MyLineEdit* edit = new MyLineEdit();\ncomboBox->setLineEdit(edit);\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/190876", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11212/" ]
190,890
<p>does it matter at all what order the <code>&lt;link&gt;</code> or <code>&lt;script&gt;</code> or <code>&lt;meta&gt;</code> tags are in in the <code>&lt;head&gt;&lt;/head&gt;</code>?</p> <p>(daft question but one of those things i've never given any thought to until now.)</p>
[ { "answer_id": 190899, "author": "Joe Lencioni", "author_id": 18986, "author_profile": "https://Stackoverflow.com/users/18986", "pm_score": 5, "selected": false, "text": "h1 { color: #f00; }\n h1 { color: #00f; }\n h1 #00f" }, { "answer_id": 190902, "author": "Adhip Gupta", "author_id": 384, "author_profile": "https://Stackoverflow.com/users/384", "pm_score": 2, "selected": false, "text": "<script> <head> <link>" }, { "answer_id": 191745, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 5, "selected": true, "text": "<meta http-equiv=\"Content-Type\" … meta" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/190890", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26107/" ]
190,908
<p>When you tap a row in a <code>UITableView</code>, the row is highlighted and selected. Is it possible to disable this so tapping a row does nothing?</p>
[ { "answer_id": 191245, "author": "Martin Gordon", "author_id": 2481, "author_profile": "https://Stackoverflow.com/users/2481", "pm_score": 11, "selected": false, "text": "UITableViewCell cell.selectionStyle = UITableViewCellSelectionStyleNone;\n [cell setSelectionStyle:UITableViewCellSelectionStyleNone];\n cell.selectionStyle = UITableViewCellSelectionStyle.None\n cell.selectionStyle = .none\n -tableView:didSelectRowAtIndexPath:" }, { "answer_id": 1062825, "author": "user41806", "author_id": 41806, "author_profile": "https://Stackoverflow.com/users/41806", "pm_score": 5, "selected": false, "text": "UITableViewDelegate willSelectRowAtIndexPath return nil willDeselectRowAtIndexPath return nil" }, { "answer_id": 1166670, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 10, "selected": true, "text": "tableView.allowsSelection = false\n didSelectRowAt# UIButton didSelectRowAt# UITableView tableView.allowsSelectionDuringEditing = false \n" }, { "answer_id": 6154555, "author": "Denis Kutlubaev", "author_id": 751641, "author_profile": "https://Stackoverflow.com/users/751641", "pm_score": 4, "selected": false, "text": "cell.selected = NO;\n override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {\n let r = indexPath.row\n print(\"clicked .. \\(r)\")\n tableView.cellForRow(at: indexPath)?.setSelected(false, animated: true)\n}\n" }, { "answer_id": 6201993, "author": "JosephH", "author_id": 292166, "author_profile": "https://Stackoverflow.com/users/292166", "pm_score": 7, "selected": false, "text": "cell.userInteractionEnabled = NO;\n [cell setSelectionStyle:UITableViewCellSelectionStyleNone];\n - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath tableView.allowsSelection = NO;\n" }, { "answer_id": 6305493, "author": "mbm29414", "author_id": 394484, "author_profile": "https://Stackoverflow.com/users/394484", "pm_score": 9, "selected": false, "text": "[cell setSelectionStyle:UITableViewCellSelectionStyleNone];\n tableView:didSelectRowAtIndexPath: - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {\n // A case was selected, so push into the CaseDetailViewController\n UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];\n if (cell.selectionStyle != UITableViewCellSelectionStyleNone) {\n // Handle tap code here\n }\n}\n [tableView setAllowsSelection:NO];\n UITableViewCell [cell setUserInteractionEnabled:NO];\n [tableView setUserInteractionEnabled:NO];\n UITableViewDelegate - (BOOL)tableView:(UITableView *)tableView \n shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath\n" }, { "answer_id": 9852081, "author": "iDhaval", "author_id": 921510, "author_profile": "https://Stackoverflow.com/users/921510", "pm_score": 4, "selected": false, "text": " cell.selectionStyle = UITableViewCellSelectionStyleNone;\n" }, { "answer_id": 11390674, "author": "v_1", "author_id": 1642772, "author_profile": "https://Stackoverflow.com/users/1642772", "pm_score": 3, "selected": false, "text": "cell.selectionStyle = UITableViewCellSelectionStyleNone;\n [cell setSelectionStyle:UITableViewCellSelectionStyleNone];\n" }, { "answer_id": 13167946, "author": "cbowns", "author_id": 774, "author_profile": "https://Stackoverflow.com/users/774", "pm_score": 6, "selected": false, "text": "UITableViewDelegate tableView:shouldHighlightRowAtIndexPath: userInteractionEnabled = NO" }, { "answer_id": 13363194, "author": "Chris Fox", "author_id": 1119654, "author_profile": "https://Stackoverflow.com/users/1119654", "pm_score": 5, "selected": false, "text": "didSelectRowAtIndexPath\n [tableView deselectRowAtIndexPath:indexPath animated:YES];\n" }, { "answer_id": 13910050, "author": "Aniruddh", "author_id": 530432, "author_profile": "https://Stackoverflow.com/users/530432", "pm_score": 2, "selected": false, "text": "cell.userInteractionEnabled = NO;\n didSelectRowAtIndexPath:" }, { "answer_id": 14147268, "author": "Yarek T", "author_id": 274503, "author_profile": "https://Stackoverflow.com/users/274503", "pm_score": 4, "selected": false, "text": "UITableViewCell userInteractionEnabled - (NSIndexPath *)tableView: (UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {\n if (indexPath.row == 2) {\n return nil;\n }\n return indexPath;\n}\n" }, { "answer_id": 14390807, "author": "Sharme", "author_id": 867280, "author_profile": "https://Stackoverflow.com/users/867280", "pm_score": 3, "selected": false, "text": "cell.selectionStyle = UITableViewCellSelectionStyleNone;\n cell.userInteractionEnabled = NO;\n" }, { "answer_id": 16214897, "author": "ashevin", "author_id": 867943, "author_profile": "https://Stackoverflow.com/users/867943", "pm_score": 2, "selected": false, "text": "- (void) setHighlighted:(BOOL)highlighted\n{\n}\n\n- (void) setHighlighted:(BOOL)highlighted animated:(BOOL)animated\n{\n}\n\n- (void) setSelected:(BOOL)selected animated:(BOOL)animated\n{\n}\n" }, { "answer_id": 16215743, "author": "vignesh kumar", "author_id": 1211532, "author_profile": "https://Stackoverflow.com/users/1211532", "pm_score": 6, "selected": false, "text": "NoSelection selection" }, { "answer_id": 16479416, "author": "iEinstein", "author_id": 1603461, "author_profile": "https://Stackoverflow.com/users/1603461", "pm_score": 3, "selected": false, "text": "cell.selectionStyle = UITableViewCellSelectionStyleNone;\n" }, { "answer_id": 18345211, "author": "Steve Barden", "author_id": 974035, "author_profile": "https://Stackoverflow.com/users/974035", "pm_score": 3, "selected": false, "text": "cell.selectionStyle = UITableViewCellSelectionStyleNone;\n - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {\n [tableView deselectRowAtIndexPath:indexPath animated:NO];\n...\n}\n" }, { "answer_id": 18429455, "author": "Harini", "author_id": 980918, "author_profile": "https://Stackoverflow.com/users/980918", "pm_score": 3, "selected": false, "text": "[cell setSelectionStyle:UITableViewCellSelectionStyleNone];\n" }, { "answer_id": 19246155, "author": "Mak083", "author_id": 2724163, "author_profile": "https://Stackoverflow.com/users/2724163", "pm_score": 3, "selected": false, "text": "[cell setSelectionStyle:UITableViewCellSelectionStyleNone];\n" }, { "answer_id": 21104706, "author": "virindh", "author_id": 1418074, "author_profile": "https://Stackoverflow.com/users/1418074", "pm_score": 3, "selected": false, "text": "UITableViewCellSelectionStyleNone UITableViewCellSelectionStyleNone UIView *backgroundColorView = [[UIView alloc] init];\nbackgroundColorView.backgroundColor = [UIColor clearColor];\nbackgroundColorView.layer.masksToBounds = YES;\n[cell setSelectedBackgroundView: backgroundColorView];\n" }, { "answer_id": 22987593, "author": "iDeveloper", "author_id": 2417281, "author_profile": "https://Stackoverflow.com/users/2417281", "pm_score": 3, "selected": false, "text": "cell.selectionStyle = UITableViewCellSelectionStyleNone;\n" }, { "answer_id": 24711398, "author": "Programming Learner", "author_id": 2484878, "author_profile": "https://Stackoverflow.com/users/2484878", "pm_score": 3, "selected": false, "text": "cell.selectionStyle = UITableViewCellSelectionStyleNone;\n [tableView deselectRowAtIndexPath:indexPath animated:NO];\n" }, { "answer_id": 25059393, "author": "Rinku Sadhwani", "author_id": 1037317, "author_profile": "https://Stackoverflow.com/users/1037317", "pm_score": 3, "selected": false, "text": "UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];\n[cell setSelected:NO animated:NO];\n[cell setHighlighted:NO animated:NO];\n" }, { "answer_id": 27076003, "author": "Arun Gupta", "author_id": 1732743, "author_profile": "https://Stackoverflow.com/users/1732743", "pm_score": 4, "selected": false, "text": "didSelectRowAtIndexPath didSelectRowAtIndexPath UITextField self.tableView.allowsSelection = NO;\n didSelectRowAtIndexPath cellForRowAtIndexPath cell.selectionStyle = UITableViewCellSelectionStyleNone;\n buttons textfields self.tableView.userInteractionEnabled = false;\n Swift Objective-C self.tableView.allowsSelection = false\n cell?.selectionStyle = UITableViewCellSelectionStyle.None\n self.tableView.userInteractionEnabled = false\n" }, { "answer_id": 27246135, "author": "Aks", "author_id": 1326339, "author_profile": "https://Stackoverflow.com/users/1326339", "pm_score": 5, "selected": false, "text": "cell.selectionStyle = .none\n cell.selectionStyle = .None\n" }, { "answer_id": 28602027, "author": "Zorayr", "author_id": 577878, "author_profile": "https://Stackoverflow.com/users/577878", "pm_score": 3, "selected": false, "text": "import Foundation\n\nclass CustomTableViewCell: UITableViewCell\n{\n required init(coder aDecoder: NSCoder)\n {\n fatalError(\"init(coder:) has not been implemented\")\n }\n\n override init(style: UITableViewCellStyle, reuseIdentifier: String?)\n {\n super.init(style: style, reuseIdentifier: reuseIdentifier)\n self.selectionStyle = UITableViewCellSelectionStyle.None\n } \n}\n" }, { "answer_id": 29339444, "author": "parvind", "author_id": 452344, "author_profile": "https://Stackoverflow.com/users/452344", "pm_score": 5, "selected": false, "text": "UITableViewCell cell.selectionStyle = UITableViewCellSelectionStyleNone;\n [cell setSelectionStyle:UITableViewCellSelectionStyleNone];\n cell.selectionStyle = UITableViewCellSelectionStyle.None\n cell.selectionStyle = .none\n tableView:didSelectRowAtIndexPath: delegate func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {\n\n\n let cell = tableView.dequeueReusableCell(withIdentifier: \"OpenTbCell\") as! OpenTbCell\n cell.selectionStyle = .none\n return cell\n\n\n}\n" }, { "answer_id": 29343919, "author": "Ahsan Ebrahim", "author_id": 1825707, "author_profile": "https://Stackoverflow.com/users/1825707", "pm_score": 5, "selected": false, "text": "cellForRowAtIndexPath cell.selectionStyle = UITableViewCellSelectionStyleNone;\n" }, { "answer_id": 30255373, "author": "Jayprakash Dubey", "author_id": 1753005, "author_profile": "https://Stackoverflow.com/users/1753005", "pm_score": 3, "selected": false, "text": " cell.selectionStyle = UITableViewCellSelectionStyleNone;\n [cell setSelectionStyle:UITableViewCellSelectionStyleNone];\n - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { ... }\n" }, { "answer_id": 33214518, "author": "priyanka gautam", "author_id": 5358005, "author_profile": "https://Stackoverflow.com/users/5358005", "pm_score": 3, "selected": false, "text": "cell?.selectionStyle = UITableViewCellSelectionStyle.None\n" }, { "answer_id": 37290839, "author": "Gaurav Patel", "author_id": 6021734, "author_profile": "https://Stackoverflow.com/users/6021734", "pm_score": 4, "selected": false, "text": "cell.selectionStyle = UITableViewCellSelectionStyle.None\n" }, { "answer_id": 39868238, "author": "Mohammad Zaid Pathan", "author_id": 3411787, "author_profile": "https://Stackoverflow.com/users/3411787", "pm_score": 5, "selected": false, "text": "UITableViewCell Selection None" }, { "answer_id": 41525449, "author": "MANISH PATHAK", "author_id": 729179, "author_profile": "https://Stackoverflow.com/users/729179", "pm_score": 6, "selected": false, "text": "cell.selectionStyle = .none\n" }, { "answer_id": 52328730, "author": "Praful Argiddi", "author_id": 9528204, "author_profile": "https://Stackoverflow.com/users/9528204", "pm_score": 2, "selected": false, "text": " func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {\n\n\n let cell = tableView.dequeueReusableCell(withIdentifier: \"OpenTbCell\") as! OpenTbCell\n cell.selectionStyle = .none\n return cell\n\n\n}\n" }, { "answer_id": 57196754, "author": "vrat2801", "author_id": 6593648, "author_profile": "https://Stackoverflow.com/users/6593648", "pm_score": 2, "selected": false, "text": "cell.selectionStyle = UITableViewCellSelectionStyleNone;\n cell.selectionStyle = .none\n self.tableView.allowsSelection = false;\n self.tableView.allowsSelection = false\n" }, { "answer_id": 57266532, "author": "Muhammad Ahmad", "author_id": 11468227, "author_profile": "https://Stackoverflow.com/users/11468227", "pm_score": 1, "selected": false, "text": "cell.selectionStyle = .none" }, { "answer_id": 59747207, "author": "Abdul Karim Khan", "author_id": 10118612, "author_profile": "https://Stackoverflow.com/users/10118612", "pm_score": 4, "selected": false, "text": "cellForRowAt let cell = tableView.dequeueReusableCell(withIdentifier: \"YOUR_CELL_IDENTIFIER\", for: indexPath) \ncell.selectionStyle = .none\nreturn cell\n" }, { "answer_id": 63336051, "author": "Rashid Latif", "author_id": 10383865, "author_profile": "https://Stackoverflow.com/users/10383865", "pm_score": 4, "selected": false, "text": "UITableViewCell UITableViewCell MyCell awakeFromNib self.selectionStyle = .none class MyCell: UITableViewCell {\n \n override func awakeFromNib() {\n super.awakeFromNib()\n self.selectionStyle = .none\n }\n \n}\n" }, { "answer_id": 64462157, "author": "testing", "author_id": 11841585, "author_profile": "https://Stackoverflow.com/users/11841585", "pm_score": 3, "selected": false, "text": "tableView.allowsSelection = false\n cell.selectionStyle = UITableViewCell.SelectionStyle.none\n" }, { "answer_id": 67984268, "author": "André Herculano", "author_id": 1244883, "author_profile": "https://Stackoverflow.com/users/1244883", "pm_score": 2, "selected": false, "text": "tableView.allowSelection = false\n public func tableView(_ tableView: UITableView, canFocusRowAt indexPath: IndexPath) -> Bool {\n true\n}\n cell.selectionStyle = .none allowSelection = false" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/190908", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2183/" ]
190,912
<p>I've run into a problem where I'm getting two printouts of my /etc/motd file on Gentoo Linux. sshd is doing one of the printouts, and I can toggle that by configuring /etc/ssh/sshd_config, but I can't find out who's printing the second copy. I can't disable sshd from printing out the motd due to an audit requirement. I'm running the bash shell, for what it's worth</p> <p>Any ideas who's printing the second copy? I don't think it's bash, as when I change /etc/passwd to use /bin/ksh for my shell, I still get the motd displayed.</p> <p>It's not /etc/issue, as that contains the string "This is \n (\s \m \r) (\l)", which is printed only when you're sitting in front of the machine.</p>
[ { "answer_id": 682647, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "session required pam_env.so\n#session optional pam_lastlog.so\nsession include system-auth\n#session optional pam_motd.so motd=/etc/motd\nsession optional pam_mail.so\n" }, { "answer_id": 19142798, "author": "Rob Kennedy", "author_id": 33732, "author_profile": "https://Stackoverflow.com/users/33732", "pm_score": 1, "selected": false, "text": "Banner Banner /etc/motd\n Banner PrintMotd PrintMotd no\n" }, { "answer_id": 32452888, "author": "oscaroscar", "author_id": 1099483, "author_profile": "https://Stackoverflow.com/users/1099483", "pm_score": 2, "selected": false, "text": "noupdate # Print the message of the day upon successful login.\n# This includes a dynamically generated part from /run/motd.dynamic\n# and a static (admin-editable) part from /etc/motd.\nsession optional pam_motd.so motd=/run/motd.dynamic\n#session optional pam_motd.so noupdate\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/190912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9816/" ]
190,914
<p>I have a DataGridView which shows the content of a DataTable.</p> <p>I want to set the backcolor of a row based on the value of a cell in this row.</p> <p>Note that the cell in question is in a column which is not displayed in the DataGridView (Visible=False).</p>
[ { "answer_id": 190932, "author": "Jason Stevenson", "author_id": 13368, "author_profile": "https://Stackoverflow.com/users/13368", "pm_score": 2, "selected": false, "text": "protected void Page_Load(object sender, EventArgs e)\n{\n GridView g1 = new GridView();\n g1.RowDataBound += new GridViewRowEventHandler(g1_RowDataBound);\n}\n\nvoid g1_RowDataBound(object sender, GridViewRowEventArgs e)\n{\n if(e.Row.RowType == DataControlRowType.DataRow)\n {\n // Check the Value\n if(e.Row.Cells[1].Text = someValue)\n {\n e.Row.Cells[1].CssClass = \"colorCellRed\";\n }\n\n }\n}\n" }, { "answer_id": 3246896, "author": "Mr.Mindor", "author_id": 391656, "author_profile": "https://Stackoverflow.com/users/391656", "pm_score": 1, "selected": false, "text": " private void dataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)\n {\n if (((MyDataObject)dataGridView.Rows[e.RowIndex].DataBoundItem).Condition == Value)\n {\n e.CellStyle.BackColor = System.Drawing.Color.Gold;\n\n }\n }\n private void dataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)\n {\n if (dataGridView[\"ColumnName\", e.RowIndex].Value).Condition == TargetValue)\n {\n e.CellStyle.BackColor = System.Drawing.Color.Gold;\n\n }\n }\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/190914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15928/" ]
190,915
<p>I am writing a UDF for Excel 2007 which I want to pass a table to, and then reference parts of that table in the UDF. So, for instance my table called "Stock" may look something like this:</p> <blockquote> <p>Name &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Cost &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Items in Stock</p> <p>Teddy Bear &nbsp;&nbsp;&nbsp;£10&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;10</p> <p>Lollipops &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;20p&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;1000</p> </blockquote> <p>I have a UDF which I want to calculate the total cost of all the items left in stock (the actual example is much more complex which can't really be done without very complex formula)</p> <p>Ideally the syntax of for the UDF would look something like</p> <pre><code>TOTALPRICE(Stock) </code></pre> <p>Which from what I can work out would mean the UDF would have the signature</p> <pre><code>Function TOTALPRICE(table As Range) As Variant </code></pre> <p>What I am having trouble with is how to reference the columns of the table and iterate through them. Ideally I'd like to be able to do it referencing the column headers (so something like table[Cost]).</p>
[ { "answer_id": 190968, "author": "Mike Woodhouse", "author_id": 1060, "author_profile": "https://Stackoverflow.com/users/1060", "pm_score": 2, "selected": true, "text": "Public Function TotalPrice(table As Range) As Variant\n\nDim row As Long, col As Long\nDim total As Double\n\n For row = 2 To table.Rows.Count\n For col = 2 To table.Columns.Count\n TotalPrice = TotalPrice + table.Cells(row, col) * table.Cells(row, col + 1)\n Next\n Next\n\nEnd Function\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/190915", "https://Stackoverflow.com", "https://Stackoverflow.com/users/214/" ]
190,936
<p>When I type 'from' (in a <a href="http://en.wikipedia.org/wiki/Language_Integrated_Query" rel="nofollow noreferrer">LINQ</a> query) after importing <a href="http://msdn.microsoft.com/en-us/library/system.linq.aspx" rel="nofollow noreferrer">System.Linq namespace</a>, it is understood as a keyword. How does this magic happen?</p> <p>Is 'from' a extension method on some type?</p>
[ { "answer_id": 190948, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 4, "selected": true, "text": "var qry = from cust in db.Customers\n where cust.IsActive\n select cust;\n var qry = db.Customers.Where(cust => cust.IsActive);\n IEnumerable<T> IQueryable<T> Enumerable Queryable" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/190936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26788/" ]
190,937
<p>I'm looking for a way to create an "it will look cool" effect for a full screen WPF application I'm working on - a "screen glint" effect that animates or moves across the whole screen to give off a shiny display experience. I'm thinking of creating a large rectangle with a highlighted-gradient and transparent background, which could be animated across the screen. Any ideas how this can be done effectively in XAML?</p>
[ { "answer_id": 218326, "author": "Johan Danforth", "author_id": 6415, "author_profile": "https://Stackoverflow.com/users/6415", "pm_score": 4, "selected": true, "text": "<Window\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n x:Class=\"ScreenGlintApplication.Window1\"\n x:Name=\"Window\"\n Title=\"Window1\"\n Width=\"500\" Height=\"250\" Background=\"#FF000000\" Foreground=\"#FF3EE229\" >\n\n <Grid x:Name=\"LayoutRoot\">\n <TextBlock TextWrapping=\"Wrap\" FontSize=\"40\" >\n <Run Text=\"This is some sample text to have something to work with. Have a nice day! /Johan\"/>\n </TextBlock>\n <Canvas Panel.ZIndex=\"99\" >\n <Rectangle x:Name=\"ScreenGlintRect\" \n Width=\"{Binding Path=ActualWidth, ElementName=Window, Mode=Default}\" \n Height=\"{Binding Path=ActualHeight, ElementName=Window, Mode=Default}\" \n Opacity=\"0.4\" >\n <Rectangle.Triggers> \n <EventTrigger RoutedEvent=\"Rectangle.Loaded\"> \n <BeginStoryboard> \n <Storyboard> \n <DoubleAnimation Storyboard.TargetName=\"ScreenGlintRect\" \n Storyboard.TargetProperty=\"(Canvas.Left)\"\n From=\"-500\" To=\"1000\" Duration=\"0:0:2\" />\n </Storyboard> \n </BeginStoryboard> \n </EventTrigger> \n </Rectangle.Triggers> \n\n <Rectangle.Fill>\n <LinearGradientBrush StartPoint=\"0,1\" EndPoint=\"1,1\">\n <GradientStop Color=\"Transparent\" Offset=\"0.0\" />\n <GradientStop x:Name=\"GlintColor\" Color=\"LightGreen\" Offset=\"0.50\" />\n <GradientStop Color=\"Transparent\" Offset=\"1\" />\n </LinearGradientBrush>\n </Rectangle.Fill>\n </Rectangle>\n </Canvas>\n </Grid>\n</Window>\n ScreenGlintRect.Width = Width;\n ScreenGlintRect.Height = Height;\n var animation = new DoubleAnimation\n {\n Duration = new Duration(TimeSpan.FromSeconds(2)),\n From = (-Width),\n To = Width * 2\n };\n ScreenGlintRect.BeginAnimation(Canvas.LeftProperty, animation);\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/190937", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6415/" ]
190,940
<p>I've just set up a new build server with the Windows 2008 .NET 3.5 SDK, and for some reason it hasn't installed c:\Program Files\Common Files\Microsoft Shared\TextTemplating so I can't run t4 templates on it. I had a look at the install options in add/remove programs and every single option is checked. </p> <p>Any ideas why it is missing? Any ideas how to get it back?</p>
[ { "answer_id": 218326, "author": "Johan Danforth", "author_id": 6415, "author_profile": "https://Stackoverflow.com/users/6415", "pm_score": 4, "selected": true, "text": "<Window\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n x:Class=\"ScreenGlintApplication.Window1\"\n x:Name=\"Window\"\n Title=\"Window1\"\n Width=\"500\" Height=\"250\" Background=\"#FF000000\" Foreground=\"#FF3EE229\" >\n\n <Grid x:Name=\"LayoutRoot\">\n <TextBlock TextWrapping=\"Wrap\" FontSize=\"40\" >\n <Run Text=\"This is some sample text to have something to work with. Have a nice day! /Johan\"/>\n </TextBlock>\n <Canvas Panel.ZIndex=\"99\" >\n <Rectangle x:Name=\"ScreenGlintRect\" \n Width=\"{Binding Path=ActualWidth, ElementName=Window, Mode=Default}\" \n Height=\"{Binding Path=ActualHeight, ElementName=Window, Mode=Default}\" \n Opacity=\"0.4\" >\n <Rectangle.Triggers> \n <EventTrigger RoutedEvent=\"Rectangle.Loaded\"> \n <BeginStoryboard> \n <Storyboard> \n <DoubleAnimation Storyboard.TargetName=\"ScreenGlintRect\" \n Storyboard.TargetProperty=\"(Canvas.Left)\"\n From=\"-500\" To=\"1000\" Duration=\"0:0:2\" />\n </Storyboard> \n </BeginStoryboard> \n </EventTrigger> \n </Rectangle.Triggers> \n\n <Rectangle.Fill>\n <LinearGradientBrush StartPoint=\"0,1\" EndPoint=\"1,1\">\n <GradientStop Color=\"Transparent\" Offset=\"0.0\" />\n <GradientStop x:Name=\"GlintColor\" Color=\"LightGreen\" Offset=\"0.50\" />\n <GradientStop Color=\"Transparent\" Offset=\"1\" />\n </LinearGradientBrush>\n </Rectangle.Fill>\n </Rectangle>\n </Canvas>\n </Grid>\n</Window>\n ScreenGlintRect.Width = Width;\n ScreenGlintRect.Height = Height;\n var animation = new DoubleAnimation\n {\n Duration = new Duration(TimeSpan.FromSeconds(2)),\n From = (-Width),\n To = Width * 2\n };\n ScreenGlintRect.BeginAnimation(Canvas.LeftProperty, animation);\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/190940", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2086/" ]
190,956
<p>Just wanted to get an idea for ways (web) developers get round the short fall of (most) WYSIWYG editors, whereby the users that are editing the text aren't always HTML literate enough to produce good/great results.</p> <p>In the past we have resigned ourselves to either locking down the editor or simply not supplying one.</p> <p>What are other peoples experiences?</p>
[ { "answer_id": 218326, "author": "Johan Danforth", "author_id": 6415, "author_profile": "https://Stackoverflow.com/users/6415", "pm_score": 4, "selected": true, "text": "<Window\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n x:Class=\"ScreenGlintApplication.Window1\"\n x:Name=\"Window\"\n Title=\"Window1\"\n Width=\"500\" Height=\"250\" Background=\"#FF000000\" Foreground=\"#FF3EE229\" >\n\n <Grid x:Name=\"LayoutRoot\">\n <TextBlock TextWrapping=\"Wrap\" FontSize=\"40\" >\n <Run Text=\"This is some sample text to have something to work with. Have a nice day! /Johan\"/>\n </TextBlock>\n <Canvas Panel.ZIndex=\"99\" >\n <Rectangle x:Name=\"ScreenGlintRect\" \n Width=\"{Binding Path=ActualWidth, ElementName=Window, Mode=Default}\" \n Height=\"{Binding Path=ActualHeight, ElementName=Window, Mode=Default}\" \n Opacity=\"0.4\" >\n <Rectangle.Triggers> \n <EventTrigger RoutedEvent=\"Rectangle.Loaded\"> \n <BeginStoryboard> \n <Storyboard> \n <DoubleAnimation Storyboard.TargetName=\"ScreenGlintRect\" \n Storyboard.TargetProperty=\"(Canvas.Left)\"\n From=\"-500\" To=\"1000\" Duration=\"0:0:2\" />\n </Storyboard> \n </BeginStoryboard> \n </EventTrigger> \n </Rectangle.Triggers> \n\n <Rectangle.Fill>\n <LinearGradientBrush StartPoint=\"0,1\" EndPoint=\"1,1\">\n <GradientStop Color=\"Transparent\" Offset=\"0.0\" />\n <GradientStop x:Name=\"GlintColor\" Color=\"LightGreen\" Offset=\"0.50\" />\n <GradientStop Color=\"Transparent\" Offset=\"1\" />\n </LinearGradientBrush>\n </Rectangle.Fill>\n </Rectangle>\n </Canvas>\n </Grid>\n</Window>\n ScreenGlintRect.Width = Width;\n ScreenGlintRect.Height = Height;\n var animation = new DoubleAnimation\n {\n Duration = new Duration(TimeSpan.FromSeconds(2)),\n From = (-Width),\n To = Width * 2\n };\n ScreenGlintRect.BeginAnimation(Canvas.LeftProperty, animation);\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/190956", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17540/" ]
190,963
<p><a href="https://stackoverflow.com/questions/189925/password-encryption-in-iphone-apps">This question discusses encrypting data on the iPhone</a> using the crypt() function. As an alternative, is there a keychain on the iPhone and if so, what code would I use to access it in order to store login details and then retrieve them for us in an application?</p>
[ { "answer_id": 7314271, "author": "AlBeebe", "author_id": 172361, "author_profile": "https://Stackoverflow.com/users/172361", "pm_score": 3, "selected": false, "text": "#import <Security/Security.h>\n\n// -------------------------------------------------------------------------\n-(NSString *)getSecureValueForKey:(NSString *)key {\n /*\n\n Return a value from the keychain\n\n */\n\n // Retrieve a value from the keychain\n NSDictionary *result;\n NSArray *keys = [[[NSArray alloc] initWithObjects: (NSString *) kSecClass, kSecAttrAccount, kSecReturnAttributes, nil] autorelease];\n NSArray *objects = [[[NSArray alloc] initWithObjects: (NSString *) kSecClassGenericPassword, key, kCFBooleanTrue, nil] autorelease];\n NSDictionary *query = [[NSDictionary alloc] initWithObjects: objects forKeys: keys];\n\n // Check if the value was found\n OSStatus status = SecItemCopyMatching((CFDictionaryRef) query, (CFTypeRef *) &result);\n [query release];\n if (status != noErr) {\n // Value not found\n return nil;\n } else {\n // Value was found so return it\n NSString *value = (NSString *) [result objectForKey: (NSString *) kSecAttrGeneric];\n return value;\n }\n}\n\n\n\n\n// -------------------------------------------------------------------------\n-(bool)storeSecureValue:(NSString *)value forKey:(NSString *)key {\n /*\n\n Store a value in the keychain\n\n */\n\n // Get the existing value for the key\n NSString *existingValue = [self getSecureValueForKey:key];\n\n // Check if a value already exists for this key\n OSStatus status;\n if (existingValue) {\n // Value already exists, so update it\n NSArray *keys = [[[NSArray alloc] initWithObjects: (NSString *) kSecClass, kSecAttrAccount, nil] autorelease];\n NSArray *objects = [[[NSArray alloc] initWithObjects: (NSString *) kSecClassGenericPassword, key, nil] autorelease];\n NSDictionary *query = [[[NSDictionary alloc] initWithObjects: objects forKeys: keys] autorelease];\n status = SecItemUpdate((CFDictionaryRef) query, (CFDictionaryRef) [NSDictionary dictionaryWithObject:value forKey: (NSString *) kSecAttrGeneric]);\n } else {\n // Value does not exist, so add it\n NSArray *keys = [[[NSArray alloc] initWithObjects: (NSString *) kSecClass, kSecAttrAccount, kSecAttrGeneric, nil] autorelease];\n NSArray *objects = [[[NSArray alloc] initWithObjects: (NSString *) kSecClassGenericPassword, key, value, nil] autorelease];\n NSDictionary *query = [[[NSDictionary alloc] initWithObjects: objects forKeys: keys] autorelease];\n status = SecItemAdd((CFDictionaryRef) query, NULL);\n }\n\n // Check if the value was stored\n if (status != noErr) {\n // Value was not stored\n return false;\n } else {\n // Value was stored\n return true;\n }\n}\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/190963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2183/" ]
190,988
<p>I have to use the <strong>XMLHttp object in classic ASP</strong> in order to send some data to another server via HTTP from server to server:</p> <pre><code>sURL = SOME_URL Set oXHttp = Server.CreateObject("Msxml2.XMLHTTP") oXHttp.open "POST", sURL, false oXHttp.setRequestHeader "Content-Type", "application/x-www-form-urlencoded;charset:ISO-8859-1;" sPost = SOME_FORM_DATA oXHttp.send(sPost) </code></pre> <p>I've been told (by the maintainer of the consuming server) that, depending on whether I use this code from Windows Server 2000 (IIS 5) or Windows Server 2003 (IIS 6), he gets <strong>Latin-1</strong> (Windows 2000 Server) or <strong>UTF-8</strong> (Windows Server 2003) encoded data.</p> <p>I didn't find any property or method to set the character set of data I have to send. Does it depend on some Windows configuration or scripting (asp) settings?</p>
[ { "answer_id": 7314271, "author": "AlBeebe", "author_id": 172361, "author_profile": "https://Stackoverflow.com/users/172361", "pm_score": 3, "selected": false, "text": "#import <Security/Security.h>\n\n// -------------------------------------------------------------------------\n-(NSString *)getSecureValueForKey:(NSString *)key {\n /*\n\n Return a value from the keychain\n\n */\n\n // Retrieve a value from the keychain\n NSDictionary *result;\n NSArray *keys = [[[NSArray alloc] initWithObjects: (NSString *) kSecClass, kSecAttrAccount, kSecReturnAttributes, nil] autorelease];\n NSArray *objects = [[[NSArray alloc] initWithObjects: (NSString *) kSecClassGenericPassword, key, kCFBooleanTrue, nil] autorelease];\n NSDictionary *query = [[NSDictionary alloc] initWithObjects: objects forKeys: keys];\n\n // Check if the value was found\n OSStatus status = SecItemCopyMatching((CFDictionaryRef) query, (CFTypeRef *) &result);\n [query release];\n if (status != noErr) {\n // Value not found\n return nil;\n } else {\n // Value was found so return it\n NSString *value = (NSString *) [result objectForKey: (NSString *) kSecAttrGeneric];\n return value;\n }\n}\n\n\n\n\n// -------------------------------------------------------------------------\n-(bool)storeSecureValue:(NSString *)value forKey:(NSString *)key {\n /*\n\n Store a value in the keychain\n\n */\n\n // Get the existing value for the key\n NSString *existingValue = [self getSecureValueForKey:key];\n\n // Check if a value already exists for this key\n OSStatus status;\n if (existingValue) {\n // Value already exists, so update it\n NSArray *keys = [[[NSArray alloc] initWithObjects: (NSString *) kSecClass, kSecAttrAccount, nil] autorelease];\n NSArray *objects = [[[NSArray alloc] initWithObjects: (NSString *) kSecClassGenericPassword, key, nil] autorelease];\n NSDictionary *query = [[[NSDictionary alloc] initWithObjects: objects forKeys: keys] autorelease];\n status = SecItemUpdate((CFDictionaryRef) query, (CFDictionaryRef) [NSDictionary dictionaryWithObject:value forKey: (NSString *) kSecAttrGeneric]);\n } else {\n // Value does not exist, so add it\n NSArray *keys = [[[NSArray alloc] initWithObjects: (NSString *) kSecClass, kSecAttrAccount, kSecAttrGeneric, nil] autorelease];\n NSArray *objects = [[[NSArray alloc] initWithObjects: (NSString *) kSecClassGenericPassword, key, value, nil] autorelease];\n NSDictionary *query = [[[NSDictionary alloc] initWithObjects: objects forKeys: keys] autorelease];\n status = SecItemAdd((CFDictionaryRef) query, NULL);\n }\n\n // Check if the value was stored\n if (status != noErr) {\n // Value was not stored\n return false;\n } else {\n // Value was stored\n return true;\n }\n}\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/190988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6461/" ]
190,996
<p>I am working on a collection MATLAB, Java, and C/C++ components that all inter-operate, but have distinctly different compilation/installation steps. We currently don't compile anything for MATLAB, use maven2 for our Java build and unit tests, and use autotools for our C/C++ build and unit tests.</p> <p>I would like to move everything to a single build and unit test system, using maven2, but have not been able to find a plugin that will allow the C/C++ codestream to remain autotools-based and simply wrap it in a maven build. Having to rip out autotools support and recreate all the dependencies in maven is most likely a deal-breaker, so I'm looking for a way for maven and autotools to play nicely together, rather than having to choose between the two.</p> <p>Is this possible or even desirable? Are there resources out there that I have overlooked?</p>
[ { "answer_id": 7314271, "author": "AlBeebe", "author_id": 172361, "author_profile": "https://Stackoverflow.com/users/172361", "pm_score": 3, "selected": false, "text": "#import <Security/Security.h>\n\n// -------------------------------------------------------------------------\n-(NSString *)getSecureValueForKey:(NSString *)key {\n /*\n\n Return a value from the keychain\n\n */\n\n // Retrieve a value from the keychain\n NSDictionary *result;\n NSArray *keys = [[[NSArray alloc] initWithObjects: (NSString *) kSecClass, kSecAttrAccount, kSecReturnAttributes, nil] autorelease];\n NSArray *objects = [[[NSArray alloc] initWithObjects: (NSString *) kSecClassGenericPassword, key, kCFBooleanTrue, nil] autorelease];\n NSDictionary *query = [[NSDictionary alloc] initWithObjects: objects forKeys: keys];\n\n // Check if the value was found\n OSStatus status = SecItemCopyMatching((CFDictionaryRef) query, (CFTypeRef *) &result);\n [query release];\n if (status != noErr) {\n // Value not found\n return nil;\n } else {\n // Value was found so return it\n NSString *value = (NSString *) [result objectForKey: (NSString *) kSecAttrGeneric];\n return value;\n }\n}\n\n\n\n\n// -------------------------------------------------------------------------\n-(bool)storeSecureValue:(NSString *)value forKey:(NSString *)key {\n /*\n\n Store a value in the keychain\n\n */\n\n // Get the existing value for the key\n NSString *existingValue = [self getSecureValueForKey:key];\n\n // Check if a value already exists for this key\n OSStatus status;\n if (existingValue) {\n // Value already exists, so update it\n NSArray *keys = [[[NSArray alloc] initWithObjects: (NSString *) kSecClass, kSecAttrAccount, nil] autorelease];\n NSArray *objects = [[[NSArray alloc] initWithObjects: (NSString *) kSecClassGenericPassword, key, nil] autorelease];\n NSDictionary *query = [[[NSDictionary alloc] initWithObjects: objects forKeys: keys] autorelease];\n status = SecItemUpdate((CFDictionaryRef) query, (CFDictionaryRef) [NSDictionary dictionaryWithObject:value forKey: (NSString *) kSecAttrGeneric]);\n } else {\n // Value does not exist, so add it\n NSArray *keys = [[[NSArray alloc] initWithObjects: (NSString *) kSecClass, kSecAttrAccount, kSecAttrGeneric, nil] autorelease];\n NSArray *objects = [[[NSArray alloc] initWithObjects: (NSString *) kSecClassGenericPassword, key, value, nil] autorelease];\n NSDictionary *query = [[[NSDictionary alloc] initWithObjects: objects forKeys: keys] autorelease];\n status = SecItemAdd((CFDictionaryRef) query, NULL);\n }\n\n // Check if the value was stored\n if (status != noErr) {\n // Value was not stored\n return false;\n } else {\n // Value was stored\n return true;\n }\n}\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/190996", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5840/" ]
190,999
<p>I just started experimenting with SVG in web pages, and I discovered that it is only possible to add SVG images into HTML using <code>&lt;object /&gt;</code> tags, not <code>&lt;img /&gt;</code> like I would have expected. Most of the time, I add graphics to web pages through CSS because they are part of the presentation of the site, not the content.</p> <p>I know it is possible to apply CSS <em>to</em> SVG, but is it possible to add a vector image to an HTML element using purely CSS?</p>
[ { "answer_id": 191012, "author": "Neall", "author_id": 619, "author_profile": "https://Stackoverflow.com/users/619", "pm_score": 2, "selected": false, "text": ".putapicturehere:before {\n content: url(mysvgfile.svg);\n}\n" }, { "answer_id": 1042791, "author": "Erik Dahlström", "author_id": 109374, "author_profile": "https://Stackoverflow.com/users/109374", "pm_score": 3, "selected": false, "text": "<img> <img>" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/190999", "https://Stackoverflow.com", "https://Stackoverflow.com/users/392/" ]
191,004
<p>I'm trying to dynamically hide certain DIV's when a print (or print preview) occurs from the browser.</p> <p>I can easily differentiate statically by having two style sheets, one for normal and one for print media: </p> <p>But I need to go one step further and hide some elements dynamically when the print style sheet becomes active during a print based upon certain criteria</p> <p>One way to easily solve it would be to handle a DOM event for handling print / printview, then I could just use jQuery to change the display:none on the classes that need to be hidden, but I can't find a DOM print event!!</p> <p>Anyone know what the solution is?</p>
[ { "answer_id": 191234, "author": "Marcus Downing", "author_id": 1000, "author_profile": "https://Stackoverflow.com/users/1000", "pm_score": 2, "selected": false, "text": "<div id='div19' class='noprint'>\n ...\n</div>\n .noprint {\n display: none;\n}\n document.getElementById('div19').className='noprint';\n" }, { "answer_id": 192872, "author": "Grant Wagner", "author_id": 9254, "author_profile": "https://Stackoverflow.com/users/9254", "pm_score": 3, "selected": false, "text": "@media print @media print <html>\n<head>\n<style id=\"styles\" type=\"text/css\">\n@media print { .noprint { display:none; } }\n</style>\n<script type=\"text/javascript\">\nvar x = Math.random();\n\nif (x > .5) {\n var style = document.createElement('style');\n style.type = 'text/css';\n style.innerHTML = '@media print { .maybe_noprint { display:none; } }';\n document.getElementsByTagName('head')[0].appendChild(style);\n}\n</script>\n</head>\n<body>\n<div class=\"noprint\">This will never print.</div>\n<span class=\"maybe_noprint\">This may print depending on the value of x.</span>\n</body>\n</html>\n @media print @media print innerHTML" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191004", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26793/" ]
191,010
<pre><code>dir(re.compile(pattern)) </code></pre> <p>does not return pattern as one of the lists's elements. Namely it returns:</p> <pre><code>['__copy__', '__deepcopy__', 'findall', 'finditer', 'match', 'scanner', 'search', 'split', 'sub', 'subn'] </code></pre> <p>According to the manual, it is supposed to contain </p> <blockquote> <p>the object's attributes' names, the names of its class's attributes, and recursively of the attributes of its class's base classes.</p> </blockquote> <p>It says also that</p> <blockquote> <p>The list is not necessarily complete.</p> </blockquote> <p>Is there a way to get the <strong>complete</strong> list? I always assumed that dir returns a complete list but apparently it does not...</p> <p>Also: is there a way to list only attributes? Or only methods?</p> <p><em>Edit: this is actually a bug in python -> supposedly it is fixed in the 3.0 branch (and perhaps also in 2.6)</em></p>
[ { "answer_id": 191029, "author": "PierreBdR", "author_id": 7136, "author_profile": "https://Stackoverflow.com/users/7136", "pm_score": 8, "selected": true, "text": "getattr __getattr__ dir __dict__ __getattr__ inspect" }, { "answer_id": 191679, "author": "Moe", "author_id": 3051, "author_profile": "https://Stackoverflow.com/users/3051", "pm_score": 6, "selected": false, "text": "__dir__()" }, { "answer_id": 10313703, "author": "ジョージ", "author_id": 558008, "author_profile": "https://Stackoverflow.com/users/558008", "pm_score": 5, "selected": false, "text": "dir() dir() __class__ __bases__ # code borrowed from the rlcompleter module\n# tested under Python 2.6 ( sys.version = '2.6.5 (r265:79063, Apr 16 2010, 13:09:56) \\n[GCC 4.4.3]' )\n\n# or: from rlcompleter import get_class_members\ndef get_class_members(klass):\n ret = dir(klass)\n if hasattr(klass,'__bases__'):\n for base in klass.__bases__:\n ret = ret + get_class_members(base)\n return ret\n\n\ndef uniq( seq ): \n \"\"\" the 'set()' way ( use dict when there's no set ) \"\"\"\n return list(set(seq))\n\n\ndef get_object_attrs( obj ):\n # code borrowed from the rlcompleter module ( see the code for Completer::attr_matches() )\n ret = dir( obj )\n ## if \"__builtins__\" in ret:\n ## ret.remove(\"__builtins__\")\n\n if hasattr( obj, '__class__'):\n ret.append('__class__')\n ret.extend( get_class_members(obj.__class__) )\n\n ret = uniq( ret )\n\n return ret\n get_object_attrs() dir() dir() __class__" }, { "answer_id": 39286285, "author": "mluc", "author_id": 842903, "author_profile": "https://Stackoverflow.com/users/842903", "pm_score": 3, "selected": false, "text": "obj = type(\"Obj\",(object,),{}) class Obj: pass\nobj = Obj()\n obj.name = 'gary'\nobj.age = 32\n {key: value for key, value in obj.__dict__.items() if not key.startswith(\"__\")}\n\n# {'name': 'gary', 'age': 32}\n" }, { "answer_id": 52846957, "author": "Chiron", "author_id": 3829943, "author_profile": "https://Stackoverflow.com/users/3829943", "pm_score": 4, "selected": false, "text": "dir() dir() dir() __ __doc__ __dir__() dir() __dict__ dir() __dict__ __dir__() \\\\...\\\\torchfun.py in traverse(self, mod, search_attributes)\n445 if prefix in traversed_mod_names:\n446 continue\n447 names = dir(m)\n448 for name in names:\n449 obj = getattr(m,name)\n __dir__ 'object' __dir__() dir()" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191010", "https://Stackoverflow.com", "https://Stackoverflow.com/users/985/" ]
191,013
<p>Is it possible to have an anonymous type implement an interface?</p> <p>I've got a piece of code that I would like to work, but don't know how to do this.</p> <p>I've had a couple of answers that either say no, or create a class that implements the interface construct new instances of that. This isn't really ideal, but I'm wondering if there is a mechanism to create a thin dynamic class on top of an interface which would make this simple.</p> <pre><code>public interface DummyInterface { string A { get; } string B { get; } } public class DummySource { public string A { get; set; } public string C { get; set; } public string D { get; set; } } public class Test { public void WillThisWork() { var source = new DummySource[0]; var values = from value in source select new { A = value.A, B = value.C + "_" + value.D }; DoSomethingWithDummyInterface(values); } public void DoSomethingWithDummyInterface(IEnumerable&lt;DummyInterface&gt; values) { foreach (var value in values) { Console.WriteLine("A = '{0}', B = '{1}'", value.A, value.B); } } } </code></pre> <p>I've found an article <a href="http://channel8.msdn.com/Posts/Adding-some-dynamic-to-C-interface-wrapping/" rel="noreferrer">Dynamic interface wrapping</a> that describes one approach. Is this the best way of doing this?</p>
[ { "answer_id": 191124, "author": "ICR", "author_id": 214, "author_profile": "https://Stackoverflow.com/users/214", "pm_score": 4, "selected": false, "text": "public class Test\n{\n class DummyInterfaceImplementor : IDummyInterface\n {\n public string A { get; set; }\n public string B { get; set; }\n }\n\n public void WillThisWork()\n {\n var source = new DummySource[0];\n var values = from value in source\n select new DummyInterfaceImplementor()\n {\n A = value.A,\n B = value.C + \"_\" + value.D\n };\n\n DoSomethingWithDummyInterface(values.Cast<IDummyInterface>());\n\n }\n\n public void DoSomethingWithDummyInterface(IEnumerable<IDummyInterface> values)\n {\n foreach (var value in values)\n {\n Console.WriteLine(\"A = '{0}', B = '{1}'\", value.A, value.B);\n }\n }\n}\n" }, { "answer_id": 258032, "author": "Arne Claassen", "author_id": 32577, "author_profile": "https://Stackoverflow.com/users/32577", "pm_score": 6, "selected": false, "text": "select new\n{\n A = value.A,\n B = value.C + \"_\" + value.D\n};\n select new DynamicObject(new\n {\n A = value.A,\n B = value.C + \"_\" + value.D\n }).CreateDuck<DummyInterface>();\n" }, { "answer_id": 24823427, "author": "Russell Horwood", "author_id": 972880, "author_profile": "https://Stackoverflow.com/users/972880", "pm_score": 3, "selected": false, "text": "public void ThisWillWork()\n{\n var source = new DummySource[0];\n var mock = new Mock<DummyInterface>();\n\n mock.SetupProperty(m => m.A, source.Select(s => s.A));\n mock.SetupProperty(m => m.B, source.Select(s => s.C + \"_\" + s.D));\n\n DoSomethingWithDummyInterface(mock.Object);\n}\n" }, { "answer_id": 26825196, "author": "Jason Bowers", "author_id": 1864507, "author_profile": "https://Stackoverflow.com/users/1864507", "pm_score": 4, "selected": false, "text": "class Program\n{\n static void Main(string[] args)\n {\n var developer = new { Name = \"Jason Bowers\" };\n\n PrintDeveloperName(developer.DuckCast<IDeveloper>());\n\n Console.ReadKey();\n }\n\n private static void PrintDeveloperName(IDeveloper developer)\n {\n Console.WriteLine(developer.Name);\n }\n}\n\npublic interface IDeveloper\n{\n string Name { get; }\n}\n" }, { "answer_id": 55621734, "author": "Gordon Bean", "author_id": 2288986, "author_profile": "https://Stackoverflow.com/users/2288986", "pm_score": 2, "selected": false, "text": "public interface DummyInterface\n{\n string A { get; }\n string B { get; }\n}\n\n// \"Generic\" implementing class\npublic class Dummy : DummyInterface\n{\n private readonly Func<string> _getA;\n private readonly Func<string> _getB;\n\n public Dummy(Func<string> getA, Func<string> getB)\n {\n _getA = getA;\n _getB = getB;\n }\n\n public string A => _getA();\n\n public string B => _getB();\n}\n\npublic class DummySource\n{\n public string A { get; set; }\n public string C { get; set; }\n public string D { get; set; }\n}\n\npublic class Test\n{\n public void WillThisWork()\n {\n var source = new DummySource[0];\n var values = from value in source\n select new Dummy // Syntax changes slightly\n (\n getA: () => value.A,\n getB: () => value.C + \"_\" + value.D\n );\n\n DoSomethingWithDummyInterface(values);\n\n }\n\n public void DoSomethingWithDummyInterface(IEnumerable<DummyInterface> values)\n {\n foreach (var value in values)\n {\n Console.WriteLine(\"A = '{0}', B = '{1}'\", value.A, value.B);\n }\n }\n}\n DummySource DummyInterface DummySource DummyInterface" }, { "answer_id": 63860837, "author": "Fidel", "author_id": 171846, "author_profile": "https://Stackoverflow.com/users/171846", "pm_score": 0, "selected": false, "text": "var personClass = typeof(AAnimal).CreateSubclass(\"Person\");\n var person1 = Activator.CreateInstance(personClass);\nvar person2 = Activator.CreateInstance(personClass);\n using Microsoft.CodeAnalysis;\nusing Microsoft.CodeAnalysis.CSharp;\nusing System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Reflection;\n\nnamespace Publisher\n{\n public static class Extensions\n {\n public static Type CreateSubclass(this Type baseType, string newClassName, string newNamespace = \"Magic\")\n {\n //todo: handle ref, out etc.\n var concreteMethods = baseType\n .GetMethods()\n .Where(method => method.IsAbstract)\n .Select(method =>\n {\n var parameters = method\n .GetParameters()\n .Select(param => $\"{param.ParameterType.FullName} {param.Name}\")\n .ToString(\", \");\n\n var returnTypeStr = method.ReturnParameter.ParameterType.Name;\n if (returnTypeStr.Equals(\"Void\")) returnTypeStr = \"void\";\n\n var methodString = @$\"\n public override {returnTypeStr} {method.Name}({parameters})\n {{\n Console.WriteLine(\"\"{newNamespace}.{newClassName}.{method.Name}() was called\"\");\n }}\";\n\n return methodString.Trim();\n })\n .ToList();\n\n var concreteMethodsString = concreteMethods\n .ToString(Environment.NewLine + Environment.NewLine);\n\n var classCode = @$\"\n using System;\n\n namespace {newNamespace}\n {{\n public class {newClassName}: {baseType.FullName}\n {{\n public {newClassName}()\n {{\n }}\n\n {concreteMethodsString}\n }}\n }}\n \".Trim();\n\n classCode = FormatUsingRoslyn(classCode);\n\n\n /*\n var assemblies = new[]\n {\n MetadataReference.CreateFromFile(typeof(object).Assembly.Location),\n MetadataReference.CreateFromFile(baseType.Assembly.Location),\n };\n */\n\n var assemblies = AppDomain\n .CurrentDomain\n .GetAssemblies()\n .Where(a => !string.IsNullOrEmpty(a.Location))\n .Select(a => MetadataReference.CreateFromFile(a.Location))\n .ToArray();\n\n var syntaxTree = CSharpSyntaxTree.ParseText(classCode);\n\n var compilation = CSharpCompilation\n .Create(newNamespace)\n .AddSyntaxTrees(syntaxTree)\n .AddReferences(assemblies)\n .WithOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));\n\n using (var ms = new MemoryStream())\n {\n var result = compilation.Emit(ms);\n //compilation.Emit($\"C:\\\\Temp\\\\{newNamespace}.dll\");\n\n if (result.Success)\n {\n ms.Seek(0, SeekOrigin.Begin);\n Assembly assembly = Assembly.Load(ms.ToArray());\n\n var newTypeFullName = $\"{newNamespace}.{newClassName}\";\n\n var type = assembly.GetType(newTypeFullName);\n return type;\n }\n else\n {\n IEnumerable<Diagnostic> failures = result.Diagnostics.Where(diagnostic =>\n diagnostic.IsWarningAsError ||\n diagnostic.Severity == DiagnosticSeverity.Error);\n\n foreach (Diagnostic diagnostic in failures)\n {\n Console.Error.WriteLine(\"{0}: {1}\", diagnostic.Id, diagnostic.GetMessage());\n }\n\n return null;\n }\n }\n }\n\n public static string ToString(this IEnumerable<string> list, string separator)\n {\n string result = string.Join(separator, list);\n return result;\n }\n\n public static string FormatUsingRoslyn(string csCode)\n {\n var tree = CSharpSyntaxTree.ParseText(csCode);\n var root = tree.GetRoot().NormalizeWhitespace();\n var result = root.ToFullString();\n return result;\n }\n }\n}\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191013", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5932/" ]
191,020
<p>How do I set the initial width of a QDockWidget?</p> <p>I have implemented the sizeHint function but what next?</p>
[ { "answer_id": 191078, "author": "Marius", "author_id": 1585, "author_profile": "https://Stackoverflow.com/users/1585", "pm_score": 3, "selected": false, "text": "void Applicotion::readSettings() {\n QSettings settings(\"Company Name\", \"Application Name\");\n settings.beginGroup(\"LibraryDock\");\n libraryDock->setFloating(settings.value(\"docked\").toBool());\n libraryDock->resize(settings.value(\"size\", QSize(1, 1)).toSize());\n libraryDock->move(settings.value(\"pos\", QPoint(200, 200)).toPoint());\n addDockWidget((Qt::DockWidgetArea)settings.value(\"dockarea\", Qt::RightDockWidgetArea).toInt(), libraryDock);\n settings.endGroup();\n}\n\nvoid Applicotion::writeSettings() {\n QSettings settings(\"Company Name\", \"Application Name\");\n settings.beginGroup(\"LibraryDock\");\n settings.setValue(\"dockarea\", dockWidgetArea(libraryDock));\n settings.setValue(\"docked\", libraryDock->isFloating());\n settings.setValue(\"size\", libraryDock->size());\n settings.setValue(\"pos\", libraryDock->pos());\n settings.endGroup();\n" }, { "answer_id": 191140, "author": "David Dibben", "author_id": 5022, "author_profile": "https://Stackoverflow.com/users/5022", "pm_score": 5, "selected": true, "text": "QDockWidget QDockWidget QSettings QMainWindow::saveState saveState" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191020", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24459/" ]
191,023
<p>When Windows Internet Properties -> Connections -> LAN Settings -> Automatic Configuration is set to "Automatically detect settings" how does Windows actually determine/discover what the settings are? Is it a network broadcast or some kind of targeted query to a server configured somewhere in the registry, or something else?</p>
[ { "answer_id": 191041, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 7, "selected": true, "text": "GET http://wpad/wpad.dat" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191023", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5193/" ]
191,039
<p>In deploying to a new (Solaris 9) environment recently, one of the steps was to copy a set of files and directories to their new location and then to apply the group UID bit (using "chmod -R g+s") to all files in the directory tree giving a mode of -rwxr-s--- to everything. The result was that none of our shell scripts would execute unless they were individually opened and re-saved. I should add that we had earlier set g+s on the target parent folder prior to copying files; this had set the initial mode on all the new directories to drwxr-s--- but the files had a mode of -rwxr-x---</p> <p>Having eventually discovered which step caused the problem, we were able to cut out that step and proceed.</p> <p>I would like, however, to understand what the "s" bit means when applied to directories and files, in the hope that this will explain why we had the problem in the first place.</p>
[ { "answer_id": 191782, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 3, "selected": false, "text": "g+s g+s umask 0007 0027" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191039", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26790/" ]
191,056
<p>I want a checkbox on a web page. When I click it, it sends an ajax request to the server. When the server replies, I want the checkbox to change. I can fix everything except the fact that the checkbox immediately changes state when clicked. </p>
[ { "answer_id": 191100, "author": "tloach", "author_id": 14092, "author_profile": "https://Stackoverflow.com/users/14092", "pm_score": 0, "selected": false, "text": "checkbox.checked=NOT checkbox.checked" }, { "answer_id": 192704, "author": "Parand", "author_id": 13055, "author_profile": "https://Stackoverflow.com/users/13055", "pm_score": 2, "selected": false, "text": "$('#mycheckbox').click( function() {\n var checkbox = this;\n $(checkbox).attr('disabled','1');\n $.post( url, data, function() {\n // if successful\n $(checkbox).removeAttr('disabled');\n }\n}\n" }, { "answer_id": 192981, "author": "Grant Wagner", "author_id": 9254, "author_profile": "https://Stackoverflow.com/users/9254", "pm_score": 1, "selected": false, "text": "<input id=\"theChkbox\" type=\"checkbox\" onclick=\"this.checked=!this.checked;sendAjaxRequest(this);\">\n this.checked=!this.checked sendAjaxRequest() this sendAjaxRequest() document.getElementById(\"theChkbox\")" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191056", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
191,062
<p>Could someone please explain to me how the current python webframworks fit together?</p> <p>The three I've heard of are CherryPy, TurboGears and Pylons. However I'm confused because TurboGears seems to use CherryPy as the 'Controller' (although isn't CherryPy a framework in in it's own right?), and TurbGears 2 is going to be built on top of Pylons (which I thought did the same thing?).</p>
[ { "answer_id": 58336089, "author": "Babu Reddy", "author_id": 2016203, "author_profile": "https://Stackoverflow.com/users/2016203", "pm_score": 0, "selected": false, "text": "from fastapi import FastAPI\n\napp = FastAPI()\n\n\n@app.get(\"/\")\ndef read_root():\n return {\"Hello\": \"World\"}\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191062", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
191,066
<p>I am working on a Software Project that needs to be translated into 30 languages. This means that changing any string incurs into a relatively high cost. Additionally, translation does not happen overnight, because the translation package needs to be worked by different translators, so this might take a while.</p> <p>Adding new features is cumbersome somehow. We can think up all the Strings that will be needed before we actually code the UI, but sometimes still we need to add new strings because of bug fixes or because of an oversight.</p> <p>So the question is, how do you manage all this process? Any tips in how to ease the impact of translation in the software project? How to rule the strings, instead of having the strings rule you?</p> <p>EDIT: We are using Java and all Strings are internationalized using Resource Bundles, so the problem is not the internationalization per-se, but the management of the strings.</p>
[ { "answer_id": 277508, "author": "Elijah", "author_id": 33611, "author_profile": "https://Stackoverflow.com/users/33611", "pm_score": 2, "selected": false, "text": "\npublic final class l7d {\n...normal junk\n\n/**\n * Reference to the localized strings resource bundle.\n */\npublic static final ResourceBundle l7dBundle =\n ResourceBundle.getBundle(BUNDLE_PATH);\n\n//---- start l7d fields ----\\\npublic static final String ERROR_AuthenticationException;\npublic static final String ERROR_cannot_find_algorithm;\npublic static final String ERROR_invalid_context;\n...many more\n//---- end l7d fields ----\\\nstatic {\n //---- start setting l7d fields ----\\\n ERROR_AuthenticationException = l7dBundle.getString(\"ERROR_AuthenticationException\");\n ERROR_cannot_find_algorithm = l7dBundle.getString(\"ERROR_cannot_find_algorithm\");\n ERROR_invalid_context = l7dBundle.getString(\"ERROR_invalid_context\");\n ...many more\n //---- end setting l7d fields ----\\\n}\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2309/" ]
191,070
<p>What code generation tools are built-in to vs.net 2008 or are officially available via Microsoft?</p> <p>I know of:</p> <ul> <li>Entity Framework</li> <li>sqlmetal</li> </ul> <p>What else is there?</p> <p>Ideally i'm looking for something that will generate from an existing database schema.</p>
[ { "answer_id": 277508, "author": "Elijah", "author_id": 33611, "author_profile": "https://Stackoverflow.com/users/33611", "pm_score": 2, "selected": false, "text": "\npublic final class l7d {\n...normal junk\n\n/**\n * Reference to the localized strings resource bundle.\n */\npublic static final ResourceBundle l7dBundle =\n ResourceBundle.getBundle(BUNDLE_PATH);\n\n//---- start l7d fields ----\\\npublic static final String ERROR_AuthenticationException;\npublic static final String ERROR_cannot_find_algorithm;\npublic static final String ERROR_invalid_context;\n...many more\n//---- end l7d fields ----\\\nstatic {\n //---- start setting l7d fields ----\\\n ERROR_AuthenticationException = l7dBundle.getString(\"ERROR_AuthenticationException\");\n ERROR_cannot_find_algorithm = l7dBundle.getString(\"ERROR_cannot_find_algorithm\");\n ERROR_invalid_context = l7dBundle.getString(\"ERROR_invalid_context\");\n ...many more\n //---- end setting l7d fields ----\\\n}\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191070", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
191,082
<p>Ok sorry this might seem like a dumb question but I cannot figure this thing out :</p> <p>I am trying to parse a string and simply want to check whether it only contains the following characters : '0123456789dD+ '</p> <p>I have tried many things but just can't get to figure out the right regex to use!</p> <pre><code> Regex oReg = new Regex(@"[\d dD+]+"); oReg.IsMatch("e4"); </code></pre> <p>will return true even though e is not allowed... I've tried many strings, including Regex("[1234567890 dD+]+")...</p> <p>It always works on <a href="http://regexpal.com/" rel="nofollow noreferrer">Regex Pal</a> but not in C#...</p> <p>Please advise and again i apologize this seems like a very silly question</p>
[ { "answer_id": 191104, "author": "Manu", "author_id": 2133, "author_profile": "https://Stackoverflow.com/users/2133", "pm_score": 4, "selected": true, "text": "@\"^[0-9dD+ ]+$\"\n ^ $ +" }, { "answer_id": 191110, "author": "Coincoin", "author_id": 42, "author_profile": "https://Stackoverflow.com/users/42", "pm_score": 2, "selected": false, "text": "Regex oReg = new Regex(@\"^[0-9dD +]+$\");\noReg.IsMatch(\"e4\");\n" }, { "answer_id": 191117, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 1, "selected": false, "text": " Regex re = new Regex(@\"^[\\d dD+]+$\");\n Console.WriteLine(re.IsMatch(\"e4\"));\n Console.WriteLine(re.IsMatch(\"4\"));\n" }, { "answer_id": 191127, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": -1, "selected": false, "text": "Regex oReg = new Regex(@\"[^0-9dD+]\");\n!oReg.IsMatch(\"e4\");\n" }, { "answer_id": 191132, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "Regex oReg = new Regex(@\"^[\\d dD+]+$\");\noReg.IsMatch(\"e4\");\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191082", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25152/" ]
191,093
<p>As recently as several years ago, the developers actually made the builds that went to clients. This was obviously a disaster for reasons too numerous to list.</p> <p>Then when we started to learn the errors of our ways, we looked for a way to auto-build the entire application on a dedicated build machine. The culture at that time was very averse to bringing in outside tools, so we built our own autobuild system by writing a VB app.</p> <p>This worked fine for a while, until the project's structure started to change, new projects were added, and we needed to build the application in different ways. Then then weaknesses of our hand-rolled autobuilder became apparent and, over time, increasingly onerous. This disease has progressed now to the point where QA (who owns our build process) can't even maintain the autobuilder because it requires more and more programming skill. Every time we add a project or change something in an existing project, it consumes more developer time just to make it work. There have been days when we were unable to produce a build because the system was broken.</p> <p>I'm now in a position where I can change this process, and I'm looking to scrap the entire system and put something else in it's place. My goals are:</p> <ul> <li>Have an autobuild system that can run with zero human interaction at a specific time every day. It should be able to gather all the source code, compile all the apps, create the setups, put the finished products on a network share, and possibly trigger the automated testing system to kick in (we use QTP).</li> <li>The autobuild system should be flexible enough to easily adapt to changes in the project without rrequiring a major overhaul.</li> <li>It should be simple enough so that QA can own the system and not require developer resources to make changes to how builds are made.</li> </ul> <p>What are your experiences? Can you recommend an autobuild system? Should I have different goals?</p>
[ { "answer_id": 191244, "author": "Ben Straub", "author_id": 1319, "author_profile": "https://Stackoverflow.com/users/1319", "pm_score": 2, "selected": false, "text": "build" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/241536/" ]
191,143
<p>I'm getting ready to start a new project and I've been researching the entity framework. My question is what is the best strategy for validating the entities? Other projects I've worked on have used attributes for most of the validation, but obviously this is not possible in the entity framework. Is the only way to do this by handling the partial methods in the property setters? All advice is much appreciated.</p>
[ { "answer_id": 4176794, "author": "Rob", "author_id": 133250, "author_profile": "https://Stackoverflow.com/users/133250", "pm_score": 1, "selected": false, "text": "public abstract class ValidationObjectContext : ObjectContext{\n ...\n\n public override int SaveChanges(SaveOptions options){\n ValidateEntities();\n return base.SaveChanges(options);\n }\n\n}\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17744/" ]
191,153
<p>What are your usage of delegates in C#?</p>
[ { "answer_id": 191219, "author": "Santiago Palladino", "author_id": 12791, "author_profile": "https://Stackoverflow.com/users/12791", "pm_score": 0, "selected": false, "text": "storage.Store(conditions, Download(item))\n storage.Store(conditions, (item) => Download(item))\n" }, { "answer_id": 191226, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 3, "selected": false, "text": "Delegate.CreateDelegate MethodInfo Expression Expression Expression" }, { "answer_id": 191265, "author": "harpo", "author_id": 4525, "author_profile": "https://Stackoverflow.com/users/4525", "pm_score": 4, "selected": false, "text": "public delegate void DataReaderUser( System.Data.IDataReader dataReader );\n public class DataProvider\n{\n protected string _connectionString;\n\n public DataProvider( string psConnectionString )\n {\n _connectionString = psConnectionString;\n }\n\n public void UseReader( string psSELECT, DataReaderUser readerUser )\n {\n using ( SqlConnection connection = new SqlConnection( _connectionString ) )\n try\n {\n SqlCommand command = new SqlCommand( psSELECT, connection );\n connection.Open();\n SqlDataReader reader = command.ExecuteReader();\n\n while ( reader.Read() )\n readerUser( reader ); // the delegate is invoked\n }\n catch ( System.Exception ex )\n {\n // handle exception\n throw ex;\n }\n }\n}\n string sTableName = \"test\";\nstring sQuery = \"SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='\" + sTableName + \"'\";\n\nDataProvider.UseReader( sQuery,\n delegate( System.Data.IDataReader reader )\n {\n Console.WriteLine( sTableName + \".\" + reader[0] );\n } );\n" }, { "answer_id": 1214259, "author": "Andrew Hare", "author_id": 34211, "author_profile": "https://Stackoverflow.com/users/34211", "pm_score": 5, "selected": false, "text": "using System;\nusing System.Linq;\nusing System.Collections.Generic;\n\nclass Program\n{\n static void Main()\n {\n List<String> names = new List<String>\n {\n \"Nicole Hare\",\n \"Michael Hare\",\n \"Joe Hare\",\n \"Sammy Hare\",\n \"George Washington\",\n };\n\n // Here I am passing \"inMyFamily\" to the \"Where\" extension method\n // on my List<String>. The C# compiler automatically creates \n // a delegate instance for me.\n IEnumerable<String> myFamily = names.Where(inMyFamily);\n\n foreach (String name in myFamily)\n Console.WriteLine(name);\n }\n\n static Boolean inMyFamily(String name)\n {\n return name.EndsWith(\"Hare\");\n }\n}\n" }, { "answer_id": 1214260, "author": "Reed Copsey", "author_id": 65358, "author_profile": "https://Stackoverflow.com/users/65358", "pm_score": 3, "selected": false, "text": "Func<T,TResult>" }, { "answer_id": 1214287, "author": "jonnii", "author_id": 4590, "author_profile": "https://Stackoverflow.com/users/4590", "pm_score": 4, "selected": false, "text": "class IObserver{ void Notify(...); }\n myObject.SomeEvent += delegate{ Console.WriteLine(\"...\"); };\n myList.Where(i => i > 10);\n myList.Where(delegate(int i){ return i > 10; });\n myFactory.RegisterFactory(Widgets.Foo, () => new FooWidget());\nvar widget = myFactory.BuildWidget(Widgets.Foo);\n" }, { "answer_id": 9171127, "author": "mahesh", "author_id": 1186821, "author_profile": "https://Stackoverflow.com/users/1186821", "pm_score": 0, "selected": false, "text": " delegate void del_(int no1,int no2);\nclass Math\n{\n public static void add(int x,int y)\n {\n Console.WriteLine(x+y);\n }\n public static void sub(int x,int y)\n {\n Console.WriteLine(x-y);\n }\n}\n\n\n\n class Program\n {\n static void Main(string[] args)\n {\n del_ d1 = new del_(Math.add);\n d1(10, 20);\n del_ d2 = new del_(Math.sub);\n d2(20, 10);\n Console.ReadKey();\n }\n }\n" }, { "answer_id": 12754615, "author": "will", "author_id": 1717933, "author_profile": "https://Stackoverflow.com/users/1717933", "pm_score": 3, "selected": false, "text": "using System;\n\npublic class Test {\n public const int MAX_VALUE = 255;\n public const int MIN_VALUE = 10;\n\n public static void checkInt(int a) {\n Console.Write(\"checkInt result of {0}: \", a);\n if (a < MAX_VALUE && a > MIN_VALUE)\n Console.WriteLine(\"max and min value is valid\");\n else\n Console.WriteLine(\"max and min value is not valid\");\n }\n\n public static void checkMax(int a) {\n Console.Write(\"checkMax result of {0}: \", a);\n if (a < MAX_VALUE)\n Console.WriteLine(\"max value is valid\");\n else\n Console.WriteLine(\"max value is not valid\");\n }\n\n public static void checkMin(int a) {\n Console.Write(\"checkMin result of {0}: \", a);\n if (a > MIN_VALUE)\n Console.WriteLine(\"min value is valid\");\n else\n Console.WriteLine(\"min value is not valid\");\n Console.WriteLine(\"\");\n }\n}\n\npublic class Driver {\n public static void Main(string [] args) {\n Test.checkInt(1);\n Test.checkMax(1);\n Test.checkMin(1);\n\n Test.checkInt(10);\n Test.checkMax(10);\n Test.checkMin(10);\n\n Test.checkInt(20);\n Test.checkMax(20);\n Test.checkMin(20);\n\n Test.checkInt(30);\n Test.checkMax(30);\n Test.checkMin(30);\n\n Test.checkInt(254);\n Test.checkMax(254);\n Test.checkMin(254);\n\n Test.checkInt(255);\n Test.checkMax(255);\n Test.checkMin(255);\n\n Test.checkInt(256);\n Test.checkMax(256);\n Test.checkMin(256);\n }\n}\n using System;\n\npublic delegate void Valid(int a);\n\npublic class Test {\n public const int MAX_VALUE = 255;\n public const int MIN_VALUE = 10;\n\n public static void checkInt(int a) {\n Console.Write(\"checkInt result of {0}: \", a);\n if (a < MAX_VALUE && a > MIN_VALUE)\n Console.WriteLine(\"max and min value is valid\");\n else\n Console.WriteLine(\"max and min value is not valid\");\n }\n\n public static void checkMax(int a) {\n Console.Write(\"checkMax result of {0}: \", a);\n if (a < MAX_VALUE)\n Console.WriteLine(\"max value is valid\");\n else\n Console.WriteLine(\"max value is not valid\");\n }\n\n public static void checkMin(int a) {\n Console.Write(\"checkMin result of {0}: \", a);\n if (a > MIN_VALUE)\n Console.WriteLine(\"min value is valid\");\n else\n Console.WriteLine(\"min value is not valid\");\n Console.WriteLine(\"\");\n }\n}\n\npublic class Driver {\n public static void Main(string [] args) {\n Valid v1 = new Valid(Test.checkInt);\n v1 += new Valid(Test.checkMax);\n v1 += new Valid(Test.checkMin);\n v1(1);\n v1(10);\n v1(20);\n v1(30);\n v1(254);\n v1(255);\n v1(256);\n }\n}\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191153", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24975/" ]
191,157
<p>What exactly is the difference between the <code>window.onload</code> event and the <code>onload</code> event of the <code>body</code> tag? when do I use which and how should it be done correctly?</p>
[ { "answer_id": 191221, "author": "Dr. Bob", "author_id": 12182, "author_profile": "https://Stackoverflow.com/users/12182", "pm_score": 1, "selected": false, "text": "<body onload=\"\">" }, { "answer_id": 191227, "author": "Mark Biek", "author_id": 305, "author_profile": "https://Stackoverflow.com/users/305", "pm_score": 3, "selected": false, "text": "<body onload=\"\" <head document.observe(\"dom:loaded\", function(){\n alert('The DOM is loaded!');\n});\n Event.observe(window, 'load', function(){\n alert('Window onload');\n});\n" }, { "answer_id": 191318, "author": "Richard Turner", "author_id": 12559, "author_profile": "https://Stackoverflow.com/users/12559", "pm_score": 9, "selected": true, "text": "window.onload = myOnloadFunc <body onload=\"myOnloadFunc();\"> window.onload" }, { "answer_id": 191337, "author": "Rajeshwaran S P", "author_id": 21995, "author_profile": "https://Stackoverflow.com/users/21995", "pm_score": 0, "selected": false, "text": "<body onload=\"\">" }, { "answer_id": 191488, "author": "Soldarnal", "author_id": 3420, "author_profile": "https://Stackoverflow.com/users/3420", "pm_score": 1, "selected": false, "text": "<input id=\"test1\" value=\"something\"/>\n document.getElementById('test1').value = \"somethingelse\";\n" }, { "answer_id": 191601, "author": "Shadow2531", "author_id": 1697, "author_profile": "https://Stackoverflow.com/users/1697", "pm_score": 2, "selected": false, "text": "<body onload=\"\"> window.onload <body onload=\"\"> document.body.onload getAttribute(\"onload\") window.onload window.onload window.onload <body onload=\"\"> window.onload window.onload <body onload=\"\"> window.addEventListener(\"load\", func, false))" }, { "answer_id": 191750, "author": "jcampbell1", "author_id": 20512, "author_profile": "https://Stackoverflow.com/users/20512", "pm_score": 5, "selected": false, "text": "window.onload DOMContentLoaded $(document).ready()" }, { "answer_id": 1412684, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": " <body onload=\"body_onload();\">\n" }, { "answer_id": 2690787, "author": "john Joseph", "author_id": 323244, "author_profile": "https://Stackoverflow.com/users/323244", "pm_score": 5, "selected": false, "text": "window.onload <script>\n function testSp()\n {\n alert(\"hit\");\n }\n window.onload=testSp;\n</script>\n" }, { "answer_id": 19632613, "author": "Yesu Raj", "author_id": 896043, "author_profile": "https://Stackoverflow.com/users/896043", "pm_score": 3, "selected": false, "text": "window.onload $(window).load(function() {}) <body onload=\"\"> $(document).ready(function() {})" }, { "answer_id": 62388542, "author": "Petr Pivonka", "author_id": 3468283, "author_profile": "https://Stackoverflow.com/users/3468283", "pm_score": 0, "selected": false, "text": "window.onload=fn1; <body onload=\"fn1()\"> onload <script type=\"module\" … > onload <script type=\"module\" … > <body onload=\"fn1()\"> window.onload=fn1;" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191157", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2133/" ]
191,159
<p>You'd like to call a stored proc on MS SQL that has a parameter type of TIMESTAMP within T-SQL, not ADO.NET using a VARCHAR value (e.g. '0x0000000002C490C8').</p> <p>What do you do?</p> <p>UPDATE: This is where you have a "Timestamp" value coming at you but exists only as VARCHAR. (Think OUTPUT variable on another stored proc, but it's fixed already as VARCHAR, it just has the value of a TIMESTAMP). So, unless you decide to build Dynamic SQL, how can you programmatically change a value stored in VARCHAR into a valid TIMESTAMP?</p>
[ { "answer_id": 191169, "author": "John Rudy", "author_id": 14048, "author_profile": "https://Stackoverflow.com/users/14048", "pm_score": 2, "selected": false, "text": "EXEC usp_MyProc @myParam=0x0000000002C490C8\n select top 10 convert(varchar, ts) from foo\n select convert(timestamp, '0x0000000000170B2E')\n 0x3078303030303030" }, { "answer_id": 220226, "author": "6eorge Jetson", "author_id": 23422, "author_profile": "https://Stackoverflow.com/users/23422", "pm_score": 1, "selected": true, "text": "CREATE TABLE tblSource (\nId int not null\ncolData int not null\ncolTimestamp timestamp null)\n\nCREATE TABLE tblTarget (\nId int not null\ncolData int not null\ncolTimestampVarBinary varbinary(8) null)\n DECLARE @maxFrozenTargetTimestamp varchar(8)\nSELECT @maxFrozenTargetTimestamp = max(colStamp) FROM tblTarget\n\nINSERT tblTarget(Id, colData, colTimestampVarBinary)\nSELECT \nId\n,colData\ncolTimestampVarBinary = convert(varbinary(8) colTimestamp)\nFROM \ntblSource \nWHERE\ntblSource.colTimestamp > @maxFrozenTargetTimestamp\n" }, { "answer_id": 8316842, "author": "Sanchitos", "author_id": 317832, "author_profile": "https://Stackoverflow.com/users/317832", "pm_score": 3, "selected": false, "text": "declare @hexstring varchar(max);\nset @hexstring = '0xabcedf012439';\nselect CONVERT(varbinary(max), @hexstring, 1);\n\nset @hexstring = 'abcedf012439';\nselect CONVERT(varbinary(max), @hexstring, 2);\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191159", "https://Stackoverflow.com", "https://Stackoverflow.com/users/307/" ]
191,160
<p>I am creating a new build process for a DotNet project which is to be held in Subversion.</p> <p>For each dll/exe that I compile (via Nant) I would like to include 2 additional attibutes in the dlls that are built.</p> <p>I already understand the workings of the 'asminfo' nant task. But I need help retrieving the information which I hope to embed in my binaries.</p> <p>The build will always happen from a full working copy (checked out by the build process itself.) and will therefore always have an .svn directory available.</p> <p>The attributes I want to add are RepositoryVersion and RepositoryPath. (I understand that these are not the names this information goes by in svn)</p> <p>In order to do this I will need to extract the RepositoryVersion and RepositoryPath represented by the working copy folder that the BuildFile sits within.</p> <p><strong>How do I extract this information from any given .svn folder into the 2 nant variables?</strong> </p>
[ { "answer_id": 191199, "author": "EggyBach", "author_id": 15475, "author_profile": "https://Stackoverflow.com/users/15475", "pm_score": 3, "selected": true, "text": "<xmlpeek file=\"out.xml\" xpath=\"/info/entry/url\" property=\"svn.url\" />\n" }, { "answer_id": 191238, "author": "user24881", "author_id": 24881, "author_profile": "https://Stackoverflow.com/users/24881", "pm_score": 0, "selected": false, "text": "<property name=\"RepositoryPath\" value=\"$HeadURL$\" /> <property name=\"RepositoryVersion\" value=\"$Revision$\" />" }, { "answer_id": 219222, "author": "Tim Scott", "author_id": 29493, "author_profile": "https://Stackoverflow.com/users/29493", "pm_score": 2, "selected": false, "text": "<exec\n program=\"svn\"\n commandline='log \"${solution.dir}\" --xml --limit 1'\n output=\"${solution.dir}\\_revision.xml\"\n failonerror=\"false\"/>\n<xmlpeek\n file=\"${solution.dir}\\_revision.xml\"\n xpath=\"/log/logentry/@revision\"\n property=\"version.revision\"\n failonerror=\"false\"/>\n<delete file=\"${solution.dir}\\_revision.xml\" failonerror=\"false\"/>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191160", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11356/" ]
191,179
<p>How can I find the font that the user has set in their Windows Display Properties using C# in .NET?</p> <p>I want to display a form using the fonts that the user has selected. The fonts I want are those selected in the Windows Display Properties form for 3D-objects, menus and window title bars. But I cannot find a way to access them. There is a <code>System.Windows.Forms.Control.DefaultFont</code> property but that is returning the Windows default font (which is, I think, MS Sans Serif on XP).</p>
[ { "answer_id": 191199, "author": "EggyBach", "author_id": 15475, "author_profile": "https://Stackoverflow.com/users/15475", "pm_score": 3, "selected": true, "text": "<xmlpeek file=\"out.xml\" xpath=\"/info/entry/url\" property=\"svn.url\" />\n" }, { "answer_id": 191238, "author": "user24881", "author_id": 24881, "author_profile": "https://Stackoverflow.com/users/24881", "pm_score": 0, "selected": false, "text": "<property name=\"RepositoryPath\" value=\"$HeadURL$\" /> <property name=\"RepositoryVersion\" value=\"$Revision$\" />" }, { "answer_id": 219222, "author": "Tim Scott", "author_id": 29493, "author_profile": "https://Stackoverflow.com/users/29493", "pm_score": 2, "selected": false, "text": "<exec\n program=\"svn\"\n commandline='log \"${solution.dir}\" --xml --limit 1'\n output=\"${solution.dir}\\_revision.xml\"\n failonerror=\"false\"/>\n<xmlpeek\n file=\"${solution.dir}\\_revision.xml\"\n xpath=\"/log/logentry/@revision\"\n property=\"version.revision\"\n failonerror=\"false\"/>\n<delete file=\"${solution.dir}\\_revision.xml\" failonerror=\"false\"/>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191179", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26808/" ]
191,201
<p>I do all my coding in vim and am quite happy with it (so, please, no "use a different editor" responses), but have an ongoing annoyance in that the smartindent feature wants to not indent comments beginning with # at all. e.g., I want</p> <pre><code> # Do something $x = $x + 1; if ($y) { # Do something else $y = $y + $z; } </code></pre> <p>instead of vim's preferred</p> <pre><code># Do something $x = $x + 1; if ($y) { # Do something else $y = $y + $z; } </code></pre> <p>The only ways I have been able to prevent comments from being sent to the start of the line are to either insert and delete a character on the line before hitting # (a nuisance to have to remember to do every time) or turn off smartindent entirely (losing automatic indentation increase/decrease as I open/close braces).</p> <p>How can I set vim to maintain my indentation for comments instead of sending them to the start of the line?</p>
[ { "answer_id": 191230, "author": "Ben Hoffstein", "author_id": 4482, "author_profile": "https://Stackoverflow.com/users/4482", "pm_score": 3, "selected": false, "text": "set cindent\nset cinkeys=0{,0},!^F,o,O,e \" default is: 0{,0},0),:,0#,!^F,o,O,e\n" }, { "answer_id": 191267, "author": "Richard Waite", "author_id": 1200605, "author_profile": "https://Stackoverflow.com/users/1200605", "pm_score": 7, "selected": true, "text": "filetype plugin indent on\nsyntax enable\n set smartindent set autoindent ~/.vimrc" }, { "answer_id": 2323718, "author": "Russell Silva", "author_id": 280043, "author_profile": "https://Stackoverflow.com/users/280043", "pm_score": 4, "selected": false, "text": " When typing '#' as the first character in a new line, the indent for\n that line is removed, the '#' is put in the first column. The indent\n is restored for the next line. If you don't want this, use this\n mapping: \":inoremap # X^H#\", where ^H is entered with CTRL-V CTRL-H.\n When using the \">>\" command, lines starting with '#' are not shifted\n right.\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191201", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18914/" ]
191,206
<p>I need to programmatically get a list of running applications as shown in the "Applications" tab inside the Windows Task Manager using PowerShell or VBScript.</p> <p>All I could find so far is how to list processes using VBScript and WMI.</p>
[ { "answer_id": 191343, "author": "stahler", "author_id": 26811, "author_profile": "https://Stackoverflow.com/users/26811", "pm_score": 4, "selected": true, "text": "Set Word = CreateObject(\"Word.Application\")\nSet Tasks = Word.Tasks\nFor Each Task in Tasks\n If Task.Visible Then Wscript.Echo Task.Name\nNext\nWord.Quit\n" }, { "answer_id": 191548, "author": "Steven Murawski", "author_id": 1233, "author_profile": "https://Stackoverflow.com/users/1233", "pm_score": 5, "selected": false, "text": "get-process | where-object {$_.mainwindowhandle -ne 0} | select-object name, mainwindowtitle\n gps | ? {$_.mainwindowhandle -ne 0} | select name, mainwindowtitle\n" }, { "answer_id": 199204, "author": "EdgeVB", "author_id": 24863, "author_profile": "https://Stackoverflow.com/users/24863", "pm_score": 3, "selected": false, "text": "gps | ? {$_.mainwindowtitle.length -ne 0} | select name, mainwindowtitle\n" }, { "answer_id": 13499640, "author": "Jack", "author_id": 1784078, "author_profile": "https://Stackoverflow.com/users/1784078", "pm_score": 3, "selected": false, "text": "tasklist /v /v tasklist /v /fi \"imagenaem eq POWERPNT.EXE\"" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191206", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26810/" ]
191,208
<p>I have a table in SQL server that has the normal tree structure of Item_ID, Item_ParentID. Suppose I want to iterate and get all CHILDREN of a particular Item_ID (at any level).</p> <p>Recursion seems an intuitive candidate for this problem and I can write an SQL Server function to do this. </p> <p>Will this affect performance if my table has many many records? How do I avoid recursion and simply query the table? Please any suggestions?</p>
[ { "answer_id": 191220, "author": "JosephStyons", "author_id": 672, "author_profile": "https://Stackoverflow.com/users/672", "pm_score": 0, "selected": false, "text": "SELECT\n SOME_FIELDS\nFROM\n MASTER_TABLE MT\n ,CHILD_TABLE CT\nWHERE CT.PARENT_ID = MT.ITEM_ID\n" }, { "answer_id": 191256, "author": "Ilya Kochetov", "author_id": 15329, "author_profile": "https://Stackoverflow.com/users/15329", "pm_score": 4, "selected": true, "text": "WITH CONNECT BY" }, { "answer_id": 191279, "author": "AlexCuse", "author_id": 794, "author_profile": "https://Stackoverflow.com/users/794", "pm_score": 1, "selected": false, "text": ";\nwith CTE (Some, Columns, ItemId, ParentId) as \n(\n select Some, Columns, ItemId, ParentId\n from myTable \n where ItemId = @itemID\n union all\n select a.Some, a.Columns, a.ItemId, a.ParentId\n from myTable as a\n inner join CTE as b on a.ParentId = b.ItemId\n where a.ItemId <> b.ItemId\n)\nselect * from CTE\n" }, { "answer_id": 191299, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 0, "selected": false, "text": "select * from T where ParentId = @parent with AllDescendants (ItemId, ItemText) as (\n select t.ItemId, t.ItemText \n from [TableName] t\n where t.ItemId = @ancestorId\n union\n select sub.ItemId, sub.ItemText \n from [TableName] sub\n inner join [TableName] tree\n on tree.ItemId = sub.ParentItemId\n)\n" }, { "answer_id": 191369, "author": "jjacka", "author_id": 26515, "author_profile": "https://Stackoverflow.com/users/26515", "pm_score": 1, "selected": false, "text": "WITH Managers AS \n( \n--initialization \nSELECT EmployeeID, LastName, ReportsTo \nFROM Employees \nWHERE ReportsTo IS NULL \nUNION ALL \n--recursive execution \nSELECT e.employeeID,e.LastName, e.ReportsTo \nFROM Employees e INNER JOIN Managers m \nON e.ReportsTo = m.employeeID \n) \nSELECT * FROM Managers \n ManagerId EmployeeId\n1 2\n1 3\n2 1\n select * from employee_managers em \ninner join employee e on e.employeeid = em.employeeid and em.managerid = 42\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13370/" ]
191,209
<p>By default, copying from the command prompt will prompt you to overwrite files that already exist in the target location.</p> <p>You can add "/Y" to say "Yes to all" replacements.</p> <p>But how can you say "No to all" ?</p> <p>In other words, I want to copy everything from one directory that does <strong>not</strong> already exist in the target.</p> <p>The closest thing I see is the XCOPY argument to only copy things after a specific mod-datetime.</p>
[ { "answer_id": 191239, "author": "Adam Davis", "author_id": 2915, "author_profile": "https://Stackoverflow.com/users/2915", "pm_score": 3, "selected": false, "text": "2.3 By comparison with the file in destination\n\n The switches in this group select files based on the\n comparison between the files in the source and those in\n the destination. They are often used for periodic backup\n and directory synchronization purposes. These switches\n were originally created as variations of directory backup.\n They are also convenient for selecting files for deletion.\n\n2.3.1 by Presence/Absence\n\n The /BB and /U switches are the two switches which select\n files by the pure presence or absence as the criteria.\n Other switches in the this group (Group 2.3) are also\n affected by the file in the destination, but for a\n particular characteristics for comparison's sake.\n\n /BB Selects files that are present in source but not in destination.\n /U Selects files that are present in both source and destination.\n" }, { "answer_id": 191381, "author": "chitza", "author_id": 2073, "author_profile": "https://Stackoverflow.com/users/2073", "pm_score": 3, "selected": false, "text": "XCOPY /D /Y /R /H \n\n/D:m-d-y - Copies files changed on or after the specified date. If no date is given, copies only those files whose source time is newer than the destination time.\n\n/Y - Suppresses prompting to confirm you want to overwrite an existing destination file.\n\n/R - Overwrites read-only files.\n\n/H - Copies hidden and system files also.\n" }, { "answer_id": 8531251, "author": "krishnan", "author_id": 1101483, "author_profile": "https://Stackoverflow.com/users/1101483", "pm_score": 5, "selected": false, "text": "echo \"No\" | copy/-Y c:\\source c:\\Dest\\\n" }, { "answer_id": 10428877, "author": "ghostCoder", "author_id": 592099, "author_profile": "https://Stackoverflow.com/users/592099", "pm_score": 3, "selected": false, "text": "no | cp -rf c:\\source c:\\Dest\\\n" }, { "answer_id": 25529159, "author": "Jeff Tondreau", "author_id": 2565572, "author_profile": "https://Stackoverflow.com/users/2565572", "pm_score": 2, "selected": false, "text": "robocopy \"source\" \"destination\" /e /b /copyall /xo /it\n /e=Copies subdirectories. Note that this option includes empty directories\n/b=Copies files in Backup mode\n/copyall=Copies all file information\n/xo=Excludes older files. (this is what prevents it from copy the same file over and over)\n/it=Includes \"tweaked\" files. (this will allow the copy and replace of modified files)\n" }, { "answer_id": 36480990, "author": "Eddie Middlebrooks", "author_id": 6173109, "author_profile": "https://Stackoverflow.com/users/6173109", "pm_score": 3, "selected": false, "text": "xcopy {Source} {Destination} /E /D \n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191209", "https://Stackoverflow.com", "https://Stackoverflow.com/users/672/" ]
191,215
<p>How do I stop a Java process gracefully in Linux and Windows?</p> <p>When does <code>Runtime.getRuntime().addShutdownHook</code> get called, and when does it not?</p> <p>What about finalizers, do they help here?</p> <p>Can I send some sort of signal to a Java process from a shell?</p> <p>I am looking for preferably portable solutions.</p>
[ { "answer_id": 191961, "author": "jsight", "author_id": 1432, "author_profile": "https://Stackoverflow.com/users/1432", "pm_score": 7, "selected": true, "text": "SIGTERM System.exit(int) kill -9 kill -SIGKILL" }, { "answer_id": 208809, "author": "Ma99uS", "author_id": 20390, "author_profile": "https://Stackoverflow.com/users/20390", "pm_score": 6, "selected": false, "text": "//ThreadMonitorMBean.java\npublic interface ThreadMonitorMBean\n{\nString getName();\nvoid start();\nvoid stop();\nboolean isRunning();\n}\n\n// ThreadMonitor.java\npublic class ThreadMonitor implements ThreadMonitorMBean\n{\nprivate Thread m_thrd = null;\n\npublic ThreadMonitor(Thread thrd)\n{\n m_thrd = thrd;\n}\n\n@Override\npublic String getName()\n{\n return \"JMX Controlled App\";\n}\n\n@Override\npublic void start()\n{\n // TODO: start application here\n System.out.println(\"remote start called\");\n}\n\n@Override\npublic void stop()\n{\n // TODO: stop application here\n System.out.println(\"remote stop called\");\n\n m_thrd.interrupt();\n}\n\npublic boolean isRunning()\n{\n return Thread.currentThread().isAlive();\n}\n\npublic static void main(String[] args)\n{\n try\n {\n System.out.println(\"JMX started\");\n\n ThreadMonitorMBean monitor = new ThreadMonitor(Thread.currentThread());\n\n MBeanServer server = ManagementFactory.getPlatformMBeanServer();\n\n ObjectName name = new ObjectName(\"com.example:type=ThreadMonitor\");\n\n server.registerMBean(monitor, name);\n\n while(!Thread.interrupted())\n {\n // loop until interrupted\n System.out.println(\".\");\n try \n {\n Thread.sleep(1000);\n } \n catch(InterruptedException ex) \n {\n Thread.currentThread().interrupt();\n }\n }\n }\n catch(Exception e)\n {\n e.printStackTrace();\n }\n finally\n {\n // TODO: some final clean up could be here also\n System.out.println(\"JMX stopped\");\n }\n}\n}\n public class ThreadMonitorConsole\n{\n\npublic static void main(String[] args)\n{\n try\n { \n // connecting to JMX\n System.out.println(\"Connect to JMX service.\");\n JMXServiceURL url = new JMXServiceURL(\"service:jmx:rmi:///jndi/rmi://:9999/jmxrmi\");\n JMXConnector jmxc = JMXConnectorFactory.connect(url, null);\n MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();\n\n // Construct proxy for the the MBean object\n ObjectName mbeanName = new ObjectName(\"com.example:type=ThreadMonitor\");\n ThreadMonitorMBean mbeanProxy = JMX.newMBeanProxy(mbsc, mbeanName, ThreadMonitorMBean.class, true);\n\n System.out.println(\"Connected to: \"+mbeanProxy.getName()+\", the app is \"+(mbeanProxy.isRunning() ? \"\" : \"not \")+\"running\");\n\n // parse command line arguments\n if(args[0].equalsIgnoreCase(\"start\"))\n {\n System.out.println(\"Invoke \\\"start\\\" method\");\n mbeanProxy.start();\n }\n else if(args[0].equalsIgnoreCase(\"stop\"))\n {\n System.out.println(\"Invoke \\\"stop\\\" method\");\n mbeanProxy.stop();\n }\n\n // clean up and exit\n jmxc.close();\n System.out.println(\"Done.\"); \n }\n catch(Exception e)\n {\n // TODO Auto-generated catch block\n e.printStackTrace();\n }\n}\n}\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191215", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20390/" ]
191,233
<p>Often WinDbg will enter a state where it is <strong>*Busy*</strong> performing an operation. </p> <p>Often this is due to some mistake I made trying to <em>dt some_variable_itll_never_find</em> or setting a break point somewhere without symbols or the 1000's of other mistakes I make fumbling around this tool.</p> <p><strong>Is there a way to cancel the current operation?</strong></p>
[ { "answer_id": 9576204, "author": "EdChum", "author_id": 704848, "author_profile": "https://Stackoverflow.com/users/704848", "pm_score": 4, "selected": false, "text": "Ctrl+Break \n Ctrl+c\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191233", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3655/" ]
191,248
<p>I'm experimenting with <a href="http://en.wikipedia.org/wiki/Latent_Dirichlet_allocation" rel="noreferrer">Latent Dirichlet Allocation</a> for topic disambiguation and assignment, and I'm looking for advice.</p> <ol> <li>Which program is the "best", where best is some combination of easiest to use, best prior estimation, fast</li> <li>How do I incorporate my intuitions about topicality. Let's say I think I know that some items in the corpus are really in the same category, like all articles by the same author. Can I add that into the analysis?</li> <li>Any unexpected pitfalls or tips I should know before embarking?</li> </ol> <p>I'd prefer is there are R or Python front ends for whatever program, but I expect (and accept) that I'll be dealing with C. </p>
[ { "answer_id": 71241775, "author": "Платформа Игр", "author_id": 17389005, "author_profile": "https://Stackoverflow.com/users/17389005", "pm_score": 0, "selected": false, "text": "def plot_top_words(model, feature_names, n_top_words, title):\nfig, axes = plt.subplots(2, 5, figsize=(30, 15), sharex=True)\naxes = axes.flatten()\nfor topic_idx, topic in enumerate(model.components_):\n top_features_ind = topic.argsort()[:-n_top_words - 1:-1]\n top_features = [feature_names[i] for i in top_features_ind]\n weights = topic[top_features_ind]\n\n ax = axes[topic_idx]\n ax.barh(top_features, weights, height=0.7)\n ax.set_title(f'Topic {topic_idx +1}',\n fontdict={'fontsize': 30})\n ax.invert_yaxis()\n ax.tick_params(axis='both', which='major', labelsize=20)\n for i in 'top right left'.split():\n ax.spines[i].set_visible(False)\n fig.suptitle(title, fontsize=40)\n\nplt.subplots_adjust(top=0.90, bottom=0.05, wspace=0.90, hspace=0.3)\nplt.show()\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191248", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15842/" ]
191,250
<p>I have the following code fragment that starts a <a href="http://en.wikipedia.org/wiki/Google_Earth" rel="nofollow noreferrer">Google Earth</a> process using a hardcoded path:</p> <pre><code>var process = new Process { StartInfo = { //TODO: Get location of google earth executable from registry FileName = @"C:\Program Files\Google\Google Earth\googleearth.exe", Arguments = "\"" + kmlPath + "\"" } }; process.Start(); </code></pre> <p>I want to programmatically fetch the installation location of <em>googleearth.exe</em> from somewhere (most likely the registry).</p>
[ { "answer_id": 191281, "author": "Iain", "author_id": 5993, "author_profile": "https://Stackoverflow.com/users/5993", "pm_score": 2, "selected": false, "text": "Process.Start(kmlPath);\n" }, { "answer_id": 194238, "author": "ICR", "author_id": 214, "author_profile": "https://Stackoverflow.com/users/214", "pm_score": 3, "selected": true, "text": "static Regex pathArgumentsRegex = new Regex(@\"(%\\d+)|(\"\"%\\d+\"\")\", RegexOptions.ExplicitCapture);\nstatic string GetPathAssociatedWithFileExtension(string extension)\n{\n RegistryKey extensionKey = Registry.ClassesRoot.OpenSubKey(extension);\n if (extensionKey != null)\n {\n object applicationName = extensionKey.GetValue(string.Empty);\n if (applicationName != null)\n {\n RegistryKey commandKey = Registry.ClassesRoot.OpenSubKey(applicationName.ToString() + @\"\\shell\\open\\command\");\n if (commandKey != null)\n {\n object command = commandKey.GetValue(string.Empty);\n if (command != null)\n {\n return pathArgumentsRegex.Replace(command.ToString(), \"\");\n }\n }\n }\n }\n return null;\n}\n private static string GetGoogleEarthExePath()\n{\n RegistryKey googleEarthRK = Registry.CurrentUser.OpenSubKey(@\"Software\\Google\\Google Earth Plus\\\");\n if (googleEarthRK != null)\n {\n object rootDir = googleEarthRK.GetValue(\"InstallLocation\");\n if (rootDir != null)\n {\n return Path.Combine(rootDir.ToString(), \"googleearth.exe\");\n }\n }\n\n return null;\n}\n" }, { "answer_id": 814009, "author": "Hawkeye Parker", "author_id": 99717, "author_profile": "https://Stackoverflow.com/users/99717", "pm_score": 1, "selected": false, "text": "void PrintString(CString string)\n{\n std::wcout << static_cast<LPCTSTR>(string) << endl;\n}\n\nCString GetClassesRootKeyValue(const wchar_t * keyName)\n{\n HKEY hkey;\n TCHAR keyNameCopy[256] = {0};\n _tcscpy_s(keyNameCopy, 256, keyName);\n BOOL bResult = SUCCEEDED(::RegOpenKey(HKEY_CLASSES_ROOT, keyNameCopy, &hkey));\n CString hkeyValue = CString(\"\");\n if (bResult) {\n TCHAR temporaryValueBuffer[256];\n DWORD bufferSize = sizeof (temporaryValueBuffer);\n DWORD type;\n bResult = SUCCEEDED(RegQueryValueEx(hkey, _T(\"\"), NULL, &type, (BYTE*)temporaryValueBuffer, &bufferSize)) && (bufferSize > 1);\n if (bResult) {\n hkeyValue = CString(temporaryValueBuffer);\n }\n RegCloseKey(hkey);\n return hkeyValue;\n }\n return hkeyValue;\n}\n\n\nint _tmain(int argc, TCHAR* argv[], TCHAR* envp[])\n{\n int nRetCode = 0;\n\n // initialize MFC and print and error on failure\n if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))\n {\n // TODO: change error code to suit your needs\n _tprintf(_T(\"Fatal Error: MFC initialization failed\\n\"));\n nRetCode = 1;\n }\n else\n {\n\n CString dwgAppName = GetClassesRootKeyValue(_T(\".dwg\"));\n PrintString(dwgAppName);\n\n dwgAppName.Append(_T(\"\\\\shell\\\\open\\\\command\"));\n PrintString(dwgAppName);\n\n CString trueViewOpenCommand = GetClassesRootKeyValue(static_cast<LPCTSTR>(dwgAppName));\n PrintString(trueViewOpenCommand);\n\n // Shell open command usually ends with a \"%1\" for commandline params. We don't want that,\n // so strip it off.\n int firstParameterIndex = trueViewOpenCommand.Find(_T(\"%\"));\n PrintString(trueViewOpenCommand.Left(firstParameterIndex).TrimRight('\"').TrimRight(' '));\n\n\n cout << \"\\n\\nPress <enter> to exit...\";\n getchar();\n }\n}\n" }, { "answer_id": 1309191, "author": "snicker", "author_id": 160359, "author_profile": "https://Stackoverflow.com/users/160359", "pm_score": 2, "selected": false, "text": " Type type = Type.GetTypeFromProgID(\"WindowsInstaller.Installer\");\n Installer msi = (Installer)Activator.CreateInstance(type);\n foreach (string productcode in msi.Products)\n {\n string productname = msi.get_ProductInfo(productcode, \"InstalledProductName\");\n if (productname.Contains(\"Google Earth\"))\n {\n string installdir = msi.get_ProductInfo(productcode, \"InstallLocation\");\n Console.WriteLine(\"{0}: {1} @({2})\", productcode, productname, installdir);\n }\n }\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191250", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5993/" ]
191,253
<p>I have a client who is still using Visual Studio 6 for building production systems. They write multi-threaded systems that use STL and run on mutli-processor machines. </p> <p>Occasionally when they change the spec of or increase the load on one of their server machines they get 'weird' difficult to reproduce errors... </p> <p>I know that there are several issues with Visual Studio 6 development and I'd like to convince them to move to Visual Stuio 2005 or 2008 (they have Visual Studio 2005 and use it for some projects). </p> <p>The purpose of this question is to put together a list of known issues or reasons to upgrade along with links to where these issues are discussed or reported. It would also be useful to have real life 'horror stories' of how these issues have bitten you.</p>
[ { "answer_id": 191303, "author": "Ben Straub", "author_id": 1319, "author_profile": "https://Stackoverflow.com/users/1319", "pm_score": 0, "selected": false, "text": "/clr" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191253", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7925/" ]
191,260
<p>We've recently completed phase 1 of a ASP.Net website in English and French. We went with using resource files to store language specific strings, but because the site used ASP.Net AJAX and javascript heavily we rigged up a solution to pass the right files through the ASP.Net pipeline where we could catch "tokens" and replace them with the appropriate text pulled from the resource files. </p> <p>This is the second project I've been involved in that had these kinds of challenges, the first one stored the text strings in a database, and instead of ASP.Net AJAX, it used the AJAX tools that come with the Prototype library and put all Javascript into aspx files so that the tokens could be replaced on the way out.</p> <p>What I'm wondering is, has anyone else encountered a similar scenario? What approach did you take? What lessons were learned? How did you deal with things like internationalized date formats?</p>
[ { "answer_id": 191754, "author": "Joe Scylla", "author_id": 25771, "author_profile": "https://Stackoverflow.com/users/25771", "pm_score": 2, "selected": true, "text": "<script scr=\"var/scripts/en_GB-76909c49e9222ec2bb2f45e0a3c8baef80deb665.js\"></script>\n" }, { "answer_id": 1156538, "author": "Walter Rumsby", "author_id": 1654, "author_profile": "https://Stackoverflow.com/users/1654", "pm_score": 0, "selected": false, "text": "LOCALISATIONS = {\n 'util.date.day.long': ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],\n 'util.date.day.short': ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],\n ...\n};\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191260", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22152/" ]
191,291
<p>How would you manually trigger additional team builds from a team build? For example, when we were in CC.Net other builds would trigger if certain builds were successful. The second build could either be projects that use this component or additional, long running test libraries for the same component. </p>
[ { "answer_id": 191898, "author": "Martin Woodward", "author_id": 6438, "author_profile": "https://Stackoverflow.com/users/6438", "pm_score": 3, "selected": true, "text": " <Target Name=\"AfterEndToEndIteration\">\n\n <GetBuildProperties TeamFoundationServerUrl=\"$(TeamFoundationServerUrl)\"\n BuildUri=\"$(BuildUri)\"\n Condition=\" '$(IsDesktopBuild)' != 'true' \">\n <Output TaskParameter=\"Status\" PropertyName=\"Status\" />\n </GetBuildProperties>\n\n <Exec Condition=\" '$(Status)'=='Succeeded' \"\n Command=\"TfsBuild.exe start /server:$(TeamFoundationServerUrl) /buildDefinition:&quot;Your Build Definition To Run&quot;\" />\n\n </Target>\n" }, { "answer_id": 290865, "author": "joshua.ewer", "author_id": 28664, "author_profile": "https://Stackoverflow.com/users/28664", "pm_score": 2, "selected": false, "text": " public override bool Execute()\n { \n IBuildDefinition[] buildDefinitions = BuildServer.QueryBuildDefinitions(ProjectName);\n\n foreach (IBuildDefinition build in buildDefinitions)\n {\n if(build.Enabled) //I did a bunch of custom rules here\n {\n Log.LogMessage(String.Concat(\"Queuing build: \", build.Name));\n BuildServer.QueueBuild(build);\n }\n }\n\n return true;\n }\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191291", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18264/" ]
191,306
<p>I want to force the current execution line to a specific line in the same function, possibly skipping intermediate lines. All my old school debuggers had this feature, but I can't find it in eclipse. Is there a way to do it without changing code?</p>
[ { "answer_id": 42689490, "author": "Ciro Santilli OurBigBook.com", "author_id": 895245, "author_profile": "https://Stackoverflow.com/users/895245", "pm_score": 0, "selected": false, "text": "i = 1 #include <stdio.h>\n\nint main(void) {\n int i;\n i = 0; /* Break here. */\n i = 1;\n printf(\"%d\\n\", i); /* Jump to here. */\n}\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12386/" ]
191,312
<p>If you launch Emacs using the <code>-nw</code> flag to force a console session (rather than an X session if you have X windows running), how do you get to the menu?</p> <p>There are some items held in the menus that are infrequently-enough used on my part that I don't recall the escape or control sequence to do them.</p>
[ { "answer_id": 191344, "author": "JesperE", "author_id": 13051, "author_profile": "https://Stackoverflow.com/users/13051", "pm_score": 2, "selected": false, "text": "M-x menu-bar-mode\n" }, { "answer_id": 191377, "author": "Chris Conway", "author_id": 1412, "author_profile": "https://Stackoverflow.com/users/1412", "pm_score": 8, "selected": true, "text": "M-x menu-bar-open F10 menu-bar-mode" }, { "answer_id": 7304812, "author": "Drew", "author_id": 729907, "author_profile": "https://Stackoverflow.com/users/729907", "pm_score": 3, "selected": false, "text": "ESC M-x\nMenu command:\nMenu command: t [TAB]\nMenu command: Tools > \nMenu command: Tools > Compa [TAB]\nMenu command: Tools > Compare (Ediff) > Two F [TAB]\nMenu command: Tools > Compare (Ediff) > Two Files... [RET]\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4418/" ]
191,329
<p>I am working through a book which gives examples of Ranges being converted to equivalent arrays using their "to_a" methods</p> <p>When i run the code in irb I get the following warning</p> <pre><code> warning: default `to_a' will be obsolete </code></pre> <p>What is the the correct alternative to using to_a?</p> <p>are there alternate ways to populate an array with a Range?</p>
[ { "answer_id": 191357, "author": "Daniel Lucraft", "author_id": 11951, "author_profile": "https://Stackoverflow.com/users/11951", "pm_score": 6, "selected": false, "text": "irb> (1..4).to_a\n=> [1, 2, 3, 4]\n irb> 1..4.to_a\n(irb):1: warning: default `to_a' will be obsolete\nArgumentError: bad value for range\n from (irb):1\n" }, { "answer_id": 191373, "author": "Richard Turner", "author_id": 12559, "author_profile": "https://Stackoverflow.com/users/12559", "pm_score": 5, "selected": false, "text": "0..10.to_a\n (0..10).to_a\n" }, { "answer_id": 6587096, "author": "Zamith", "author_id": 830229, "author_profile": "https://Stackoverflow.com/users/830229", "pm_score": 10, "selected": true, "text": ">> a=*(1..10)\n=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n Kernel Array Array (1..10)\n=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n (1..10).to_a\n=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n" }, { "answer_id": 16038564, "author": "Nickolay Kondratenko", "author_id": 1812321, "author_profile": "https://Stackoverflow.com/users/1812321", "pm_score": 3, "selected": false, "text": "irb(main):007:0> Array(1..5)\n=> [1, 2, 3, 4, 5]\nirb(main):008:0> Array(5..1)\n=> []\n (1..5).to_a.reverse\n" }, { "answer_id": 17057666, "author": "Boris Stitnicky", "author_id": 1153747, "author_profile": "https://Stackoverflow.com/users/1153747", "pm_score": 3, "selected": false, "text": "a = [*(1..10), :top, *10.downto( 1 )]\n" }, { "answer_id": 49009672, "author": "Jesús Andrés Valencia Montoya", "author_id": 3582073, "author_profile": "https://Stackoverflow.com/users/3582073", "pm_score": 3, "selected": false, "text": "irb> [*1..10]\n\n=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191329", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24773/" ]
191,335
<p>Is there a way to generate random number on Windows by reading from a file or pseudo file or character special file, the way that can be done on Linux by reading from <a href="http://en.wikipedia.org/wiki/Urandom#Linux" rel="nofollow noreferrer">/dev/random</a>? Not asking about various crypto API, but whether there is in Windows something akin to the Linux way.</p>
[ { "answer_id": 20825047, "author": "cxxl", "author_id": 1045800, "author_profile": "https://Stackoverflow.com/users/1045800", "pm_score": 1, "selected": false, "text": "rand_s() RtlGenRandom rand_s()" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191335", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5764/" ]
191,339
<p>I have a <code>DataGridView</code> bound to a <code>DataView</code>. The grid can be sorted by the user on any column.</p> <p>I add a row to the grid by calling NewRow on the <code>DataView</code>'s underlying <code>DataTable</code>, then adding it to the <code>DataTable</code>'s Rows collection. How can I select the newly-added row in the grid?</p> <p>I tried doing it by creating a <code>BindingManagerBase</code> object bound to the <code>BindingContext</code> of the <code>DataView</code>, then setting <code>BindingManagerBase.Position = BindingManagerBase.Count</code>. This works if the grid is not sorted, since the new row gets added to the bottom of the grid. However, if the sort order is such that the row is not added to the bottom, this does not work.</p> <p>How can I reliably set the selected row of the grid to the new row?</p>
[ { "answer_id": 209841, "author": "Brendan Kendrick", "author_id": 13473, "author_profile": "https://Stackoverflow.com/users/13473", "pm_score": 0, "selected": false, "text": "Dim myRecentItemID As Integer = 3\n\nFor Each row As GridViewRow In gvIndividuals.Rows\n Dim drv As DataRowView = DirectCast(row.DataItem, DataRowView)\n If CInt(drv(\"ItemID\")) = myRecentItemID Then\n gvIndividuals.EditIndex = row.RowIndex\n End If\nNext\n" }, { "answer_id": 478650, "author": "stefano", "author_id": 58898, "author_profile": "https://Stackoverflow.com/users/58898", "pm_score": 2, "selected": false, "text": "//local member\nprivate int addedRowIndex;\n\nprivate void AddMyRow()\n{\n //add the DataRow \n MyDataSet.MyDataTable.Rows.Add(...);\n\n //RowsAdded event is fired here....\n\n //select the row\n MyDataGrid.Rows[addedRowIndex].Selected = true;\n}\n\nprivate void MyDataGrid_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)\n{\n addedRowIndex = e.RowIndex;\n}\n" }, { "answer_id": 1664824, "author": "Ruben Trancoso", "author_id": 137149, "author_profile": "https://Stackoverflow.com/users/137149", "pm_score": 1, "selected": false, "text": " DataRowView drv = (DataRowView)source.AddNew();\n grupoTableAdapter.Update(drv.Row);\n grupoBindingSource.Position = grupoBindingSource.Find(\"ID\", drv.Row.ItemArray[0]);\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3012/" ]
191,342
<p>Is there a succinct way to retrieve a random record from a sql server table? </p> <p>I would like to randomize my unit test data, so am looking for a simple way to select a random id from a table. In English, the select would be "Select one id from the table where the id is a random number between the lowest id in the table and the highest id in the table." </p> <p>I can't figure out a way to do it without have to run the query, test for a null value, then re-run if null.</p> <p>Ideas?</p>
[ { "answer_id": 191348, "author": "Sklivvz", "author_id": 7028, "author_profile": "https://Stackoverflow.com/users/7028", "pm_score": 8, "selected": true, "text": "SELECT TOP 1 * FROM table ORDER BY NEWID()\n NEWID() SELECT TOP 1 * FROM table ORDER BY RAND() RAND()" }, { "answer_id": 191498, "author": "Sklivvz", "author_id": 7028, "author_profile": "https://Stackoverflow.com/users/7028", "pm_score": 3, "selected": false, "text": "SELECT TOP 1 * FROM table WHERE Id >= @yourrandomid\n" }, { "answer_id": 12129340, "author": "Martin Smith", "author_id": 73226, "author_profile": "https://Stackoverflow.com/users/73226", "pm_score": 5, "selected": false, "text": "TABLESAMPLE SELECT TOP 1 *\nFROM YourTable\nTABLESAMPLE (1000 ROWS)\nORDER BY NEWID()\n ORDER BY NEWID" }, { "answer_id": 18857785, "author": "user2788934", "author_id": 2788934, "author_profile": "https://Stackoverflow.com/users/2788934", "pm_score": 0, "selected": false, "text": "Create Table ##TmpAddress (id Int Identity(1,1), street VarChar(50), city VarChar(50), st VarChar(2), zip VarChar(5))\nInsert Into ##TmpAddress(street, city, st, zip)\nSelect street, city, st, zip \nFrom tbl_Address (NOLOCK)\nWhere st = @st\n\n\n-- unseeded RAND() will return the same number when called in rapid succession so\n-- here, I seed it with a guaranteed different number each time. @@ROWCOUNT is the count from the most recent table operation.\n\nSet @csr = Ceiling(RAND(convert(varbinary, newid())) * @@ROWCOUNT)\n\nSelect street, city, st, Right(('00000' + ltrim(zip)),5) As zip\nFrom ##tmpAddress (NOLOCK)\nWhere id = @csr\n" }, { "answer_id": 20606423, "author": "hmfarimani", "author_id": 3106590, "author_profile": "https://Stackoverflow.com/users/3106590", "pm_score": 3, "selected": false, "text": "SELECT * FROM Table1\nWHERE (ABS(CAST(\n (BINARY_CHECKSUM\n (keycol1, NEWID())) as int))\n % 100) < 10\n" }, { "answer_id": 58487944, "author": "XpiritO", "author_id": 76219, "author_profile": "https://Stackoverflow.com/users/76219", "pm_score": 0, "selected": false, "text": "SELECT * FROM Sales.SalesOrderDetail\nWHERE 0.01 >= CAST(CHECKSUM(NEWID(), SalesOrderID) & 0x7fffffff AS float)\n/ CAST (0x7fffffff AS int)\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10693/" ]
191,351
<p>I am trying to rename all the files present in a Windows directory using <strong>FOR</strong> command as follows at the command prompt:</p> <pre><code>for %1 in (*.*) do ren %1 test%1 </code></pre> <p>E.g. This renames a file <strong>enc1.ctl</strong> to <strong>testenc1.ctl</strong> <strong>enc2.ctl</strong> to <strong>testenc2.ctl</strong> </p> <p>Thats not what i want. What i want is <strong>enc1.ctl</strong> renamed to <strong>test1.ctl</strong> <strong>enc2.ctl</strong> renamed to <strong>test2.ctl</strong> </p> <p>How do i do that?</p> <hr> <p>@Akelunuk: Thanks, that w kind of works but i have files names as </p> <p><strong>h263_enc_random_pixels_1.ctl , h263_enc_random_pixels_2.ctl</strong> which i want to rename to</p> <p><strong>test1.ctl and test2.ctl</strong> respectively </p> <p>Then how?</p>
[ { "answer_id": 191420, "author": "David Nehme", "author_id": 14167, "author_profile": "https://Stackoverflow.com/users/14167", "pm_score": 2, "selected": true, "text": "for /L %1 in (1,1,10) do ren enc%1.ctl test%1.ctl\n" }, { "answer_id": 191451, "author": "akalenuk", "author_id": 25459, "author_profile": "https://Stackoverflow.com/users/25459", "pm_score": 2, "selected": false, "text": "for %1 in (.) do ren %1 t%1\n ren tenc*.* test*.*\n" }, { "answer_id": 191620, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 1, "selected": false, "text": "var path= \"E:/tmp\";\n\nvar fso = WScript.CreateObject(\"Scripting.FileSystemObject\");\nvar folder = fso.GetFolder(path);\nvar files = new Enumerator(folder.files);\nfor (; !files.atEnd(); files.moveNext())\n{\n var file = files.item();\n var fileName = file.Name;\n var p = /^enc(\\d+)\\.ctl$/.exec(fileName);\n if (p != null)\n {\n var newFileName = \"test\" + p[1] + \".ctl\";\n // Optional feedback\n WScript.echo(fileName + \" -----> \" + newFileName);\n file.Move(newFileName);\n }\n}\n file.Copy(file.ParentFolder + \"/SO/\" + newFileName);" }, { "answer_id": 39759575, "author": "Yousef Rabby RJ", "author_id": 6896699, "author_profile": "https://Stackoverflow.com/users/6896699", "pm_score": 0, "selected": false, "text": "@echo ON\ncls\nfor %%a in (*.pdf) do (set myfiledate=%%~ta echo !myfiledate!)\n\necho Date format = %myfiledate%\necho dd = %myfiledate:~0,2%\necho mm = %myfiledate:~3,2%\necho yyyy = %myfiledate:~6,4%\necho.\necho Time format = %myfiledate%\necho hh = %myfiledate:~11,2%\necho mm = %myfiledate:~14,2%\necho AM = %myfiledate:~17,2%\necho.\necho Timestamp = %myfiledate:~0,2%_%myfiledate:~3,2%_%myfiledate:~6,4%-%myfiledate:~11,2%_%myfiledate:~14,2%_%myfiledate:~17,2%\nECHO \"TEST...\" > \"test-%myfiledate:~0,2%_%myfiledate:~3,2%_%myfiledate:~6,4%-TIME-%myfiledate:~11,2%_%myfiledate:~14,2%_%myfiledate:~17,2%.txt\"\nPAUSE\n @echo ON\nsetlocal\ncls\nfor %%a in (*.pdf) do (set myfiledate=%%~ta echo !myfiledate!)\n\n:DATETIME\necho Date format = %myfiledate%\necho dd = %myfiledate:~0,2%\necho mm = %myfiledate:~3,2%\necho yyyy = %myfiledate:~6,4%\n\necho Time format = %myfiledate%\necho hh = %myfiledate:~11,2%\necho mm = %myfiledate:~14,2%\necho AM = %myfiledate:~17,2%\n = %myfiledate:~17,2%\necho.\n\necho Timestamp = %myfiledate:~0,2%_%myfiledate:~3,2%_%myfiledate:~6,4%-%myfiledate:~11,2%_%myfiledate:~14,2%_%myfiledate:~17,2%\nECHO \"TEST...\" > \"test-%myfiledate:~0,2%_%myfiledate:~3,2%_%myfiledate:~6,4%-TIME-%myfiledate:~11,2%_%myfiledate:~14,2%_%myfiledate:~17,2%.txt\"\n\nfor /f \"delims=\" %%a in ('dir *.pdf /t:a /a:-d /b /s') do call :RENAME \"%%a\"\n\n:RENAME\nREM for /f \"tokens=1-6 delims=/ \" %%a in ('dir %%a /t:w^|find \"/\"') do (\nren %%a \"3DC-test-OFF-ELE-%myfiledate:~0,2%_%myfiledate:~3,2%_%myfiledate:~6,4%-TIME-%myfiledate:~11,2%_%myfiledate:~14,2%_%myfiledate:~17,2%~x1\")\nPAUSE\nGOTO :EOF\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191351", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2759376/" ]
191,359
<p>I need to convert a bunch of files to utf-8 in Python, and I have trouble with the "converting the file" part.</p> <p>I'd like to do the equivalent of:</p> <pre><code>iconv -t utf-8 $file &gt; converted/$file # this is shell code </code></pre> <p>Thanks!</p>
[ { "answer_id": 191403, "author": "DzinX", "author_id": 18745, "author_profile": "https://Stackoverflow.com/users/18745", "pm_score": 7, "selected": true, "text": "import codecs\nBLOCKSIZE = 1048576 # or some other, desired size in bytes\nwith codecs.open(sourceFileName, \"r\", \"your-source-encoding\") as sourceFile:\n with codecs.open(targetFileName, \"w\", \"utf-8\") as targetFile:\n while True:\n contents = sourceFile.read(BLOCKSIZE)\n if not contents:\n break\n targetFile.write(contents)\n BLOCKSIZE" }, { "answer_id": 191455, "author": "Staale", "author_id": 3355, "author_profile": "https://Stackoverflow.com/users/3355", "pm_score": 5, "selected": false, "text": "sourceEncoding = \"iso-8859-1\"\ntargetEncoding = \"utf-8\"\nsource = open(\"source\")\ntarget = open(\"target\", \"w\")\n\ntarget.write(unicode(source.read(), sourceEncoding).encode(targetEncoding))\n" }, { "answer_id": 192086, "author": "Sébastien RoccaSerra", "author_id": 2797, "author_profile": "https://Stackoverflow.com/users/2797", "pm_score": 4, "selected": false, "text": "sourceFormats UnicodeDecodeError from __future__ import with_statement\n\nimport os\nimport sys\nimport codecs\nfrom chardet.universaldetector import UniversalDetector\n\ntargetFormat = 'utf-8'\noutputDir = 'converted'\ndetector = UniversalDetector()\n\ndef get_encoding_type(current_file):\n detector.reset()\n for line in file(current_file):\n detector.feed(line)\n if detector.done: break\n detector.close()\n return detector.result['encoding']\n\ndef convertFileBestGuess(filename):\n sourceFormats = ['ascii', 'iso-8859-1']\n for format in sourceFormats:\n try:\n with codecs.open(fileName, 'rU', format) as sourceFile:\n writeConversion(sourceFile)\n print('Done.')\n return\n except UnicodeDecodeError:\n pass\n\ndef convertFileWithDetection(fileName):\n print(\"Converting '\" + fileName + \"'...\")\n format=get_encoding_type(fileName)\n try:\n with codecs.open(fileName, 'rU', format) as sourceFile:\n writeConversion(sourceFile)\n print('Done.')\n return\n except UnicodeDecodeError:\n pass\n\n print(\"Error: failed to convert '\" + fileName + \"'.\")\n\n\ndef writeConversion(file):\n with codecs.open(outputDir + '/' + fileName, 'w', targetFormat) as targetFile:\n for line in file:\n targetFile.write(line)\n\n# Off topic: get the file list and call convertFile on each file\n# ...\n" }, { "answer_id": 9200298, "author": "Ricardo", "author_id": 583064, "author_profile": "https://Stackoverflow.com/users/583064", "pm_score": 2, "selected": false, "text": "file $ file --mime jumper.xml\n\njumper.xml: application/xml; charset=utf-8\n" }, { "answer_id": 41535910, "author": "MojiProg", "author_id": 3454902, "author_profile": "https://Stackoverflow.com/users/3454902", "pm_score": 2, "selected": false, "text": "def correctSubtitleEncoding(filename, newFilename, encoding_from, encoding_to='UTF-8'):\n with open(filename, 'r', encoding=encoding_from) as fr:\n with open(newFilename, 'w', encoding=encoding_to) as fw:\n for line in fr:\n fw.write(line[:-1]+'\\r\\n')\n" }, { "answer_id": 53553157, "author": "DEX Data Explorers", "author_id": 10726534, "author_profile": "https://Stackoverflow.com/users/10726534", "pm_score": 0, "selected": false, "text": " # open the CSV file\n inputfile = open(filelocation, 'rb')\n outputfile = open(outputfilelocation, 'w', encoding='utf-8')\n for line in inputfile:\n if line[-2:] == b'\\r\\n' or line[-2:] == b'\\n\\r':\n output = line[:-2].decode('utf-8', 'replace') + '\\n'\n elif line[-1:] == b'\\r' or line[-1:] == b'\\n':\n output = line[:-1].decode('utf-8', 'replace') + '\\n'\n else:\n output = line.decode('utf-8', 'replace') + '\\n'\n outputfile.write(output)\n outputfile.close()\nexcept BaseException as error:\n cfg.log(self.outf, \"Error(18): opening CSV-file \" + filelocation + \" failed: \" + str(error))\n self.loadedwitherrors = 1\n return ([])\ntry:\n # open the CSV-file of this source table\n csvreader = csv.reader(open(outputfilelocation, \"rU\"), delimiter=delimitervalue, quoting=quotevalue, dialect=csv.excel_tab)\nexcept BaseException as error:\n cfg.log(self.outf, \"Error(19): reading CSV-file \" + filelocation + \" failed: \" + str(error))\n" }, { "answer_id": 53851783, "author": "Sole Sensei", "author_id": 9026554, "author_profile": "https://Stackoverflow.com/users/9026554", "pm_score": 4, "selected": false, "text": "import os \nfrom chardet import detect\n\n# get file encoding type\ndef get_encoding_type(file):\n with open(file, 'rb') as f:\n rawdata = f.read()\n return detect(rawdata)['encoding']\n\nfrom_codec = get_encoding_type(srcfile)\n\n# add try: except block for reliability\ntry: \n with open(srcfile, 'r', encoding=from_codec) as f, open(trgfile, 'w', encoding='utf-8') as e:\n text = f.read() # for small files, for big use chunks\n e.write(text)\n\n os.remove(srcfile) # remove old encoding file\n os.rename(trgfile, srcfile) # rename new encoding\nexcept UnicodeDecodeError:\n print('Decode Error')\nexcept UnicodeEncodeError:\n print('Encode Error')\n" }, { "answer_id": 67268768, "author": "Cesc", "author_id": 7535684, "author_profile": "https://Stackoverflow.com/users/7535684", "pm_score": 3, "selected": false, "text": " python -c \"from pathlib import Path; path = Path('yourfile.txt') ; path.write_text(path.read_text(encoding='utf16'), encoding='utf8')\"\n yourfile.txt from pathlib import Path\npath = Path(\"yourfile.txt\")\npath.write_text(path.read_text(encoding=\"utf16\"), encoding=\"utf8\")\n" }, { "answer_id": 70404526, "author": "jamlee", "author_id": 4268594, "author_profile": "https://Stackoverflow.com/users/4268594", "pm_score": 0, "selected": false, "text": "# pip install -i https://pypi.tuna.tsinghua.edu.cn/simple chardet\nimport os\nimport re\nfrom chardet import detect\n\n\ndef get_file_list(d):\n result = []\n for root, dirs, files in os.walk(d):\n dirs[:] = [d for d in dirs if d not in ['venv', 'cmake-build-debug']]\n for filename in files:\n # your filter\n if re.search(r'(\\.c|\\.cpp|\\.h|\\.txt)$', filename):\n result.append(os.path.join(root, filename))\n return result\n\n\n# get file encoding type\ndef get_encoding_type(file):\n with open(file, 'rb') as f:\n raw_data = f.read()\n return detect(raw_data)['encoding']\n\n\nif __name__ == \"__main__\":\n file_list = get_file_list('.')\n for src_file in file_list:\n print(src_file)\n trg_file = src_file + '.swp'\n from_codec = get_encoding_type(src_file)\n try:\n with open(src_file, 'r', encoding=from_codec) as f, open(trg_file, 'w', encoding='utf-8') as e:\n text = f.read()\n e.write(text)\n os.remove(src_file)\n os.rename(trg_file, src_file)\n except UnicodeDecodeError:\n print('Decode Error')\n except UnicodeEncodeError:\n print('Encode Error')\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2797/" ]
191,364
<p>Trying to debug an issue with a server and my only log file is a 20GB log file (with no timestamps even! Why do people use <code>System.out.println()</code> as logging? In production?!)</p> <p>Using grep, I've found an area of the file that I'd like to take a look at, line 347340107.</p> <p>Other than doing something like</p> <pre><code>head -&lt;$LINENUM + 10&gt; filename | tail -20 </code></pre> <p>... which would require <code>head</code> to read through the first 347 million lines of the log file, is there a quick and easy command that would dump lines 347340100 - 347340200 (for example) to the console?</p> <p><strong>update</strong> I totally forgot that grep can print the context around a match ... this works well. Thanks!</p>
[ { "answer_id": 191397, "author": "itsmatt", "author_id": 7862, "author_profile": "https://Stackoverflow.com/users/7862", "pm_score": 5, "selected": false, "text": "tail -n +347340107 filename | head -n 100\n" }, { "answer_id": 191440, "author": "mweerden", "author_id": 4285, "author_profile": "https://Stackoverflow.com/users/4285", "pm_score": 2, "selected": false, "text": "sed -e '1,N d; M q' grep -C" }, { "answer_id": 191449, "author": "Sklivvz", "author_id": 7028, "author_profile": "https://Stackoverflow.com/users/7028", "pm_score": 9, "selected": false, "text": "sed -n '20,40p;41q' file_name\n awk 'FNR>=20 && FNR<=40' file_name\n sed sed 41q" }, { "answer_id": 191797, "author": "Luka Marinko", "author_id": 19814, "author_profile": "https://Stackoverflow.com/users/19814", "pm_score": 4, "selected": false, "text": "$ split --lines=50000 /path/to/large/file /path/to/output/file/prefix\n" }, { "answer_id": 204790, "author": "unwind", "author_id": 28169, "author_profile": "https://Stackoverflow.com/users/28169", "pm_score": 5, "selected": false, "text": "head grep grep head head" }, { "answer_id": 17367226, "author": "WCC", "author_id": 1102552, "author_profile": "https://Stackoverflow.com/users/1102552", "pm_score": 7, "selected": false, "text": "# print line number 52\nsed -n '52p' # method 1\nsed '52!d' # method 2\nsed '52q;d' # method 3, efficient on large files \n" }, { "answer_id": 18093093, "author": "sehe", "author_id": 85371, "author_profile": "https://Stackoverflow.com/users/85371", "pm_score": 4, "selected": false, "text": "less :43210 vim" }, { "answer_id": 28302773, "author": "Keithel", "author_id": 2701456, "author_profile": "https://Stackoverflow.com/users/2701456", "pm_score": 2, "selected": false, "text": ".bash_aliases function middle()\n{\n startidx=$1\n len=$2\n endidx=$(($startidx+$len))\n filename=$3\n\n awk \"FNR>=${startidx} && FNR<=${endidx} { print NR\\\" \\\"\\$0 }; FNR>${endidx} { print \\\"END HERE\\\"; exit }\" $filename\n}\n" }, { "answer_id": 28383283, "author": "osirisgothra", "author_id": 549506, "author_profile": "https://Stackoverflow.com/users/549506", "pm_score": 1, "selected": false, "text": "<textfile> <line#> perl -wne 'print if $. == <line#>' <textfile>\n perl -wne 'print if m/<regex1>/ .. m/<regex2>/' <filename>\n / m!<regex>! <filename> <regex1> <regex2>" }, { "answer_id": 31723186, "author": "Ramana Reddy", "author_id": 4894197, "author_profile": "https://Stackoverflow.com/users/4894197", "pm_score": 2, "selected": false, "text": "x=`cat -n <file> | grep <match> | awk '{print $1}'`\n awk -v var=\"$x\" 'NR>=var && NR<=var+100{print}' <file>\n sed -n \"${x},${x+100}p\" <file>\n" }, { "answer_id": 33272897, "author": "Fritz Dodoo", "author_id": 5474151, "author_profile": "https://Stackoverflow.com/users/5474151", "pm_score": 0, "selected": false, "text": "egrep -n \"*\" <filename> | egrep \"<line number>\"\n" }, { "answer_id": 36179770, "author": "dagelf", "author_id": 764312, "author_profile": "https://Stackoverflow.com/users/764312", "pm_score": 0, "selected": false, "text": "perl -e 'while(<>){if(++$l~~[1,3,5]){print}}' < /etc/passwd\n" }, { "answer_id": 38250006, "author": "kenorb", "author_id": 55075, "author_profile": "https://Stackoverflow.com/users/55075", "pm_score": 4, "selected": false, "text": "ex ex +2p -scq file.txt\n sed -n '2p' file.txt ex +2,5p -scq file.txt\n sed -n '2,5p' file.txt ex +5,p -scq file.txt\n sed -n '2,$p' file.txt ex +2,4p +6,8p -scq file.txt\n sed -n '2,4p;6,8p' file.txt seq 1 20 > file.txt\n + -c -s q -c ! -scq!" }, { "answer_id": 48709493, "author": "eel ghEEz", "author_id": 80772, "author_profile": "https://Stackoverflow.com/users/80772", "pm_score": 0, "selected": false, "text": "file=FILE\nlineno=LINENO\nwb=\"107\"; bf=\"30;1\"; rb=\"101\"; yb=\"103\"\ncat -n ${file} | { GREP_COLORS=\"se=${wb};${bf}:cx=${wb};${bf}:ms=${rb};${bf}:sl=${yb};${bf}\" grep --color -C 10 \"^[[:space:]]\\\\+${lineno}[[:space:]]\"; }\n" }, { "answer_id": 49246288, "author": "Odeyin", "author_id": 9482464, "author_profile": "https://Stackoverflow.com/users/9482464", "pm_score": 3, "selected": false, "text": "ack $ sudo apt-get install ack-grep\n $ ack --lines=$START-$END filename\n $ ack --lines=10-20 filename\n $ man ack --lines=NUM\n Only print line NUM of each file. Multiple lines can be given with multiple --lines options or as a comma separated list (--lines=3,5,7). --lines=4-7 also works. \n The lines are always output in ascending order, no matter the order given on the command line.\n" }, { "answer_id": 50940642, "author": "Roopa", "author_id": 6774155, "author_profile": "https://Stackoverflow.com/users/6774155", "pm_score": 4, "selected": false, "text": "head -100 filename | tail -1\n" }, { "answer_id": 71393963, "author": "jarppa", "author_id": 1609063, "author_profile": "https://Stackoverflow.com/users/1609063", "pm_score": 1, "selected": false, "text": "sed -n '5p' file.txt\nsed '5q' file.txt\n `sed '5d' file.txt\n #!/bin/bash\n#removeline.sh\n#remove deleting it comes move line xD\n\nusage() { # Function: Print a help message.\n echo \"Usage: $0 -l LINENUMBER -i INPUTFILE [ -o OUTPUTFILE ]\"\n echo \"line is removed from INPUTFILE\"\n echo \"line is appended to OUTPUTFILE\"\n}\nexit_abnormal() { # Function: Exit with error.\n usage\n exit 1\n}\n\nwhile getopts l:i:o:b flag\ndo\n case \"${flag}\" in\n l) line=${OPTARG};;\n i) input=${OPTARG};;\n o) output=${OPTARG};;\n esac\ndone\n\nif [ -f tmp ]; then\necho \"Temp file:tmp exist. delete it yourself :)\"\nexit\nfi\n\nif [ -f \"$input\" ]; then\n re_isanum='^[0-9]+$'\n if ! [[ $line =~ $re_isanum ]] ; then\n echo \"Error: LINENUMBER must be a positive, whole number.\"\n exit 1\n elif [ $line -eq \"0\" ]; then\n echo \"Error: LINENUMBER must be greater than zero.\"\n exit_abnormal\n fi\n if [ ! -z $output ]; then\n sed -n \"${line}p\" $input >> $output\n fi\n if [ ! -z $input ]; then\n # remove this sed command and this comes move line to other file\n sed \"${line}d\" $input > tmp && cp tmp $input\n fi\nfi\n\nif [ -f tmp ]; then\nrm tmp\nfi\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191364", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4249/" ]
191,368
<p>I can reset FPU's CTRL registers with this:</p> <p><a href="http://support.microsoft.com/kb/326219" rel="nofollow noreferrer">http://support.microsoft.com/kb/326219</a></p> <p>But how can I save current registers, and restore them later?</p> <p>It's from .net code..</p> <p>What I'm doing, is from Delphi calling an .net dll as an COM module. Checking the <kbd>Ctrl</kbd> registers in delphi yield one value, checking with controlfp in the .net code gives another value. What I need, is in essential is to do this:</p> <pre><code>_controlfp(_CW_DEFAULT, 0xfffff); </code></pre> <p>So my floatingpoint calculations in the .net code does not crash, but I want to restore the <kbd>Ctrl</kbd> registers when returning.</p> <p>Maybe I don't? Maybe Delphi is resetting them when needed? I blogged about this problem <a href="http://blog.neslekkim.net/2008/10/fpu-issues-when-interoping-delphi-and.html" rel="nofollow noreferrer">here</a>.</p>
[ { "answer_id": 191454, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 3, "selected": false, "text": "_controlfp() _controlfp()" }, { "answer_id": 198658, "author": "Jim", "author_id": 22722, "author_profile": "https://Stackoverflow.com/users/22722", "pm_score": 4, "selected": true, "text": "uses\n SysUtils;\n\nvar\n SavedCW: Word;\nbegin\n SavedCW := Get8087CW;\n try\n Set8087CW($027f);\n // Call .NET code here\n finally\n Set8087CW(SavedCW);\n end;\nend;\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191368", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3308/" ]
191,376
<p>I am still trying to wrap my head around design patterns and for the second time I'm coming up against the same problem that seems to be crying out for a pattern solution. </p> <p>I have an accounts system with multiple account types. We have restaurant, hotel, service_provider, and consumer account types. Im sure there will be more business account types in the future, and of course there's a global administrator account.</p> <p>So what I'm wondering is how to implement the switching of account types. Eg. each account will have one or more profiles, but the profile will be different depending on the account type. What kind class relationships should I use here to deal with the multiple types of account - polymorphism or inheritance?</p> <p>It seems like maybe there should be an abstract base Profile class that the other profiles should extend, but I'm not sure how to implement that (eg a join table between profile types and account types?).</p> <p>It also feels like an opportunity to implement the factory pattern, I'm just not sure really how to go about it.</p> <p>Any ideas please?</p> <pre><code>* * </code></pre> <p><em>Edited to provide some examples as suggested:</em></p> <pre><code>Account -&gt; hasMany -&gt; Users Account -&gt; belongsTo -&gt; AccountType Account -&gt; hasOne -&gt; Profile </code></pre> <p>The profile is different depending on what type of account it is, eg an account of type restaurant will have a menu, a wine list etc, an account of type hotel will have room types, amenities, an account of type consumer will have personal tastes, home country etc.</p> <p>The question was what design pattern would best implement these relationships. </p> <p>Hope thats clearer, thanks!</p>
[ { "answer_id": 192666, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 0, "selected": false, "text": "User <<--> Account\nAccount <<--> AccountType\nAccount <--> Profile\nProfile <<--> ProfileType\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191376", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
191,383
<p>For PHP</p> <p>I have a date I want line wrapped.</p> <p>I have $date = '2008-09-28 9:19 pm'; I need the first space replaced with a br to become </p> <pre><code>2008-09-28&lt;br&gt;9:19 pm </code></pre> <p>If it wasn't for that second space before PM, I would just str_replace() it. </p>
[ { "answer_id": 192666, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 0, "selected": false, "text": "User <<--> Account\nAccount <<--> AccountType\nAccount <--> Profile\nProfile <<--> ProfileType\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13704/" ]
191,390
<p>I'm about to inherit a rather large Java enterprise project that has a large amount of third party dependencies. There is at least seventy JARs included and some of them would seem to be unused e.g. spring.jar which I know isn't used.</p> <p>It seems that over the years as various developers have touched upon the code base they have all tried out new project-of-the-month type libraries.</p> <p><strong>How does one go about getting rid of these?</strong> Within reason of course, as clearly some dependencies are helpful to not have to re-invent the wheel. </p> <p>I'm obviously interested in java based projects but I'm welcome to answers across languages that people think will be helpful.</p>
[ { "answer_id": 191672, "author": "Adam Crume", "author_id": 25498, "author_profile": "https://Stackoverflow.com/users/25498", "pm_score": 1, "selected": false, "text": "[Opened C:\\Program Files\\Java\\jre1.6.0_04\\lib\\rt.jar]\n[Loaded java.util.regex.Pattern$Single from C:\\Program Files\\Java\\jre1.6.0_04\\lib\\rt.jar]\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191390", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1915/" ]
191,399
<p>How do I change the Read-only file attribute for each file in a folder using c#?</p> <p>Thanks</p>
[ { "answer_id": 191423, "author": "Jeffrey L Whitledge", "author_id": 10174, "author_profile": "https://Stackoverflow.com/users/10174", "pm_score": 4, "selected": false, "text": "foreach (string fileName in System.IO.Directory.GetFiles(path))\n{\n System.IO.FileInfo fileInfo = new System.IO.FileInfo(fileName);\n\n fileInfo.Attributes |= System.IO.FileAttributes.ReadOnly;\n // or\n fileInfo.IsReadOnly = true;\n}\n" }, { "answer_id": 191460, "author": "mathieu", "author_id": 971, "author_profile": "https://Stackoverflow.com/users/971", "pm_score": 3, "selected": false, "text": "public void Recurse(DirectoryInfo directory)\n{\n foreach (FileInfo fi in directory.GetFiles())\n {\n fi.IsReadOnly = false; // or true\n }\n\n foreach (DirectoryInfo subdir in directory.GetDirectories())\n {\n Recurse(subdir);\n }\n}\n" }, { "answer_id": 17674053, "author": "Mike", "author_id": 1699543, "author_profile": "https://Stackoverflow.com/users/1699543", "pm_score": 1, "selected": false, "text": "Directory.EnumerateFiles(path, \"*.txt\").ToList().ForEach(file => new FileInfo(file).Attributes = FileAttributes.Normal);\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
191,400
<p>I have around 25 worksheets in my workbook (Excel spreadsheet). Is there a way I can protect all the 25 worksheets in single click ? or this feature is not available and I will have to write a VBA code to accomplish this. I need very often to protect all sheets and unprotect all sheets and doing individually is time consuming</p>
[ { "answer_id": 191416, "author": "Ben Hoffstein", "author_id": 4482, "author_profile": "https://Stackoverflow.com/users/4482", "pm_score": 5, "selected": true, "text": "Dim ws as Worksheet\nDim pwd as String\n\npwd = \"\" ' Put your password here\nFor Each ws In Worksheets\n ws.Protect Password:=pwd\nNext ws\n Dim ws as Worksheet\nDim pwd as String\n\npwd = \"\" ' Put your password here\nFor Each ws In Worksheets\n ws.Unprotect Password:=pwd\nNext ws\n" }, { "answer_id": 34207413, "author": "ChrisB", "author_id": 5640342, "author_profile": "https://Stackoverflow.com/users/5640342", "pm_score": 2, "selected": false, "text": "Dim ws as Worksheet\nDim pwd as String\n\npwd = \"\" ' Put your password here\nor Each ws In Worksheets\n ws.Protect Password:=pwd, UserInterfaceOnly:=True\nNext ws\n Dim ws as Worksheet\nDim pwd as String\n\npwd = \"\" ' Put your password here\nFor Each ws In Worksheets\n ws.Unprotect Password:=pwd\nNext ws\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17266/" ]
191,404
<p>I have been asking myself this question for a long time now. Thought of posting it. C# doesn't support Multiple Inheritance(this is the fact). All classes created in C# derive out of 'Object' class(again a fact).</p> <p>So if C# does not support Multiple inheritance, then how are we able to extend a class even though it already extends Object class?</p> <p>Illustating with an example: </p> <ol> <li>class A : object - Class A created.</li> <li>class B : object - Class B created.</li> <li>class A : B - this again is supported. What happens to the earlier association to object.</li> </ol> <p>We are able to use object class methods in A after step 3. So is the turned to multi level inheritance. If that is the case, then</p> <ol> <li>class A : B</li> <li>class C : B</li> <li>class A : C - I must be able to access class B's methods in A. Which is not the case?</li> </ol> <p>Can anyone please explain?</p>
[ { "answer_id": 191450, "author": "David Basarab", "author_id": 2469, "author_profile": "https://Stackoverflow.com/users/2469", "pm_score": 0, "selected": false, "text": "public class A : B\n{\n\n}\n\npublic class B : C\n{\n public int BProperty { get; set; }\n}\n\npublic class C\n{\n public int CProperty { get; set; }\n}\n\npublic class Test\n{\n public void TestStuff()\n {\n A a = new A();\n\n // These are valid.\n a.CProperty = 1;\n a.BProperty = 2;\n }\n\n}\n" }, { "answer_id": 191466, "author": "harpo", "author_id": 4525, "author_profile": "https://Stackoverflow.com/users/4525", "pm_score": 2, "selected": false, "text": "public class A\n public class A : System.Object\n public class A : B\n public class B : System.Object\n" }, { "answer_id": 191513, "author": "jop", "author_id": 11830, "author_profile": "https://Stackoverflow.com/users/11830", "pm_score": 0, "selected": false, "text": "class C {}\n class C : Object {}\n class B : C {}\n class A : B {}\n class C {}\nclass B : C {}\nclass A : B {}\n" }, { "answer_id": 191521, "author": "Scott Dorman", "author_id": 1559, "author_profile": "https://Stackoverflow.com/users/1559", "pm_score": 4, "selected": true, "text": "public class BaseClass { }\n\npublic class SpecialBaseClass : BaseClass {}\n\npublic class SpecialtyDerivedClass : SpecialBaseClass {}\n public class BaseClass { }\n\npublic class SpecialBaseClass {}\n\npublic class SpecialtyDerivedClass : BaseClass, SpecialBaseClass {}\n public class BaseClass { }\n\npublic interface ISpecialBase {}\n\npublic interface ISpecialDerived {}\n\npublic class SpecialtyDerivedClass : BaseClass, ISpecialBase, ISpecialDerived {}\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191404", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21995/" ]
191,413
<p>I'm just starting to wean myself from ASP.NET UpdatePanels. I'm using jQuery and jTemplates to bind the results of a web service to a grid, and everything works fine. </p> <p>Here's the thing: I'm trying to show a spinner GIF while the table is being refreshed (à la UpdateProgress in ASP.NET) I've got it all working, except that the spinner is frozen. To see what's going on, I've tried moving the spinner out from the update progress div and out on the page where I can see it the whole time. It spins and spins until the refresh starts, and stays frozen until the refresh is done, and then starts spinning again. Not really what you want from a 'please wait' spinner!</p> <p>This is in IE7 - haven't had a chance to test in other browsers yet. Any thoughts? Is the ajax call or the client-side databinding so resource-intensive that the browser is unable to tend to its animated GIFs?</p> <h3>Update</h3> <p>Here's the code that refreshes the grid. Not sure if this is synchronous or asynchronous.</p> <pre><code>updateConcessions = function(e) { $.ajax({ type: "POST", url: "Concessions.aspx/GetConcessions", data: "{'Countries':'ga'}", contentType: "application/json; charset=utf-8", dataType: "json", success: function(msg) { applyTemplate(msg); }, error: function(XMLHttpRequest, textStatus, errorThrown) { } }); } applyTemplate = function(msg) { $('div#TemplateTarget').setTemplate($('div#TemplateSource').html()); $('div#TemplateTarget').processTemplate(msg); } </code></pre> <h3>Update 2</h3> <p>I just checked the <a href="http://docs.jquery.com/Ajax/jQuery.ajax#options" rel="noreferrer">jQuery documentation</a> and the <code>$.ajax()</code> method is asynchronous by default. Just for kicks I added this</p> <pre><code>$.ajax({ async: true, ... </code></pre> <p>and it didn't make any difference.</p>
[ { "answer_id": 191677, "author": "David", "author_id": 26144, "author_profile": "https://Stackoverflow.com/users/26144", "pm_score": 3, "selected": false, "text": "setTimeout(\"document.images['BusyImage'].src=document.images['BusyImage'].src\",10);\n" }, { "answer_id": 191761, "author": "AnthonyWJones", "author_id": 17516, "author_profile": "https://Stackoverflow.com/users/17516", "pm_score": 3, "selected": false, "text": "System.Threading.Thread.Sleep(5000);\n" }, { "answer_id": 191887, "author": "Chase Seibert", "author_id": 7679, "author_profile": "https://Stackoverflow.com/users/7679", "pm_score": 6, "selected": true, "text": "applyTemplate = function(msg) {\n return;\n}\n" }, { "answer_id": 12202877, "author": "ruffrey", "author_id": 985414, "author_profile": "https://Stackoverflow.com/users/985414", "pm_score": 3, "selected": false, "text": "function showLoader(callback){\n $('#wherever').append(\n '<img class=\"waiting\" src=\"/path/to/gif.gif\" />'\n );\n\n callback();\n}\n\nfunction finishForm(){\n var passed = formValidate(document.forms.clientSupportReq);\n\n if(passed)\n {\n $('input#subm')\n .val('Uploading...')\n .attr('disabled','disabled');\n $('input#res').hide();\n }\n\n return passed;\n}\n$(function(){\n // on submit\n $('form#formid').submit(function(){\n var l = showLoader( function(){\n finishForm() \n });\n\n if(!l){\n $('.waiting').remove();\n }\n\n return l;\n });\n});\n" }, { "answer_id": 30917147, "author": "Venkat", "author_id": 2551594, "author_profile": "https://Stackoverflow.com/users/2551594", "pm_score": -1, "selected": false, "text": " function ajaxFn(){\n $('#status').html('WAIT... <img id=\"theImg\" src=\"page-loader.gif\" alt=\"preload\" width=\"30\" height=\"30\"/>');\n $('#status').css(\"color\",\"red\");\n $.ajax({\n url:\"MyServlet\",\n method: \"POST\",\n data: { name: $(\"textarea\").val(),\n id : $(\"input[type=text]\").val() },\n //async: false,\n success:function(response){\n //alert(response); //response is \"welcome to..\"\n $(\"#status\").text(response);\n $('#status').css(\"color\",\"green\");\n },\n complete:function(x,y){\n //alert(y)\n },\n error:function(){\n $(\"#status\").text(\"?\");\n }\n });\n}\n \n" }, { "answer_id": 33142061, "author": "yesnik", "author_id": 1921272, "author_profile": "https://Stackoverflow.com/users/1921272", "pm_score": 0, "selected": false, "text": "setTimeout(function() {\n $.get('/some_link', function (response) {\n // some actions\n });\n}, 0);\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191413", "https://Stackoverflow.com", "https://Stackoverflow.com/users/239663/" ]
191,421
<p>I am using SQL Server 2005. I want to constrain the values in a column to be unique, while allowing NULLS.</p> <p>My current solution involves a unique index on a view like so:</p> <pre><code>CREATE VIEW vw_unq WITH SCHEMABINDING AS SELECT Column1 FROM MyTable WHERE Column1 IS NOT NULL CREATE UNIQUE CLUSTERED INDEX unq_idx ON vw_unq (Column1) </code></pre> <p>Any better ideas? </p>
[ { "answer_id": 191729, "author": "onedaywhen", "author_id": 15354, "author_profile": "https://Stackoverflow.com/users/15354", "pm_score": 6, "selected": false, "text": "CREATE TABLE dupNulls (\npk int identity(1,1) primary key,\nX int NULL,\nnullbuster as (case when X is null then pk else 0 end),\nCONSTRAINT dupNulls_uqX UNIQUE (X,nullbuster)\n)\n" }, { "answer_id": 3191576, "author": "Phil Haselden", "author_id": 1899, "author_profile": "https://Stackoverflow.com/users/1899", "pm_score": 7, "selected": false, "text": "CREATE UNIQUE INDEX AK_MyTable_Column1 ON MyTable (Column1) WHERE Column1 IS NOT NULL\n" }, { "answer_id": 28688808, "author": "roy", "author_id": 760150, "author_profile": "https://Stackoverflow.com/users/760150", "pm_score": -1, "selected": false, "text": "create table the_entity_incorrect\n(\n id integer,\n uniqnull integer null, /* we want this to be \"unique and nullable\" */\n primary key (id)\n);\n create table the_entity\n(\n id integer,\n primary key(id)\n);\n\ncreate table the_relation\n(\n the_entity_id integer not null,\n uniqnull integer not null,\n\n unique(the_entity_id),\n unique(uniqnull),\n /* primary key can be both or either of the_entity_id or uniqnull */\n primary key (the_entity_id, uniqnull), \n foreign key (the_entity_id) references the_entity(id)\n);\n start transaction;\ninsert into the_entity (id) values (3); \ninsert into the_relation (the_entity_id, uniqnull) values (3, 5);\ncommit;\n start transaction;\ninsert into the_entity (id) values (10); \ncommit;\n select\n id, uniqnull\nfrom\n the_entity left outer join the_relation\non\n the_entity.id = the_relation.the_entity_id\n;\n" }, { "answer_id": 66320752, "author": "Martin Staufcik", "author_id": 1882699, "author_profile": "https://Stackoverflow.com/users/1882699", "pm_score": 1, "selected": false, "text": "CREATE TABLE Table1 (\n NullableCol int NULL\n)\n\nCREATE UNIQUE INDEX IX_Table1 ON Table1 (NullableCol) WHERE NullableCol IS NOT NULL;\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191421", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20959/" ]
191,428
<p>Is it possible to change the language of system messages from PostgreSQL?</p> <p>In MSSQL for instance this is possible with the SQL statement <a href="http://msdn.microsoft.com/en-us/library/ms174398.aspx" rel="noreferrer">SET LANGUAGE</a>.</p>
[ { "answer_id": 191958, "author": "Milen A. Radev", "author_id": 15785, "author_profile": "https://Stackoverflow.com/users/15785", "pm_score": 6, "selected": false, "text": "SET lc_messages TO 'en_US.UTF-8';\n" }, { "answer_id": 36998716, "author": "user1", "author_id": 2377652, "author_profile": "https://Stackoverflow.com/users/2377652", "pm_score": 5, "selected": false, "text": "postgresql.conf sudo find / -iname postgresql.conf\n /var/lib/pgsql/data lc_messages 'en_US.UTF-8' invalid value for parameter \"lc_messages\": \"en_US.UTF-8\"\n /etc/locale.gen en_US.UTF-8 locale-gen locale -a lc_messages = 'C'" }, { "answer_id": 56811670, "author": "AndreKR", "author_id": 476074, "author_profile": "https://Stackoverflow.com/users/476074", "pm_score": 5, "selected": false, "text": "PostgreSQL\\11\\data\\postgresql.conf lc_messages = 'random value' PostgreSQL\\11\\share\\locale\\*\\LC_MESSAGES" }, { "answer_id": 59288926, "author": "Birgit Vera Schmidt", "author_id": 1961209, "author_profile": "https://Stackoverflow.com/users/1961209", "pm_score": 3, "selected": false, "text": "setx LC_MESSAGES English /m\n" }, { "answer_id": 69787330, "author": "invzbl3", "author_id": 8370915, "author_profile": "https://Stackoverflow.com/users/8370915", "pm_score": 1, "selected": false, "text": "PostgreSQL Intellij IDEA C:\\Program Files\\PostgreSQL\\13\\share\\locale Intellij Idea IDE" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191428", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3565/" ]
191,429
<p>I'm trying to use <a href="http://www.glish.com/css/9.asp" rel="nofollow noreferrer">this</a> layout with two 50% column width instead. But it seems that when the right columns reaches its 'min-width', it goes under the left column. Is there any way to use the 'shim' technique to set a min-width to the wrapper so both columns stop resizing. Thus, eliminating the problem of the right column finding itself under the left column.</p> <p>My page is as follows.</p> <pre><code>&lt;style type="text/css"&gt; #left { float: left; width: 50%; } .minwidth { width: 500px; height: 0; line-height: 0; } &lt;/style&gt; &lt;div id="wrapper"&gt; &lt;div id="left"&gt; left &lt;/div&gt; &lt;div id="right"&gt; right &lt;/div&gt; &lt;div class="minwidth"&gt;&amp;nbsp;&lt;/div&gt; &lt;/div&gt; </code></pre> <p>The issue with that is the left column will stop resizing, but the right column will go below the left column and keep resizing. Basically, the effect that I want is once the wrappers width goes bellow, that both left, and right columns also stop resizing. Putting the shim in both left and right columns did not work either.</p> <p>Is there possibly another way of going abouts getting two 50% width columns and using a shim to properly set a min width?</p> <p>Thank you.</p> <p>Edit: The whitespace in the minwidth class is actually &amp;nbsp but it got converted. ;)</p>
[ { "answer_id": 191540, "author": "Robert K", "author_id": 24950, "author_profile": "https://Stackoverflow.com/users/24950", "pm_score": 1, "selected": false, "text": ".left, .right { width:50%; float: left; }\n.right { float: right; }\n.minwidth { min-width: 500px; display: block; height: 0; clear: both; }\n" }, { "answer_id": 191553, "author": "slashnick", "author_id": 21030, "author_profile": "https://Stackoverflow.com/users/21030", "pm_score": 1, "selected": false, "text": "<head>\n<style type=\"text/css\">\n\n#left {\n float: left;\n width: 50%;\n}\n\n.minwidth {\n min-width: 500px;\n background:#eee;\n height: 0;\n overflow:visible;\n}\n.col{\n min-width:250px;\n background:#eaa;\n}\n\n</style>\n</head>\n<body>\n<div id=\"wrapper\" class=\"minwidth\">\n <div id=\"left\" class=\"col\">\n left\n </div>\n <div id=\"right\" class=\"col\">\n right\n </div>\n <div><!-- Not needed --></div>\n</div>\n</body>\n" }, { "answer_id": 191577, "author": "willasaywhat", "author_id": 12234, "author_profile": "https://Stackoverflow.com/users/12234", "pm_score": 1, "selected": false, "text": "<html>\n<head>\n<title>Testing some CSS</title>\n<style type=\"text/css\">\n\n.floatme {\n float: left;\n width: 50%;\n}\n\n.minwidth {\n width: 500px;\n height: 0;\n line-height: 0;\n clear: both;\n}\n\n</style>\n\n\n<body>\n<div id=\"wrapper\">\n <div class=\"floatme\">\n left\n </div>\n <div id=\"floatme\">\n right\n </div>\n <div class=\"minwidth\"> </div>\n</div>\n</body>\n</html>\n" }, { "answer_id": 230152, "author": "adgoudz", "author_id": 30527, "author_profile": "https://Stackoverflow.com/users/30527", "pm_score": 4, "selected": true, "text": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n<html>\n<head>\n <style type=\"text/css\">\n\n /* For browsers that understand min-width */\n .width {\n width: 100%;\n min-width: 500px;\n }\n\n /* IE6 Only */\n * html .minwidth {\n border-left: 500px solid white;\n position: relative;\n float: left;\n }\n\n /* IE6 Only */\n * html .wrapper {\n margin-left: -500px;\n position: relative;\n float: left;\n }\n\n .left {\n float: left;\n width: 50%;\n }\n\n .right {\n float: left;\n }\n\n </style>\n</head>\n<body>\n\n<div class=\"width\">\n <div class=\"minwidth\">\n <div class=\"wrapper\">\n <div class=\"left\">\n Left\n </div>\n <div class=\"right\">\n Right\n </div>\n </div>\n </div>\n</div>\n\n</body>\n</html>\n" }, { "answer_id": 1622334, "author": "Patrick Desjardins", "author_id": 13913, "author_profile": "https://Stackoverflow.com/users/13913", "pm_score": 1, "selected": false, "text": "/* Start of Column CSS */\n#container2 {\n clear:left;\n float:left;\n width:100%;\n overflow:hidden;\n background:#ffa7a7; /* column 2 background colour */\n}\n#container1 {\n float:left;\n width:100%;\n position:relative;\n right:50%;\n background:#fff689; /* column 1 background colour */\n}\n#col1 {\n float:left;\n width:46%;\n position:relative;\n left:52%;\n overflow:hidden;\n}\n#col2 {\n float:left;\n width:46%;\n position:relative;\n left:56%;\n overflow:hidden;\n}\n <div id=\"container2\">\n <div id=\"container1\">\n <div id=\"col1\">\n <!-- Column one start -->\n <h2>Equal height columns</h2>\n <p>It does not matter how much content is in each column, the background colours will always stretch down to the height of the tallest column.</p>\n\n <h2>Valid XHTML strict markup</h2>\n <p>The HTML in this layout validates as XHTML 1.0 strict.</p>\n <!-- Column one end -->\n </div>\n <div id=\"col2\">\n <!-- Column two start -->\n <h3>Windows</h3>\n <ul>\n <li>Firefox 1.5, 2 &amp; 3</li>\n <li>Safari</li>\n <li>Opera 8 &amp; 9</li>\n\n <li>Explorer 5.5, 6 &amp; 7</li>\n <li>Google Chrome</li>\n <li>Netscape 8</li>\n </ul>\n\n\n <!-- Column two end -->\n </div>\n </div>\n</div>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191429", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25371/" ]
191,463
<p>This seems like the most basic question in the world, but damned if I can find an answer.</p> <p>Is there a keyboard shortcut, either native to Visual Studio or through Code Rush or other third-party plug-in, to wrap the current selection with an HTML tag? I'm tired of typing the opening tag, cutting the misplaced closing tag to the clipboard, moving the cursor, and pasting it at the end where it belongs.</p> <p><strong>Update:</strong> <a href="http://screencast.com/t/pesxOgON" rel="noreferrer">This is how TextMate handles surrounding a selection with a tag</a>. Frankly, I'm stunned that Visual Studio doesn't seem to have a similar feature. Creating a macro or snippet for every conceivable tag I might want to use seems absurd.</p>
[ { "answer_id": 2879206, "author": "Bradley Mountford", "author_id": 302103, "author_profile": "https://Stackoverflow.com/users/302103", "pm_score": 6, "selected": false, "text": "ctrl-k ctrl-s Surround with... File New XML File Save Save as All Files (*.*) File name .snippet Save <CodeSnippet Format=\"1.1.0\" xmlns=\"http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet\">\n <Header>\n <Title>ul-div</Title>\n <Author>Microsoft Corporation</Author>\n <Shortcut>ul>li</Shortcut>\n <Description>Wrap in a ul and then an li</Description>\n <SnippetTypes>\n <SnippetType>Expansion</SnippetType>\n <SnippetType>SurroundsWith</SnippetType>\n </SnippetTypes>\n </Header>\n <Snippet>\n <Declarations>\n <Literal>\n <ID>selected</ID>\n <ToolTip>content</ToolTip>\n <Default>content</Default>\n </Literal>\n </Declarations>\n <Code Language=\"html\"><![CDATA[<ul><li>$selected$</li></ul>$end$]]></Code>\n </Snippet>\n</CodeSnippet>\n Tools Code Snippets Manager Import My HTML Snippets Finish OK" }, { "answer_id": 5512631, "author": "Chao", "author_id": 300996, "author_profile": "https://Stackoverflow.com/users/300996", "pm_score": 3, "selected": false, "text": "<CodeSnippet Format=\"1.1.0\" xmlns=\"http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet\">\n <!-- Generic HTML Snippet -->\n <Header>\n <Title>Html</Title>\n <Author>Liam Slater</Author>\n <Shortcut>h</Shortcut>\n <Description>Markup snippet for HTML</Description>\n <SnippetTypes>\n <SnippetType>SurroundsWith</SnippetType>\n </SnippetTypes>\n </Header>\n <Snippet>\n <Declarations>\n <Literal>\n <ID>tag</ID>\n <ToolTip>tag</ToolTip>\n <Default></Default>\n </Literal>\n <Literal>\n <ID>selected</ID>\n <ToolTip>content</ToolTip>\n <Default>content</Default>\n </Literal>\n </Declarations>\n <Code Language=\"html\"><![CDATA[<$tag$>$selected$</$tag$>$end$]]></Code>\n </Snippet>\n</CodeSnippet>\n" }, { "answer_id": 36803516, "author": "djones", "author_id": 1647159, "author_profile": "https://Stackoverflow.com/users/1647159", "pm_score": 8, "selected": true, "text": "Shift+Alt+W > p > Enter\n" }, { "answer_id": 43863928, "author": "Burak Karakuş", "author_id": 1817929, "author_profile": "https://Stackoverflow.com/users/1817929", "pm_score": 3, "selected": false, "text": "html cshtml Wrap With <div>" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191463", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1923/" ]
191,482
<p>I'm trying to build a similar 'slider' as demoed here <a href="http://ui.jquery.com/repository/real-world/product-slider/" rel="nofollow noreferrer">http://ui.jquery.com/repository/real-world/product-slider/</a> but I'm trying to use interior divs inside of the list items (<code>&lt;li&gt;</code>). it seems as if this demo breaks if you're not using an image or block element (<code>&lt;p&gt;</code>,<code>&lt;div&gt;</code>,etc.)</p> <p>Anyone have any quick solutions to this? I basically want to use text and possibly images inside of a <code>&lt;div&gt;</code> instead of using images.</p> <p>I did find jCarousel which seems as if it works, but I was looking for something a little more lightweight? Any ideas?</p>
[ { "answer_id": 196871, "author": "Rudi", "author_id": 22830, "author_profile": "https://Stackoverflow.com/users/22830", "pm_score": 2, "selected": false, "text": " <div class=\"sliderGallery\">\n <div class=\"div-that-gets-cropped\">\n <div class=\"text-and-images-chunk\">Some text!<br /><img class=\"pb-airportexpress\" src=\"slider-gallery_files/pb_airport_express.jpg\" /></div>\n <div class=\"text-and-images-chunk\">Some text!<br /><img src=\"slider-gallery_files/pb_airport_extreme.jpg\" /></div>\n <div class=\"text-and-images-chunk\">Some text!<br /><img src=\"slider-gallery_files/pb_timecapsule_20080115.jpg\" /></div>\n ...\n </div>\n window.onload = function () {\n var container = $('div.sliderGallery');\n var divThatGetsCropped = $('div.div-that-gets-cropped', container);\n var itemsWidth = divThatGetsCropped.innerWidth() - container.outerWidth();\n $('.slider', container).slider({\n minValue: 0,\n maxValue: itemsWidth,\n handle: '.handle',\n stop: function (event, ui) {\n divThatGetsCropped.animate({'left' : ui.value * -1}, 500);\n },\n slide: function (event, ui) {\n divThatGetsCropped.css('left', ui.value * -1);\n }\n });\n };\n .sliderGallery div.div-that-gets-cropped {\n position: absolute;\n list-style: none;\n overflow: none;\n white-space: nowrap;\n padding: 0;\n margin: 0;\n width: 10000px;\n }\n\n .sliderGallery div.div-that-gets-cropped div.text-and-images-chunk {\n float: left;\n margin-right: 24px;\n }\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8534/" ]
191,483
<p>I want to check the login status of a user through an ajax request. Depending wether the user is logged in I want to display either the username/password input or the username. Currently the request is sent on body.onload and a prgoress indicator is shown until the response arrives. Is there a better way?</p> <hr> <p>Let's assume that the requirements state that there should be no direct server side processing.</p>
[ { "answer_id": 191516, "author": "Neall", "author_id": 619, "author_profile": "https://Stackoverflow.com/users/619", "pm_score": 0, "selected": false, "text": "$(document).ready(function() {\n // The DOM is fully loaded now, but images might still be loading.\n});\n" }, { "answer_id": 191605, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 0, "selected": false, "text": "<HTML><HEAD>...</HEAD>\n<BODY>\n<script>\ndocument.write(\"This is written before anything else\");\n</script>\nThis come later.\n</BODY>\n</HTML>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2133/" ]
191,490
<p>I want to display the results of a searchquery in a website with a title and a short description. The short description should be a small part of the page which holds the searchterm. What i want to do is: 1 strip tags in page 2 find first position of seachterm 3 from that position, going back find the beginning (if there is one) of that sentence. 4 Start at the found position in step 3 and display ie 200 characters from there</p> <p>I need some help with step 3. I think i need an regex that finds the first capital or dot...</p>
[ { "answer_id": 191543, "author": "acrosman", "author_id": 24215, "author_profile": "https://Stackoverflow.com/users/24215", "pm_score": 1, "selected": false, "text": "$offset = stripos( strrev(substr($string, $searchlocation)), '.');\n$startloc = $searchlocation - $offset;\n$finalstring = substr($string, $startloc, 200);\n" }, { "answer_id": 71606071, "author": "Iterniam", "author_id": 5521465, "author_profile": "https://Stackoverflow.com/users/5521465", "pm_score": 0, "selected": false, "text": "Smith We went to Dr. Smith's office. This sentence is English. So is this one. (?m)(?:^|[.!?][\\t ]+)([A-Z]\\S*)\n (?m)[A-Z]\\S*\\.[^\\S\\r\\n]+[A-Z]|(?:^|[.!?][\\t ]+)([A-Z]\\S*)\n [A-Z]\\S*\\.[^\\S\\r\\n]+[A-Z]| Smith We went to Dr. Smith's office. So This is sentence is English. So is this one." } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191490", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21238/" ]
191,493
<p>I often need to design a dialog in Delphi/C++Builder that allows various properties of an object to be modified, and the code to use it typically looks like this.</p> <pre><code>Dialog.Edit1.Text := MyObject.Username; Dialog.Edit2.Text := MyObject.Password; // ... many more of the same if (Dialog.ShowModal = mrOk) begin MyObject.Username := Dialog.Edit1.Text; MyObject.Password := Dialog.Edit2.Text; // ... again, many more of the same end; </code></pre> <p>I also often need similar code for marshalling objects to/from xml/ini-files/whatever.</p> <p>Are there any common idioms or techniques for avoiding this kind of simple but repetitive code?</p>
[ { "answer_id": 191610, "author": "akalenuk", "author_id": 25459, "author_profile": "https://Stackoverflow.com/users/25459", "pm_score": 0, "selected": false, "text": "if (Dialog.ShowModal = mrOk) \nbegin\n with MyObject do\n begin\n Username := Dialog.Edit1.Text;\n Password := Dialog.Edit2.Text;\n // ... again, many more of the same\n end;\nend;\n" }, { "answer_id": 191809, "author": "mj2008", "author_id": 5544, "author_profile": "https://Stackoverflow.com/users/5544", "pm_score": 2, "selected": false, "text": "procedure TfrmFTPSetup.LoadFromXML(szFileName : string);\nvar\nxComponent : TComponent;\nnLoop : Integer;\nxMainNode : TXmlNode;\nxDocument : TNativeXml;\nbegin\ninherited;\n\nxDocument := TNativeXml.Create;\ntry\n xDocument.LoadFromFile(szFileName);\n xMainNode := xml_ChildNodeByName(xDocument.Root, 'options');\n for nLoop := 0 to ComponentCount - 1 do\n begin\n xComponent := Components[nLoop];\n if xComponent is TRzCustomEdit then\n begin\n (xComponent as TRzCustomEdit).Text := xMainNode.AttributeByName[xComponent.Name];\n end;\n if xComponent is TRzCheckBox then\n begin\n (xComponent as TRzCheckBox).Checked := xml_X2Boolean(xMainNode.AttributeByName[xComponent.Name], false);\n end;\n end;\nfinally\n FreeAndNil(xDocument);\nend;\n end;\n\n procedure TfrmFTPSetup.SaveToXML(szFileName : string);\nvar\nxComponent : TComponent;\nnLoop : Integer;\nxMainNode : TXmlNode;\nxDocument : TNativeXml;\nbegin\ninherited;\n\nxDocument := TNativeXml.CreateName('ftpcontrol');\ntry\n xMainNode := xml_ChildNodeByNameCreate(xDocument.Root, 'options');\n for nLoop := 0 to ComponentCount - 1 do\n begin\n xComponent := Components[nLoop];\n if xComponent is TRzCustomEdit then\n begin\n xMainNode.AttributeByName[xComponent.Name] := (xComponent as TRzCustomEdit).Text;\n end;\n if xComponent is TRzCheckBox then\n begin\n xMainNode.AttributeByName[xComponent.Name] := xml_Boolean2X((xComponent as TRzCheckBox).Checked);\n end;\n end;\n\n xDocument.XmlFormat := xfReadable;\n xDocument.SaveToFile(szFileName);\nfinally\n FreeAndNil(xDocument);\nend;\n end;\n" }, { "answer_id": 192008, "author": "skamradt", "author_id": 9217, "author_profile": "https://Stackoverflow.com/users/9217", "pm_score": 3, "selected": true, "text": "edit1.text := dbfield.asString;\n dbField.asString := edit1.text;\n" }, { "answer_id": 197176, "author": "dcraggs", "author_id": 4382, "author_profile": "https://Stackoverflow.com/users/4382", "pm_score": 1, "selected": false, "text": "unit Unit1;\n\ninterface\n\nuses\n Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,\n Dialogs, StdCtrls;\n\ntype\n TForm1 = class(TForm)\n Edit1: TEdit;\n Edit2: TEdit;\n private\n function GetPassword: string;\n function GetUsername: string;\n procedure SetPassword(const Value: string);\n procedure SetUsername(const Value: string);\n public\n property Password: string read GetPassword write SetPassword;\n property Username: string read GetUsername write SetUsername;\n end;\n\nvar\n Form1: TForm1;\n\nimplementation\n\n{$R *.dfm}\n\nfunction TForm1.GetPassword: string;\nbegin\n Result := Edit2.Text;\nend;\n\nfunction TForm1.GetUsername: string;\nbegin\n Result := Edit1.Text;\nend;\n\nprocedure TForm1.SetPassword(const Value: string);\nbegin\n Edit2.Text := Value;\nend;\n\nprocedure TForm1.SetUsername(const Value: string);\nbegin\n Edit1.Text := Value;\nend;\n\nend.\n unit Unit1;\n\ninterface\n\nuses\n Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,\n Dialogs, StdCtrls;\n\ntype\n TUserObject = class(TObject)\n private\n FPassword: string;\n FUsername: string;\n public\n property Password: string read FPassword write FPassword;\n property Username: string read FUsername write FUsername;\n end;\n\n TForm1 = class(TForm)\n Edit1: TEdit;\n Edit2: TEdit;\n btnOK: TButton;\n procedure btnOKClick(Sender: TObject);\n private\n FUserObject: TUserObject;\n procedure SetUserObject(const Value: Integer);\n public\n property UserObject: Integer read FUserObject write SetUserObject;\n end;\n\nvar\n Form1: TForm1;\n\nimplementation\n\n{$R *.dfm}\n\nprocedure TForm1.btnOKClick(Sender: TObject);\nbegin\n FUserObject.Username := Edit1.Text;\n FUserObject.Password := Edit2.Text;\n ModalResult := mrOK;\nend;\n\nprocedure TForm1.SetUserObject(const Value: Integer);\nbegin\n FUserObject := Value;\n Edit1.Text := FUserObject.Username;\n Edit2.Text := FUserObject.Password;\nend;\n\nend.\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191493", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1737/" ]
191,503
<p>I'm using the following code to loop through a directory to print out the names of the files. However, not all of the files are displayed. I have tried using <strong>clearstatcache</strong> with no effect.</p> <pre><code> $str = ''; $ignore = array('.', '..'); $dh = @opendir( $path ); if ($dh === FALSE) { // error } $file = readdir( $dh ); while( $file !== FALSE ) { if (in_array($file, $ignore, TRUE)) { break; } $str .= $file."\n"; $file = readdir( $dh ); } </code></pre> <p>Here's the contents of the directory right now:</p> <pre><code>root.auth test1.auth test2.auth test3.auth test5.auth </code></pre> <p>However, test5.auth does not appear. If I rename it to test4.auth it does not appear. If I rename it to test6.auth it <strong>does</strong> appear. This is reliable behaviour - I can rename it several times and it still won't show up unless I rename it to test6.auth.</p> <p>What on earth could be happening?</p> <p>I'm running Arch Linux (kernel 2.6.26-ARCH) with PHP Version 5.2.6 and Apache/2.2.9 with Suhosin-Patch. My filesystem is ext3 and I'm running fam 2.6.10.</p>
[ { "answer_id": 191535, "author": "Jacco", "author_id": 22674, "author_profile": "https://Stackoverflow.com/users/22674", "pm_score": 2, "selected": true, "text": "break continue" }, { "answer_id": 191545, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 1, "selected": false, "text": "if (in_array($file, $ignore, TRUE)) { break; }\n continue break" }, { "answer_id": 192005, "author": "Tom Haigh", "author_id": 22224, "author_profile": "https://Stackoverflow.com/users/22224", "pm_score": 2, "selected": false, "text": "$file = readdir( $dh ); while (false !== ($file = readdir($dh))) {\n if (in_array($file, $ignore, TRUE)) { continue; }\n $str .= $file.\"\\n\";\n}\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191503", "https://Stackoverflow.com", "https://Stackoverflow.com/users/840/" ]
191,528
<p>I found this:</p> <p><a href="http://www.evolt.org/failover-database-connection-with-php-mysql" rel="nofollow noreferrer">http://www.evolt.org/failover-database-connection-with-php-mysql</a></p> <p>and similar examples. But is there a better way?</p> <p>I am thinking along the lines of the <a href="http://www.microsoft.com/technet/prodtechnol/sql/bestpractice/implappfailover.mspx#EMD" rel="nofollow noreferrer">Automatic Failover Client</a> in the MS SQL Native Client.</p>
[ { "answer_id": 191581, "author": "Till", "author_id": 2859, "author_profile": "https://Stackoverflow.com/users/2859", "pm_score": 2, "selected": false, "text": "if (fails) { connect to another }" }, { "answer_id": 191835, "author": "Toxygene", "author_id": 8428, "author_profile": "https://Stackoverflow.com/users/8428", "pm_score": 2, "selected": false, "text": "interface MySQL_Interface {\n public function query($sql);\n}\n\nclass MySQL_Concrete implements MySQL_Interface {\n public function __construct($host, $user, $pass, $dbname) {\n $this->_mysql = mysql_connect($host, $user, $pass) or throw Exception(\"Could not connect to server\");\n mysql_select_db($db, $this->_mysql) or throw Exception(\"Could not connect to database\");\n }\n public function query($sql) {\n return mysql_query($sql) or throw new Exception(\"Query failed\");\n }\n}\n\nclass MySQL_Failover implements MySQL_Interface {\n public function __construct(MySQL_Interface $one, MySQL_Interface $two) {\n $this->_one = $one;\n $this->_two = $two;\n }\n public function query($sql) {\n try {\n return $this->_one->query($sql);\n } catch (Exception $e) {\n return $this->_two->query($sql);\n }\n }\n}\n\n$db = new MySQL_Failover(\n new MySQL_Concrete('host1', 'user', 'pass', 'db'),\n new MySQL_Concrete('host2', 'user', 'pass', 'db')\n);\n\n$db->query('SELECT * FROM Users');\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191528", "https://Stackoverflow.com", "https://Stackoverflow.com/users/419/" ]
191,536
<p>I've seen a fair share of ungainly XML->JSON code on the web, and having interacted with Stack's users for a bit, I'm convinced that this crowd can help more than the first few pages of Google results can.</p> <p>So, we're parsing a weather feed, and we need to populate weather widgets on a multitude of web sites. We're looking now into Python-based solutions.</p> <p>This public <a href="http://rss.weather.com/weather/rss/local/14607?cm_ven=LWO&amp;cm_cat=rss&amp;par=LWO_rss" rel="noreferrer">weather.com RSS feed</a> is a good example of what we'd be parsing (<em>our actual weather.com feed contains additional information because of a partnership w/them</em>).</p> <p>In a nutshell, how should we convert XML to JSON using Python?</p>
[ { "answer_id": 191617, "author": "Dan Lenski", "author_id": 20789, "author_profile": "https://Stackoverflow.com/users/20789", "pm_score": 7, "selected": true, "text": "json" }, { "answer_id": 3884849, "author": "pykler", "author_id": 469480, "author_profile": "https://Stackoverflow.com/users/469480", "pm_score": 3, "selected": false, "text": "<key>value</key>" }, { "answer_id": 10011736, "author": "Andrew_1510", "author_id": 451718, "author_profile": "https://Stackoverflow.com/users/451718", "pm_score": 2, "selected": false, "text": "# <user><name>Happy Man</name>...</user>\nimport re\nnames = re.findall(r'<name>(\\w+)<\\/name>', xml_string)\n# do some thing to names\n >>> from lxml import objectify\n>>> root = objectify.fromstring(\"\"\"\n... <root xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n... <a attr1=\"foo\" attr2=\"bar\">1</a>\n... <a>1.2</a>\n... <b>1</b>\n... <b>true</b>\n... <c>what?</c>\n... <d xsi:nil=\"true\"/>\n... </root>\n... \"\"\")\n\n>>> print(str(root))\nroot = None [ObjectifiedElement]\n a = 1 [IntElement]\n * attr1 = 'foo'\n * attr2 = 'bar'\n a = 1.2 [FloatElement]\n b = 1 [IntElement]\n b = True [BoolElement]\n c = 'what?' [StringElement]\n d = None [NoneElement]\n * xsi:nil = 'true'\n" }, { "answer_id": 10201405, "author": "Martin Blech", "author_id": 113643, "author_profile": "https://Stackoverflow.com/users/113643", "pm_score": 8, "selected": false, "text": "import xmltodict, json\n\no = xmltodict.parse('<e> <a>text</a> <a>text</a> </e>')\njson.dumps(o) # '{\"e\": {\"a\": [\"text\", \"text\"]}}'\n" }, { "answer_id": 10201546, "author": "Michael Anderson", "author_id": 221955, "author_profile": "https://Stackoverflow.com/users/221955", "pm_score": 3, "selected": false, "text": "class Channel:\n def __init__(self)\n self.items = []\n self.title = \"\"\n\n def from_xml( self, xml_node ):\n self.title = xml_node.xpath(\"title/text()\")[0]\n for x in xml_node.xpath(\"item\"):\n item = Item()\n item.from_xml( x )\n self.items.append( item )\n\n def to_json( self ):\n retval = {}\n retval['title'] = title\n retval['items'] = []\n for x in items:\n retval.append( x.to_json() )\n return retval\n\nclass Item:\n def __init__(self):\n ...\n\n def from_xml( self, xml_node ):\n ...\n\n def to_json( self ):\n ...\n" }, { "answer_id": 10231610, "author": "Paulo Vj", "author_id": 1313042, "author_profile": "https://Stackoverflow.com/users/1313042", "pm_score": 3, "selected": false, "text": "from xml.dom import minidom\nimport simplejson as json\ndef parse_element(element):\n dict_data = dict()\n if element.nodeType == element.TEXT_NODE:\n dict_data['data'] = element.data\n if element.nodeType not in [element.TEXT_NODE, element.DOCUMENT_NODE, \n element.DOCUMENT_TYPE_NODE]:\n for item in element.attributes.items():\n dict_data[item[0]] = item[1]\n if element.nodeType not in [element.TEXT_NODE, element.DOCUMENT_TYPE_NODE]:\n for child in element.childNodes:\n child_name, child_dict = parse_element(child)\n if child_name in dict_data:\n try:\n dict_data[child_name].append(child_dict)\n except AttributeError:\n dict_data[child_name] = [dict_data[child_name], child_dict]\n else:\n dict_data[child_name] = child_dict \n return element.nodeName, dict_data\n\nif __name__ == '__main__':\n dom = minidom.parse('data.xml')\n f = open('data.json', 'w')\n f.write(json.dumps(parse_element(dom), sort_keys=True, indent=4))\n f.close()\n" }, { "answer_id": 32676972, "author": "S Anand", "author_id": 100904, "author_profile": "https://Stackoverflow.com/users/100904", "pm_score": 5, "selected": false, "text": "<p id=\"1\">text</p>\n {\n 'p': {\n '@id': 1,\n '$': 'text'\n }\n}\n {\n 'p': {\n '$t': 'text'\n }\n}\n {\n 'p': 'text'\n}\n >>> import json, xmljson\n>>> from lxml.etree import fromstring, tostring\n>>> xml = fromstring('<p id=\"1\">text</p>')\n>>> json.dumps(xmljson.badgerfish.data(xml))\n'{\"p\": {\"@id\": 1, \"$\": \"text\"}}'\n>>> xmljson.parker.etree({'ul': {'li': [1, 2]}})\n# Creates [<ul><li>1</li><li>2</li></ul>]\n" }, { "answer_id": 40152062, "author": "shx2", "author_id": 2096752, "author_profile": "https://Stackoverflow.com/users/2096752", "pm_score": 2, "selected": false, "text": "lxml lxml from collections import Mapping\nimport lxml.etree\n\nclass ETreeDictWrapper(Mapping):\n\n def __init__(self, elem, attr_prefix = '@', list_tags = ()):\n self.elem = elem\n self.attr_prefix = attr_prefix\n self.list_tags = list_tags\n\n def _wrap(self, e):\n if isinstance(e, basestring):\n return e\n if len(e) == 0 and len(e.attrib) == 0:\n return e.text\n return type(self)(\n e,\n attr_prefix = self.attr_prefix,\n list_tags = self.list_tags,\n )\n\n def __getitem__(self, key):\n if key.startswith(self.attr_prefix):\n return self.elem.attrib[key[len(self.attr_prefix):]]\n else:\n subelems = [ e for e in self.elem.iterchildren() if e.tag == key ]\n if len(subelems) > 1 or key in self.list_tags:\n return [ self._wrap(x) for x in subelems ]\n elif len(subelems) == 1:\n return self._wrap(subelems[0])\n else:\n raise KeyError(key)\n\n def __iter__(self):\n return iter(set( k.tag for k in self.elem) |\n set( self.attr_prefix + k for k in self.elem.attrib ))\n\n def __len__(self):\n return len(self.elem) + len(self.elem.attrib)\n\n # defining __contains__ is not necessary, but improves speed\n def __contains__(self, key):\n if key.startswith(self.attr_prefix):\n return key[len(self.attr_prefix):] in self.elem.attrib\n else:\n return any( e.tag == key for e in self.elem.iterchildren() )\n\n\ndef xml_to_dictlike(xmlstr, attr_prefix = '@', list_tags = ()):\n t = lxml.etree.fromstring(xmlstr)\n return ETreeDictWrapper(\n t,\n attr_prefix = '@',\n list_tags = set(list_tags),\n )\n xml2json json.dumps def xml_to_json(xmlstr, **kwargs):\n x = xml_to_dictlike(xmlstr, **kwargs)\n return json.dumps(x)\n attr_prefix" }, { "answer_id": 43875277, "author": "shrewmouse", "author_id": 2464381, "author_profile": "https://Stackoverflow.com/users/2464381", "pm_score": 2, "selected": false, "text": "from lxml import etree \nimport json\n\n\nclass Element:\n '''\n Wrapper on the etree.Element class. Extends functionality to output element\n as a dictionary.\n '''\n\n def __init__(self, element):\n '''\n :param: element a normal etree.Element instance\n '''\n self.element = element\n\n def toDict(self):\n '''\n Returns the element as a dictionary. This includes all child elements.\n '''\n rval = {\n self.element.tag: {\n 'attributes': dict(self.element.items()),\n },\n }\n for child in self.element:\n rval[self.element.tag].update(Element(child).toDict())\n return rval\n\n\nclass XmlDocument:\n '''\n Wraps lxml to provide:\n - cleaner access to some common lxml.etree functions\n - converter from XML to dict\n - converter from XML to json\n '''\n def __init__(self, xml = '<empty/>', filename=None):\n '''\n There are two ways to initialize the XmlDocument contents:\n - String\n - File\n\n You don't have to initialize the XmlDocument during instantiation\n though. You can do it later with the 'set' method. If you choose to\n initialize later XmlDocument will be initialized with \"<empty/>\".\n\n :param: xml Set this argument if you want to parse from a string.\n :param: filename Set this argument if you want to parse from a file.\n '''\n self.set(xml, filename) \n\n def set(self, xml=None, filename=None):\n '''\n Use this to set or reset the contents of the XmlDocument.\n\n :param: xml Set this argument if you want to parse from a string.\n :param: filename Set this argument if you want to parse from a file.\n '''\n if filename is not None:\n self.tree = etree.parse(filename)\n self.root = self.tree.getroot()\n else:\n self.root = etree.fromstring(xml)\n self.tree = etree.ElementTree(self.root)\n\n\n def dump(self):\n etree.dump(self.root)\n\n def getXml(self):\n '''\n return document as a string\n '''\n return etree.tostring(self.root)\n\n def xpath(self, xpath):\n '''\n Return elements that match the given xpath.\n\n :param: xpath\n '''\n return self.tree.xpath(xpath);\n\n def nodes(self):\n '''\n Return all elements\n '''\n return self.root.iter('*')\n\n def toDict(self):\n '''\n Convert to a python dictionary\n '''\n return Element(self.root).toDict()\n\n def toJson(self, indent=None):\n '''\n Convert to JSON\n '''\n return json.dumps(self.toDict(), indent=indent)\n\n\nif __name__ == \"__main__\":\n xml='''<system>\n <product>\n <demod>\n <frequency value='2.215' units='MHz'>\n <blah value='1'/>\n </frequency>\n </demod>\n </product>\n</system>\n'''\n doc = XmlDocument(xml)\n print doc.toJson(indent=4)\n {\n \"system\": {\n \"attributes\": {}, \n \"product\": {\n \"attributes\": {}, \n \"demod\": {\n \"attributes\": {}, \n \"frequency\": {\n \"attributes\": {\n \"units\": \"MHz\", \n \"value\": \"2.215\"\n }, \n \"blah\": {\n \"attributes\": {\n \"value\": \"1\"\n }\n }\n }\n }\n }\n }\n}\n <system>\n <product>\n <demod>\n <frequency value='2.215' units='MHz'>\n <blah value='1'/>\n </frequency>\n </demod>\n </product>\n</system>\n" }, { "answer_id": 47081240, "author": "jnhustin", "author_id": 6441385, "author_profile": "https://Stackoverflow.com/users/6441385", "pm_score": 4, "selected": false, "text": "from xml.etree import ElementTree as ET\n\nxml = ET.parse('FILE_NAME.xml')\nparsed = parseXmlToJson(xml)\n\n\ndef parseXmlToJson(xml):\n response = {}\n\n for child in list(xml):\n if len(list(child)) > 0:\n response[child.tag] = parseXmlToJson(child)\n else:\n response[child.tag] = child.text or ''\n\n # one-liner equivalent\n # response[child.tag] = parseXmlToJson(child) if len(list(child)) > 0 else child.text or ''\n\n return response\n" }, { "answer_id": 50304202, "author": "Akshay Kumbhar", "author_id": 7521283, "author_profile": "https://Stackoverflow.com/users/7521283", "pm_score": 4, "selected": false, "text": "import xmltodict\n\ndata = requests.get(url)\nxpars = xmltodict.parse(data.text)\njson = json.dumps(xpars)\nprint json \n" }, { "answer_id": 63556250, "author": "Liju", "author_id": 13608228, "author_profile": "https://Stackoverflow.com/users/13608228", "pm_score": 1, "selected": false, "text": "import re\nimport json\n\ndef getdict(content):\n res=re.findall(\"<(?P<var>\\S*)(?P<attr>[^/>]*)(?:(?:>(?P<val>.*?)</(?P=var)>)|(?:/>))\",content)\n if len(res)>=1:\n attreg=\"(?P<avr>\\S+?)(?:(?:=(?P<quote>['\\\"])(?P<avl>.*?)(?P=quote))|(?:=(?P<avl1>.*?)(?:\\s|$))|(?P<avl2>[\\s]+)|$)\"\n if len(res)>1:\n return [{i[0]:[{\"@attributes\":[{j[0]:(j[2] or j[3] or j[4])} for j in re.findall(attreg,i[1].strip())]},{\"$values\":getdict(i[2])}]} for i in res]\n else:\n return {res[0]:[{\"@attributes\":[{j[0]:(j[2] or j[3] or j[4])} for j in re.findall(attreg,res[1].strip())]},{\"$values\":getdict(res[2])}]}\n else:\n return content\n\nwith open(\"test.xml\",\"r\") as f:\n print(json.dumps(getdict(f.read().replace('\\n',''))))\n <details class=\"4b\" count=1 boy>\n <name type=\"firstname\">John</name>\n <age>13</age>\n <hobby>Coin collection</hobby>\n <hobby>Stamp collection</hobby>\n <address>\n <country>USA</country>\n <state>CA</state>\n </address>\n</details>\n<details empty=\"True\"/>\n<details/>\n<details class=\"4a\" count=2 girl>\n <name type=\"firstname\">Samantha</name>\n <age>13</age>\n <hobby>Fishing</hobby>\n <hobby>Chess</hobby>\n <address current=\"no\">\n <country>Australia</country>\n <state>NSW</state>\n </address>\n</details>\n [\n {\n \"details\": [\n {\n \"@attributes\": [\n {\n \"class\": \"4b\"\n },\n {\n \"count\": \"1\"\n },\n {\n \"boy\": \"\"\n }\n ]\n },\n {\n \"$values\": [\n {\n \"name\": [\n {\n \"@attributes\": [\n {\n \"type\": \"firstname\"\n }\n ]\n },\n {\n \"$values\": \"John\"\n }\n ]\n },\n {\n \"age\": [\n {\n \"@attributes\": []\n },\n {\n \"$values\": \"13\"\n }\n ]\n },\n {\n \"hobby\": [\n {\n \"@attributes\": []\n },\n {\n \"$values\": \"Coin collection\"\n }\n ]\n },\n {\n \"hobby\": [\n {\n \"@attributes\": []\n },\n {\n \"$values\": \"Stamp collection\"\n }\n ]\n },\n {\n \"address\": [\n {\n \"@attributes\": []\n },\n {\n \"$values\": [\n {\n \"country\": [\n {\n \"@attributes\": []\n },\n {\n \"$values\": \"USA\"\n }\n ]\n },\n {\n \"state\": [\n {\n \"@attributes\": []\n },\n {\n \"$values\": \"CA\"\n }\n ]\n }\n ]\n }\n ]\n }\n ]\n }\n ]\n },\n {\n \"details\": [\n {\n \"@attributes\": [\n {\n \"empty\": \"True\"\n }\n ]\n },\n {\n \"$values\": \"\"\n }\n ]\n },\n {\n \"details\": [\n {\n \"@attributes\": []\n },\n {\n \"$values\": \"\"\n }\n ]\n },\n {\n \"details\": [\n {\n \"@attributes\": [\n {\n \"class\": \"4a\"\n },\n {\n \"count\": \"2\"\n },\n {\n \"girl\": \"\"\n }\n ]\n },\n {\n \"$values\": [\n {\n \"name\": [\n {\n \"@attributes\": [\n {\n \"type\": \"firstname\"\n }\n ]\n },\n {\n \"$values\": \"Samantha\"\n }\n ]\n },\n {\n \"age\": [\n {\n \"@attributes\": []\n },\n {\n \"$values\": \"13\"\n }\n ]\n },\n {\n \"hobby\": [\n {\n \"@attributes\": []\n },\n {\n \"$values\": \"Fishing\"\n }\n ]\n },\n {\n \"hobby\": [\n {\n \"@attributes\": []\n },\n {\n \"$values\": \"Chess\"\n }\n ]\n },\n {\n \"address\": [\n {\n \"@attributes\": [\n {\n \"current\": \"no\"\n }\n ]\n },\n {\n \"$values\": [\n {\n \"country\": [\n {\n \"@attributes\": []\n },\n {\n \"$values\": \"Australia\"\n }\n ]\n },\n {\n \"state\": [\n {\n \"@attributes\": []\n },\n {\n \"$values\": \"NSW\"\n }\n ]\n }\n ]\n }\n ]\n }\n ]\n }\n ]\n }\n]\n" }, { "answer_id": 66340843, "author": "David Lee", "author_id": 3831392, "author_profile": "https://Stackoverflow.com/users/3831392", "pm_score": 0, "selected": false, "text": "python xml_to_json.py -x PurchaseOrder.xsd PurchaseOrder.xml\n\nINFO - 2018-03-20 11:10:24 - Parsing XML Files..\nINFO - 2018-03-20 11:10:24 - Processing 1 files\nINFO - 2018-03-20 11:10:24 - Parsing files in the following order:\nINFO - 2018-03-20 11:10:24 - ['PurchaseOrder.xml']\nDEBUG - 2018-03-20 11:10:24 - Generating schema from PurchaseOrder.xsd\nDEBUG - 2018-03-20 11:10:24 - Parsing PurchaseOrder.xml\nDEBUG - 2018-03-20 11:10:24 - Writing to file PurchaseOrder.json\nDEBUG - 2018-03-20 11:10:24 - Completed PurchaseOrder.xml\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191536", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22491/" ]
191,549
<p>We have a custom collection of objects that we bind to a listbox control. When an item is added to the list the item appears in the listbox, however when one selects the item the currency manager position will not go to the position. Instead the currency manager position stays at the existing position. The listbox item is high lighted as long as the mouse is press however the cm never changes position.</p> <p>If I copy one of the collection objects the listbox operates properly.</p> <p>One additional note the collection also has collections within it, not sure if this would be an issue.</p>
[ { "answer_id": 191639, "author": "Joel B Fant", "author_id": 22211, "author_profile": "https://Stackoverflow.com/users/22211", "pm_score": 0, "selected": false, "text": "ListBox SelectedIndexChanged" }, { "answer_id": 191643, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 1, "selected": false, "text": "using System;\nusing System.ComponentModel;\nusing System.Windows.Forms;\nstatic class Program\n{\n [STAThread]\n static void Main()\n {\n Application.EnableVisualStyles();\n BindingList<Foo> foos = new BindingList<Foo>();\n foos.Add(new Foo(\"abc\"));\n foos.Add(new Foo(\"def\"));\n\n ListBox lb1 = new ListBox(), lb2 = new ListBox();\n lb1.DataSource = lb2.DataSource = foos;\n lb1.DisplayMember = lb2.DisplayMember = \"Bar\";\n lb1.Dock = DockStyle.Left;\n lb2.Dock = DockStyle.Right;\n\n Button b = new Button();\n b.Text = \"Add\";\n b.Dock = DockStyle.Top;\n b.Click += delegate\n {\n foos.Add(new Foo(\"new item\"));\n };\n Form form = new Form();\n form.Controls.Add(lb1);\n form.Controls.Add(lb2);\n form.Controls.Add(b);\n Application.Run(form);\n }\n\n\n}\nclass Foo\n{\n public Foo(string bar) {this.Bar = bar;}\n private string bar;\n public string Bar {\n get {return bar;}\n set {bar = value;}\n }\n}\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191549", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7950/" ]
191,592
<p>I'm working on a simple 2D game engine in Java, and having no trouble with FSEM, buffer strategies, and so on; my issue is with the mouse cursor. In windowed mode, I can hide the mouse cursor, no problem, by using setCursor() from my JFrame to set a wholly-transparent cursor. However, after a call to device.setFullScreenWindow(this) to go into FSEM, the mouse cursor comes back, and subsequent calls to setCursor() to set it back to my blank cursor have no effect. Calling device.setFullScreenWindow(null) allows me to get rid of the cursor again - it's only while I'm in FSEM that I can't get rid of it.</p> <p>I'm working under JDK 6, target platform is JDK 5+.</p> <p><strong>UPDATE:</strong> I've done some more testing, and it looks like this issue occurs under MacOS X 10.5 w/Java 6u7, but not under Windows XP SP3 with Java 6u7. So, it could possibly be a bug in the Mac version of the JVM.</p>
[ { "answer_id": 192829, "author": "seisyll", "author_id": 21815, "author_profile": "https://Stackoverflow.com/users/21815", "pm_score": 0, "selected": false, "text": " Toolkit toolkit = Toolkit.getDefaultToolkit();\n Dimension dim = toolkit.getBestCursorSize(1,1);\n transCursor = toolkit.createCustomCursor(gc.createCompatibleImage(dim.width, dim.height),\n new Point(0, 0), \"transCursor\");\n ((Component)mainFrame).setCursor(transCursor);\n" }, { "answer_id": 205690, "author": "Adrian", "author_id": 7426, "author_profile": "https://Stackoverflow.com/users/7426", "pm_score": 3, "selected": true, "text": "System.setProperty(\"apple.awt.fullscreenhidecursor\",\"true\");\n" }, { "answer_id": 1028113, "author": "Ricket", "author_id": 47493, "author_profile": "https://Stackoverflow.com/users/47493", "pm_score": 1, "selected": false, "text": "Toolkit toolkit = Toolkit.getDefaultToolkit();\n\n// get the smallest valid cursor size\nDimension dim = toolkit.getBestCursorSize(1, 1);\n\n// create a new image of that size with an alpha channel\nBufferedImage cursorImg = new BufferedImage(dim.width, dim.height, BufferedImage.TYPE_INT_ARGB);\n\n// get a Graphics2D object to draw to the image\nGraphics2D g2d = cursorImg.createGraphics();\n\n// set the background 'color' with 0 alpha and clear the image\ng2d.setBackground(new Color(0.0f, 0.0f, 0.0f, 0.0f));\ng2d.clearRect(0, 0, dim.width, dim.height);\n\n// dispose the Graphics2D object\ng2d.dispose();\n\n// now create your cursor using that transparent image\nhiddenCursor = toolkit.createCustomCursor(cursorImg, new Point(0,0), \"hiddenCursor\");\n public void hideMouse(boolean hide) {\n if(hide) {\n fr.setCursor(hiddenCursor);\n } else {\n fr.setCursor(Cursor.getDefaultCursor());\n }\n}\n" }, { "answer_id": 4141187, "author": "Janthoe", "author_id": 502739, "author_profile": "https://Stackoverflow.com/users/502739", "pm_score": 4, "selected": false, "text": " Toolkit toolkit = Toolkit.getDefaultToolkit();\n Point hotSpot = new Point(0,0);\n BufferedImage cursorImage = new BufferedImage(1, 1, BufferedImage.TRANSLUCENT); \n Cursor invisibleCursor = toolkit.createCustomCursor(cursorImage, hotSpot, \"InvisibleCursor\"); \n setCursor(invisibleCursor);\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7426/" ]
191,609
<p>Where would you write an error log file, say <code>ErrorLog.txt</code>, in Windows? Keep in mind the path would need to be open to basic users for file write permissions.</p> <p>I know the eventlog is a possible location for writing errors, but does it work for "user" level permissions?</p> <p>EDIT: I am targeting Windows 2003, but I was posing the question in such a way as to have a "General Guideline" for where to write error logs.<br> As for the EventLog, I have had issues before in an ASP.NET application where I wanted to log to the Windows event log, but I had security issues causing me heartache. (I do not recall the issues I had, but remember having them.)</p>
[ { "answer_id": 191625, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 5, "selected": true, "text": "Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)\n" }, { "answer_id": 191667, "author": "gimel", "author_id": 6491, "author_profile": "https://Stackoverflow.com/users/6491", "pm_score": 2, "selected": false, "text": "C:\\Documents and Settings\\All Users\\Application Data\\MyApp\n C:\\Documents and Settings\\%Username%\\Application Data\\MyApp\n %UserProfile%\\Application Data\\MyApp AppDir=\n System.Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData)\n AppDir=\n System.Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)\n MyAppDir = IO.Path.Combine(AppDir,'MyApp')\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191609", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1048/" ]
191,614
<p>We have a fairly large code base, 400K LOC of C++, and code duplication is something of a problem. Are there any tools which can effectively detect duplicated blocks of code?</p> <p>Ideally this would be something that developers could use during development rather than just run occasionally to see where the problems are. It would also be nice if we could integrate such a tool with CruiseControl to give a report after each check in. </p> <p>I had a look at <a href="http://www.iam.unibe.ch/~scg/Research/Duploc/index.html" rel="noreferrer">Duploc</a> some time ago, it showed a nice graph but requires a smalltalk environment to use it, which makes running it automatically rather difficult.</p> <p>Free tools would be nice, but if there are some good commercial tools I would also be interested.</p>
[ { "answer_id": 314808, "author": "user39039", "author_id": 39039, "author_profile": "https://Stackoverflow.com/users/39039", "pm_score": 4, "selected": false, "text": "<project name=\"duplicatecheck\" default=\"cpd\">\n\n<property name=\"files.dir\" value=\"dir containing your sources\"/>\n<property name=\"output.dir\" value=\"dir containing results for publishing\"/>\n\n<target name=\"cpd\">\n <taskdef name=\"cpd\" classname=\"net.sourceforge.pmd.cpd.CPDTask\"/>\n <cpd minimumTokenCount=\"100\" \n language=\"cpp\" \n outputFile=\"${output.dir}/duplicates.txt\"\n ignoreLiterals=\"false\"\n ignoreIdentifiers=\"false\"\n format=\"text\">\n <fileset dir=\"${files.dir}/\">\n <include name=\"**/*.h\"/>\n <include name=\"**/*.cpp\"/>\n <!-- exclude third-party stuff -->\n <exclude name=\"boost/\"/>\n <exclude name=\"cppunit/\"/>\n </fileset>\n </cpd>\n</target>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5022/" ]
191,640
<p>I wish to search a database table on a nullable column. Sometimes the value I'm search for is itself NULL. Since Null is equal to nothing, even NULL, saying</p> <pre><code>where MYCOLUMN=SEARCHVALUE </code></pre> <p>will fail. Right now I have to resort to</p> <pre><code>where ((MYCOLUMN=SEARCHVALUE) OR (MYCOLUMN is NULL and SEARCHVALUE is NULL)) </code></pre> <p>Is there a simpler way of saying that?</p> <p>(I'm using Oracle if that matters)</p>
[ { "answer_id": 191646, "author": "DCookie", "author_id": 8670, "author_profile": "https://Stackoverflow.com/users/8670", "pm_score": 2, "selected": false, "text": "WHERE NVL(mycolumn,'NULL') = NVL(searchvalue,'NULL')\n" }, { "answer_id": 191648, "author": "JosephStyons", "author_id": 672, "author_profile": "https://Stackoverflow.com/users/672", "pm_score": 3, "selected": false, "text": "WHERE NVL(MYCOLUMN,0) = NVL(SEARCHVALUE,0)\n" }, { "answer_id": 191649, "author": "Chris Shaffer", "author_id": 6744, "author_profile": "https://Stackoverflow.com/users/6744", "pm_score": 4, "selected": false, "text": "WHERE ISNULL(MyColumn, -1) = ISNULL(SearchValue, -1)\n" }, { "answer_id": 191656, "author": "Andy Lester", "author_id": 8454, "author_profile": "https://Stackoverflow.com/users/8454", "pm_score": 7, "selected": true, "text": "where ((MYCOLUMN=SEARCHVALUE) OR (MYCOLUMN is NULL and SEARCHVALUE is NULL))\n" }, { "answer_id": 191658, "author": "Carl", "author_id": 951280, "author_profile": "https://Stackoverflow.com/users/951280", "pm_score": 0, "selected": false, "text": "where NVL(MYCOLUMN, '') = NVL(SEARCHVALUE, '')\n" }, { "answer_id": 191680, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 3, "selected": false, "text": "if (SEARCHVALUE IS NULL) {\n condition = 'MYCOLUMN IS NULL'\n} else {\n condition = 'MYCOLUMN=SEARCHVALUE'\n}\nrunQuery(query,condition)\n" }, { "answer_id": 192072, "author": "DCookie", "author_id": 8670, "author_profile": "https://Stackoverflow.com/users/8670", "pm_score": 5, "selected": false, "text": " SQL> DECLARE\n 2 CURSOR B IS\n 3 SELECT batch_id, equipment_id\n 4 FROM batch;\n 5 v_t1 NUMBER;\n 6 v_t2 NUMBER;\n 7 v_c1 NUMBER;\n 8 v_c2 NUMBER;\n 9 v_b INTEGER;\n 10 BEGIN\n 11 -- Form 1 of the where clause\n 12 v_t1 := dbms_utility.get_time;\n 13 v_c1 := dbms_utility.get_cpu_time;\n 14 FOR R IN B LOOP\n 15 SELECT COUNT(*)\n 16 INTO v_b\n 17 FROM batch\n 18 WHERE equipment_id = R.equipment_id OR (equipment_id IS NULL AND R.equipment_id IS NULL);\n 19 END LOOP;\n 20 v_t2 := dbms_utility.get_time;\n 21 v_c2 := dbms_utility.get_cpu_time;\n 22 dbms_output.put_line('For clause: WHERE equipment_id = R.equipment_id OR (equipment_id IS NULL AND R.equipment_id IS NULL)');\n 23 dbms_output.put_line('CPU seconds used: '||(v_c2 - v_c1)/100);\n 24 dbms_output.put_line('Elapsed time: '||(v_t2 - v_t1)/100);\n 25 \n 26 -- Form 2 of the where clause\n 27 v_t1 := dbms_utility.get_time;\n 28 v_c1 := dbms_utility.get_cpu_time;\n 29 FOR R IN B LOOP\n 30 SELECT COUNT(*)\n 31 INTO v_b\n 32 FROM batch\n 33 WHERE NVL(equipment_id,'xxxx') = NVL(R.equipment_id,'xxxx');\n 34 END LOOP;\n 35 v_t2 := dbms_utility.get_time;\n 36 v_c2 := dbms_utility.get_cpu_time;\n 37 dbms_output.put_line('For clause: WHERE NVL(equipment_id,''xxxx'') = NVL(R.equipment_id,''xxxx'')');\n 38 dbms_output.put_line('CPU seconds used: '||(v_c2 - v_c1)/100);\n 39 dbms_output.put_line('Elapsed time: '||(v_t2 - v_t1)/100);\n 40 END;\n 41 /\n\n\n For clause: WHERE equipment_id = R.equipment_id OR (equipment_id IS NULL AND R.equipment_id IS NULL)\n CPU seconds used: 84.69\n Elapsed time: 84.8\n For clause: WHERE NVL(equipment_id,'xxxx') = NVL(R.equipment_id,'xxxx')\n CPU seconds used: 124\n Elapsed time: 124.01\n\n PL/SQL procedure successfully completed\n\n SQL> select count(*) from batch;\n\n COUNT(*)\n----------\n 20903\n\nSQL> \n" }, { "answer_id": 275796, "author": "Ted", "author_id": 7972, "author_profile": "https://Stackoverflow.com/users/7972", "pm_score": 2, "selected": false, "text": "where coalesce(mycolumn, 'out-of-band') \n = coalesce(searchvalue, 'out-of-band')\n" }, { "answer_id": 351611, "author": "EvilTeach", "author_id": 7734, "author_profile": "https://Stackoverflow.com/users/7734", "pm_score": 1, "selected": false, "text": "WHERE MYCOLUMN || 'X' = SEARCHVALUE || 'X'\n WITH \nTEST AS\n(\n SELECT NULL A FROM DUAL\n)\nSELECT DECODE (A, NULL, 'NULL IS EQUAL', 'NULL IS NOT EQUAL')\nFROM TEST\n" }, { "answer_id": 5303981, "author": "Peter Meinl", "author_id": 158475, "author_profile": "https://Stackoverflow.com/users/158475", "pm_score": 4, "selected": false, "text": "WHERE DECODE(MYCOLUMN, SEARCHVALUE, 1) = 1\n" }, { "answer_id": 16961703, "author": "Jason Winger", "author_id": 2459552, "author_profile": "https://Stackoverflow.com/users/2459552", "pm_score": 0, "selected": false, "text": "WHERE rte_pending.ltr_rte_id = prte_id\n OR ((rte_pending.ltr_rte_id IS NULL OR rte_pending.ltr_rte_id IS NOT NULL)\n AND prte_id IS NULL)\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191640", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12725/" ]
191,641
<p>I am attempting to have a ReportHandler service to handle report creation. Reports can have multiple, differing number of parameters that could be set. In the system currently there are several different methods of creating reports (MS reporting services, html reports, etc) and the way the data is generated for each report is different. I am trying to consolidate everything into ActiveReports. I can't alter the system and change the parameters, so in some cases I will essentially get a where clause to generate the results, and in another case I will get key/value pairs that I must use to generate the results. I thought about using the factory pattern, but because of the different number of query filters this won't work. </p> <p>I would love to have a single ReportHandler that would take my varied inputs and spit out report. At this point I'm not seeing any other way than to use a big switch statement to handle each report based on the reportName. Any suggestions how I could solve this better?</p>
[ { "answer_id": 194062, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "public class ReportContainer{\n public ReportContainer ( IReportEngine reportEngine, IStorageEngine storage, IDeliveryEngine delivery...)\n}\n}\n\n/// In your service layer you resolve which engines to use\n// Either with a bunch of if statements / Factory / config ... \n\nIReportEngine rptEngine = EngineFactory.GetEngine<IReportEngine>( pass in some values)\n\nIStorageEngine stgEngine = EngineFactory.GetEngine<IStorageEngien>(pass in some values)\n\nIDeliverEngine delEngine = EngineFactory.GetEngine<IDeliverEngine>(pass in some values)\n\n\n\nReportContainer currentContext = new ReportContainer (rptEngine, stgEngine,delEngine);\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191641", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24908/" ]
191,642
<p>I'm architecting a new app at the moment, with a high read:write ratio. At my current employer we have lots of denormalised data on our tables for performance reasons. Is it better practice to have totally 3NF tables and then use indexed views to do all the denormalisation? Should I run queries against the tables or views?</p> <p>An example of some of the things I am interested are aggregates of columns child tables (e.g. having user post count stored somewhere).</p>
[ { "answer_id": 194062, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "public class ReportContainer{\n public ReportContainer ( IReportEngine reportEngine, IStorageEngine storage, IDeliveryEngine delivery...)\n}\n}\n\n/// In your service layer you resolve which engines to use\n// Either with a bunch of if statements / Factory / config ... \n\nIReportEngine rptEngine = EngineFactory.GetEngine<IReportEngine>( pass in some values)\n\nIStorageEngine stgEngine = EngineFactory.GetEngine<IStorageEngien>(pass in some values)\n\nIDeliverEngine delEngine = EngineFactory.GetEngine<IDeliverEngine>(pass in some values)\n\n\n\nReportContainer currentContext = new ReportContainer (rptEngine, stgEngine,delEngine);\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191642", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2086/" ]
191,644
<p>I've googled around a bit, but maybe I didn't put the correct magik incantation into the search box. </p> <p>Does anyone know how to get output parameters from a stored procedure in Python? I'm using pymssql to call a stored procedure, and I'm not sure of the correct syntax to get the output parameter back. I don't think I can use any other db modules since I'm running this from a Linux box to connect to a mssql database on a MS Server.</p> <pre><code>import pymssql con = pymssql.connect(host='xxxxx',user='xxxx',password='xxxxx',database='xxxxx') cur = con.cursor() query = "EXECUTE blah blah blah" cur.execute(query) con.commit() con.close() </code></pre>
[ { "answer_id": 192032, "author": "Milen A. Radev", "author_id": 15785, "author_profile": "https://Stackoverflow.com/users/15785", "pm_score": 2, "selected": false, "text": "cur.callproc('my_stored_proc', (first_param, second_param, an_out_param))\n" }, { "answer_id": 198358, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 1, "selected": false, "text": "CREATE PROCEDURE Foo (@Bar INT OUT, @Baz INT OUT) AS\nBEGIN\n /* Stuff happens here */\n RETURN 0\nEND\n CREATE PROCEDURE Foo (@Bar INT, @Baz INT) AS\nBEGIN\n /* Stuff happens here */\n SELECT @Bar Bar, @Baz Baz\n RETURN 0\nEND\n" }, { "answer_id": 220150, "author": "Paul D. Eden", "author_id": 3045, "author_profile": "https://Stackoverflow.com/users/3045", "pm_score": 2, "selected": false, "text": "CREATE PROC GetNextNumber\n @NextNumber int OUTPUT\nAS\n...\n CREATE PROC GetNextNumberWrap\nAS\n DECLARE @RNextNumber int\n EXEC GetNextNumber @RNextNumber\n SELECT @RNextNumber\nGO\n import pymssql\ncon = pymssql.connect(...)\ncur = con.cursor()\ncur.execute(\"EXEC GetNextNumberWrap\")\nnext_num = cur.fetchone()[0]\n" }, { "answer_id": 1596296, "author": "M Deitemeyer", "author_id": 193285, "author_profile": "https://Stackoverflow.com/users/193285", "pm_score": 1, "selected": false, "text": "import sys, string, os, shutil, arcgisscripting\nfrom win32com.client import Dispatch\nfrom adoconstants import *\n\n#skip ahead to the important stuff\n\nconn = Dispatch('ADODB.Connection')\nconn.ConnectionString = \"Provider=sqloledb.1; Data Source=NT38; Integrated Security = SSPI;database=UtilityTicket\"\nconn.Open()\n\n#Target Procedure Example: EXEC TicketNumExists @ticketNum = 8386998, @exists output\n\nCmd = Dispatch('ADODB.Command')\nCmd.ActiveConnection = conn\n\nCmd.CommandType = adCmdStoredProc\nCmd.CommandText = \"TicketNumExists\"\n\nParam1 = Cmd.CreateParameter('@ticketNum', adInteger, adParamInput)\nParam1.Value = str(TicketNumber)\nParam2 = Cmd.CreateParameter('@exists', adInteger, adParamOutput)\n\nCmd.Parameters.Append(Param1)\nCmd.Parameters.Append(Param2)\n\nCmd.Execute()\n\nAnswer = Cmd.Parameters('@exists').Value\n" }, { "answer_id": 39968406, "author": "Gord Thompson", "author_id": 2144390, "author_profile": "https://Stackoverflow.com/users/2144390", "pm_score": 1, "selected": false, "text": "callproc pymssql.output() callproc CREATE PROCEDURE [dbo].[myDoubler] \n @in int = 0, \n @out int OUTPUT\nAS\nBEGIN\n SET NOCOUNT ON;\n SELECT @out = @in * 2;\nEND\n import pymssql\nconn = pymssql.connect(\n host=r'localhost:49242',\n database='myDb',\n autocommit=True\n )\ncrsr = conn.cursor()\n\nsql = \"dbo.myDoubler\"\nparams = (3, pymssql.output(int, 0))\nfoo = crsr.callproc(sql, params)\nprint(foo)\nconn.close()\n (3, 6)\n callproc foo[1] ALTER PROCEDURE [dbo].[myDoubler] \n @in int = 0, \n @out int OUTPUT\nAS\nBEGIN\n SET NOCOUNT ON;\n SELECT @out = @in * 2;\n -- now let's return a result set, too\n SELECT 'foo' AS thing UNION ALL SELECT 'bar' AS thing;\nEND\n sql = \"\"\"\\\nDECLARE @out_value INT;\nEXEC dbo.myDoubler @in = %s, @out = @out_value OUTPUT;\nSELECT @out_value AS out_value;\n\"\"\"\nparams = (3,)\ncrsr.execute(sql, params)\nrows = crsr.fetchall()\nwhile rows:\n print(rows)\n if crsr.nextset():\n rows = crsr.fetchall()\n else:\n rows = None\n [('foo',), ('bar',)]\n[(6,)]\n" }, { "answer_id": 40631433, "author": "Jaroslaw Matlak", "author_id": 7161851, "author_profile": "https://Stackoverflow.com/users/7161851", "pm_score": 0, "selected": false, "text": "query import pypyodc\n\nconnstring = \"DRIVER=SQL Server;\"\\\n \"SERVER=servername;\"\\\n \"PORT=1043;\"\\\n \"DATABASE=dbname;\"\\\n \"UID=user;\"\\\n \"PWD=pwd\"\n\nconn = pypyodbc.connect(connString)\ncursor = conn.cursor()\n\nquery=\"DECLARE @ivar INT \\r\\n\" \\\n \"DECLARE @svar VARCHAR(MAX) \\r\\n\" \\\n \"EXEC [procedure]\" \\\n \"@par1=?,\" \\\n \"@par2=?,\" \\\n \"@param1=@ivar OUTPUT,\" \\\n \"@param2=@svar OUTPUT \\r\\n\" \\\n \"SELECT @ivar, @svar \\r\\n\"\npar1=0\npar2=0\nparams=[par1, par2]\nresult = cursor.execute(query, params)\nprint result.fetchall()\n" }, { "answer_id": 40879178, "author": "neolei", "author_id": 423905, "author_profile": "https://Stackoverflow.com/users/423905", "pm_score": 0, "selected": false, "text": "import cx_Oracle as Oracle\n\nconn = Oracle.connect('xxxxxxxx')\ncur = conn.cursor()\n\nidd = cur.var(Oracle.NUMBER)\ncur.execute('begin :idd := seq_inv_turnover_id.nextval; end;', (idd,))\nprint(idd.getvalue())\n" }, { "answer_id": 71298476, "author": "Randy Stegner Sr.", "author_id": 12492220, "author_profile": "https://Stackoverflow.com/users/12492220", "pm_score": 0, "selected": false, "text": "def convert_pyodbc(pyodbc_lst):\n'''Converts pyodbc rows into usable list of lists (each sql row is a list),\n then examines each list for list elements that are strings,\n removes trailing spaces, and returns a usable list.'''\nusable_lst = []\nfor row in pyodbc_lst:\n e = [elem for elem in row]\n usable_lst.append(e)\nfor i in range(0,len(usable_lst[0])):\n for lst_elem in usable_lst:\n if isinstance(lst_elem[i],str):\n lst_elem[i] = lst_elem[i].rstrip()\nreturn usable_lst\n strtdate = '2022-02-21'\nstpdate = '2022-02-22'\n\nconn = mssql_conn('MYDB')\ncursor = conn.cursor()\n\nqry = cursor.execute(f\"EXEC mystoredprocedure_using_dates \n'{strtdate}','{stpdate}' \")\nresults = convert_pyodbc(qry.fetchall())\n\ncursor.close()\nconn.close()\n [[datetime.date(2022, 2, 21), '723521', 'A Team Line 1', 40, 9], \n[datetime.date(2022, 2, 21), '723522', 'A Team Line 2', 15, 10], \n[datetime.date(2022, 2, 21), '723523', 'A Team Line 3', 1, 5], \n[datetime.date(2022, 2, 21), '723686', 'B Team Line 1', 39, 27], \n[datetime.date(2022, 2, 21), '723687', 'B Team Line 2', 12, 14]]\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191644", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13380/" ]
191,652
<p>I work a lot with serial communications with a variety of devices, and so I often have to analyze hex dumps in log files. Currently, I do this manually by looking at the dumps, looking at the protocol spec, and writing down the results. However, this is tedious and error-prone, especially whem messages contain hundreds of bytes and contain mixtures of big-endian and little-endian data, ASCII, Unicode, compression, CRCs, . . . .</p> <p>I have written a few Python scripts to assist with the more common cases. But there are lots of protocols to deal with, and it doesn't make sense to spend the time writing a custom script unless I know I'll have a lot of dumps to analyze.</p> <p>What I'd like is some sort of utility that can automate this activity. So, for example, if I have a textual hex dump like this:</p> <pre><code>7e ff 00 7b 00 13 86 04 00 41 42 43 44 56 ef 7e </code></pre> <p>and some sort of description of the message format, like this:</p> <pre><code># Field Size Byte Order Output Format Flag 1 hex Address 1 hex Control 1 hex DataType 1 decimal LineIndex 1 decimal PollAddress 2 msb hex DataSize 2 lsb decimal Data (DataSize) ascii CRC 2 lsb hex Flag 1 hex </code></pre> <p>I'd get output like this:</p> <pre><code>Flag 0x7e Address 0xff Control 0x00 DataType 123 LineIndex 0 PollAddress 0x1386 DataSize 4 Data "ABCD" CRC 0xef56 Flag 0x7e </code></pre> <p>Hardware-based protocol analyzers often have fancy features for doing this kind of thing, but I need to work with textual log files.</p> <p>Does any such utility or library exist?</p> <hr> <p>Some good answers have come up since I set up the bounty. I guess bounties work!</p> <p>Wireshark and HexEdit both look promising; I'll take a look at those, and will proabably award the bounty to whichever one suits my needs. But I'm still open to other ideas.</p>
[ { "answer_id": 519616, "author": "Zac Thompson", "author_id": 58549, "author_profile": "https://Stackoverflow.com/users/58549", "pm_score": 1, "selected": false, "text": "bash$ tclsh\n% binary scan [binary format H* 7eff007b00138604004142434456ef7e] \\\n H2H2H2ccH4sa4h4H2 \\\n flag1 addr ctl datatype lineidx polladdr datasize data crc flag2\n10\n% puts \"$flag1 $addr $ctl $datatype $lineidx \\\n $polladdr $datasize $data $crc $flag2\"\n7e ff 00 123 0 1386 4 ABCD 65fe 7e\n" }, { "answer_id": 43699453, "author": "Pedro Gimeno", "author_id": 2428487, "author_profile": "https://Stackoverflow.com/users/2428487", "pm_score": 0, "selected": false, "text": "hexdump -e -f" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191652", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1175/" ]
191,690
<p>I have a table, we'll call <code>Users</code>. This table has a single primary key defined in SQL Server - an autoincrement <code>int ID</code>.</p> <p>Sometimes, my LINQ queries against this table fail with an <code>"Index was outside the range"</code> error - even the most simplest of queries. The query itself doesn't use any indexers.</p> <p>For example: </p> <pre><code>User = Users.Take(1); </code></pre> <p>or</p> <pre><code>IEnumerable&lt;Users&gt; = Users.ToList(); </code></pre> <p>Both of the queries threw the same error. Using the debugger Visualizer to look at the generated query - I copy and paste the query in SQL and it works fine. I also click "execute" on the visualizer and it works fine. But executing the code by itself throws this error. I don't implement any of the partial methods on the class, so nothing is happening there. If I restart my debugger, the problem goes away, only to rear it's head again randomly a few hours later. More critically, I see this bug in my error logs from the app running in production. </p> <p>I do a ton of LINQ in my app, against a dozen or so different entities in my database, but I only see this problem on queries related to a specific entity in my table. Some googling has suggested that this problem might be related to an incorrect relationship specified between my model and another entity, but I don't have <em>any</em> relationships with this object. It seems to be working 95% of the time, it's just the other 5% that fail.</p> <p>I have completely deleted the object from the designer, and re-added it from a "refreshed" server browser, and that did not fix the problem.</p> <p>Any ideas what's going on here?</p> <p>Here's the full error message and stack trace:</p> <blockquote> <p>Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index at System.Data.Linq.SqlClient.SqlProvider.Execute(Expression query, QueryInfo queryInfo, IObjectReaderFactory factory, Object[] parentArgs, Object[] userArgs, ICompiledSubQuery[] subQueries, Object lastResult) at System.Data.Linq.SqlClient.SqlProvider.ExecuteAll(Expression query, QueryInfo[] queryInfos, IObjectReaderFactory factory, Object[] userArguments, ICompiledSubQuery[] subQueries) at System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression query) at System.Data.Linq.Table<code>1.System.Linq.IQueryProvider.Execute[TResult](Expression expression) at System.Linq.Queryable.FirstOrDefault[TSource](IQueryable</code>1 source, Expression`1 predicate) at MyProject.FindUserByType(String typeId)</p> </blockquote> <p>EDIT: As requested, below is a copy of the table schema.</p> <pre><code>CREATE TABLE [dbo].[Container]( [ID] [int] IDENTITY(1,1) NOT NULL, [MarketCode] [varchar](max) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, [Description] [varchar](max) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, [Capacity] [int] NOT NULL, [Volume] [float] NOT NULL CONSTRAINT [PK_Container] PRIMARY KEY CLUSTERED ( [ID] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] </code></pre> <p>EDIT: The stack trace shows <code>FirstOrDefault</code>, but I duplicated the error using both <code>Take()</code> and <code>ToList()</code>. The stack trace is identical between all of these, simply interchangnig <code>FirstOrDefault/Take/ToList</code>. The move down the stack to <code>SqlProvider.Execute</code> is in fact identical. </p>
[ { "answer_id": 35437037, "author": "Nick Niebling", "author_id": 1095493, "author_profile": "https://Stackoverflow.com/users/1095493", "pm_score": 0, "selected": false, "text": "using(var ctx = new LinqDataContext())\n{\n List<Task> tasks = new List<Task>();\n for(int i=0;i<1000;i++)\n {\n var task = Task.Run(() => {\n var customer = ctx.Customers.SingleOrDefault(o => o.Id == i);\n customer.DoSomething();\n }\n tasks.Add(task);\n }\n Task.WaitAll(tasks);\n}\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17803/" ]
191,691
<p>I have come across numerous arguments against the inclusion of multiple inheritance in C#, some of which include (philosophical arguments aside):</p> <ul> <li>Multiple inheritance is too complicated and often ambiguous</li> <li>It is unnecessary because interfaces provide something similar</li> <li>Composition is a good substitute where interfaces are inappropriate</li> </ul> <p>I come from a C++ background and miss the power and elegance of multiple inheritance. Although it is not suited to all software designs there are situations where it is difficult to deny it's utility over interfaces, composition and similar OO techniques.</p> <p>Is the exclusion of multiple inheritance saying that developers are not smart enough to use them wisely and are incapable of addressing the complexities when they arise?</p> <p>I personally would welcome the introduction of multiple inheritance into C# (perhaps C##).</p> <hr> <p><strong>Addendum</strong>: I would be interested to know from the responses who comes from a single (or procedural background) versus a multiple inheritance background. I have often found that developers who have no experience with multiple inheritance will often default to the multiple-inheritance-is-unnecessary argument simply because they do not have any experience with the paradigm.</p>
[ { "answer_id": 191738, "author": "Chris Cudmore", "author_id": 18907, "author_profile": "https://Stackoverflow.com/users/18907", "pm_score": 5, "selected": false, "text": "class foo : bar, baz\n class foo : Ibarrable, Ibazzable\n{\n ... \n public Bar TheBar{ set }\n public Baz TheBaz{ set }\n\n public void BarFunction()\n {\n TheBar.doSomething();\n }\n public Thing BazFunction( object param )\n {\n return TheBaz.doSomethingComplex(param);\n }\n}\n" }, { "answer_id": 192179, "author": "Qwertie", "author_id": 22820, "author_profile": "https://Stackoverflow.com/users/22820", "pm_score": 3, "selected": false, "text": "/// This trait declares default methods of IList<T>\npublic trait DefaultListMethods<T> : IList<T>\n{\n // Methods without bodies must be implemented by another \n // trait or by the class\n public void Insert(int index, T item);\n public void RemoveAt(int index);\n public T this[int index] { get; set; }\n public int Count { get; }\n\n public int IndexOf(T item)\n {\n EqualityComparer<T> comparer = EqualityComparer<T>.Default;\n for (int i = 0; i < Count; i++)\n if (comparer.Equals(this[i], item))\n return i;\n return -1;\n }\n public void Add(T item)\n {\n Insert(Count, item);\n }\n public void Clear()\n { // Note: the class would be allowed to override the trait \n // with a better implementation, or select an \n // implementation from a different trait.\n for (int i = Count - 1; i >= 0; i--)\n RemoveAt(i);\n }\n public bool Contains(T item)\n {\n return IndexOf(item) != -1;\n }\n public void CopyTo(T[] array, int arrayIndex)\n {\n foreach (T item in this)\n array[arrayIndex++] = item;\n }\n public bool IsReadOnly\n {\n get { return false; }\n }\n public bool Remove(T item)\n {\n int i = IndexOf(item);\n if (i == -1)\n return false;\n RemoveAt(i);\n return true;\n }\n System.Collections.IEnumerator \n System.Collections.IEnumerable.GetEnumerator()\n {\n return GetEnumerator();\n }\n IEnumerator<T> GetEnumerator()\n {\n for (int i = 0; i < Count; i++)\n yield return this[i];\n }\n}\n class MyList<T> : MyBaseClass, DefaultListMethods<T>\n{\n public void Insert(int index, T item) { ... }\n public void RemoveAt(int index) { ... }\n public T this[int index] {\n get { ... }\n set { ... }\n }\n public int Count {\n get { ... }\n }\n}\n" }, { "answer_id": 192396, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 5, "selected": false, "text": "class private protected public public private class Foo : private Bar Bar Foo Bar abstract class Gun\n{ \n public void Shoot(object target) {} \n public void Shoot() {}\n\n public abstract void Reload();\n\n public void Cock() { Console.Write(\"Gun cocked.\"); }\n}\n\nclass Camera\n{ \n public void Shoot(object subject) {}\n\n public virtual void Reload() {}\n\n public virtual void Focus() {}\n}\n\n//this is great for taking pictures of targets!\nclass PhotoPistol : Gun, Camera\n{ \n public override void Reload() { Console.Write(\"Gun reloaded.\"); }\n\n public override void Camera.Reload() { Console.Write(\"Camera reloaded.\"); }\n\n public override void Focus() {}\n}\n\nvar pp = new PhotoPistol();\nGun gun = pp;\nCamera camera = pp;\n\npp.Shoot(); //Gun.Shoot()\npp.Reload(); //writes \"Gun reloaded\"\ncamera.Reload(); //writes \"Camera reloaded\"\npp.Cock(); //writes \"Gun cocked.\"\ncamera.Cock(); //error: Camera.Cock() not found\n((PhotoPistol) camera).Cock(); //writes \"Gun cocked.\"\ncamera.Shoot(); //error: Camera.Shoot() not found\n((PhotoPistol) camera).Shoot();//Gun.Shoot()\npp.Shoot(target); //Gun.Shoot(target)\ncamera.Shoot(target); //Camera.Shoot(target)\n public class PhotoPistol : Gun /* ,Camera */\n{\n PhotoPistolCamera camera;\n\n public PhotoPistol() {\n camera = new PhotoPistolCamera();\n }\n\n public void Focus() { camera.Focus(); }\n\n class PhotoPistolCamera : Camera \n { \n public override Focus() { }\n }\n\n public static Camera implicit operator(PhotoPistol p) \n { \n return p.camera; \n }\n}\n is as System.Type.IsSubClassOf()" }, { "answer_id": 271410, "author": "Jay Bazuzi", "author_id": 5314, "author_profile": "https://Stackoverflow.com/users/5314", "pm_score": 2, "selected": false, "text": "interface I\n{\n void F();\n void G();\n}\n\n\nclass DefaultI : I\n{\n void F() { ... }\n void G() { ... }\n}\n\nclass C : I = DefaultI\n{\n public void F() { ... } // implements I.F\n}\n ((I)new C()).F() C I.F() ((I)new C()).G() DefaultI I.G()" }, { "answer_id": 4877427, "author": "ctrl-alt-delor", "author_id": 537980, "author_profile": "https://Stackoverflow.com/users/537980", "pm_score": 0, "selected": false, "text": "class shape {}\n\nclass circle : shape {}\n\ninterface part {\n shape Form();\n}\n\ninterface wheel : part {\n circle Form();\n}\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1199234/" ]
191,692
<p>Is there a method to get all of the .aspx files in my website? Maybe iterate through the site's file structure and add to an array?</p>
[ { "answer_id": 191702, "author": "Shawn Miller", "author_id": 247, "author_profile": "https://Stackoverflow.com/users/247", "pm_score": 4, "selected": true, "text": "Directory.GetFiles(HttpContext.Current.Server.MapPath(@\"/\"), \"*.aspx\", SearchOption.AllDirectories);\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191692", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25515/" ]
191,704
<p>I want to use regular expressions (Perl compatible) to be able to find a pattern surrounded by two other patterns, but not include the strings matching the surrounding patterns in the match.</p> <p>For example, I want to be able to find occurrences of strings like:</p> <blockquote> <p>Foo Bar Baz</p> </blockquote> <p>But only have the match include the middle part:</p> <blockquote> <p>Bar</p> </blockquote> <p>I know this is possible, but I can't remember how to do it.</p>
[ { "answer_id": 191724, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 3, "selected": false, "text": "\"Foo (Bar) Baz\"\n ~> cat test.pl\n$a = \"The Foo Bar Baz was lass\";\n\n$a =~ m/Foo (Bar) Baz/;\n\nprint $1,\"\\n\";\n~> perl test.pl\nBar\n" }, { "answer_id": 191727, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 2, "selected": false, "text": "(?<=Foo\\s)Bar(?=\\sBaz)\n" }, { "answer_id": 192894, "author": "Michael Carman", "author_id": 8233, "author_profile": "https://Stackoverflow.com/users/8233", "pm_score": 3, "selected": true, "text": "Foo\\s+(Bar)\\s+Baz\n (?<=Foo\\s)Bar(?=\\sBaz)\n \\K Foo\\s+\\KBar(?=\\s+Baz)\n \\K" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191704", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4849/" ]
191,732
<p>I'm passing /file:c:\myfile.doc and I'm getting back "/file:c:\myfile.doc" instead of "C:\myfile.doc", could someone please advise where I am going wrong?</p> <pre><code> if (entry.ToUpper().IndexOf("FILE") != -1) { //override default log location MyFileLocation = entry.Split(new char[] {'='})[1]; } </code></pre>
[ { "answer_id": 191743, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 3, "selected": false, "text": " if (entry.ToUpper().IndexOf(\"FILE:\") == 0)\n {\n //override default log location\n MyFileLocation location = entry.Split(new char[] {':'},2)[1];\n }\n" }, { "answer_id": 191768, "author": "Scott Dorman", "author_id": 1559, "author_profile": "https://Stackoverflow.com/users/1559", "pm_score": 2, "selected": false, "text": "entry.Substring(6);\n" }, { "answer_id": 191772, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 0, "selected": false, "text": "/file=c:\\myfile.doc" }, { "answer_id": 191839, "author": "Carl", "author_id": 951280, "author_profile": "https://Stackoverflow.com/users/951280", "pm_score": 1, "selected": false, "text": "entry.split(new char[]{':'});\n entry.split(':');\n split(params char[] separator);\n entry.split(':','.',' ');\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
191,740
<p>I'm using SqlServer for the first time, and in every single one of our create procedure scripts there is a block of code like below to remove the procedure if it already exists:</p> <pre><code>IF EXISTS (SELECT * FROM information_schema.routines WHERE routine_name = 'SomeProcedureName' AND routine_type = 'PROCEDURE' BEGIN DROP PROCEDURE SomeProcedureName END //then the procedure definition </code></pre> <p>To stop cutting and pasting this boilerplate code in every file I would like to put this code in its own stored procedure so that instead the scripts would look like this:</p> <pre><code>DropIfRequired('SomeProcedureName') //then the procedure definition </code></pre> <p>My attempt at a solution is:</p> <pre><code>CREATE PROCEDURE DropIfRequired ( @procedureName varchar ) AS IF EXISTS (SELECT * FROM information_schema.routines WHERE routine_name = @procedureName AND routine_type = 'PROCEDURE') BEGIN DROP PROCEDURE @procedureName END </code></pre> <p>But I then get the following error:</p> <p>Msg 102, Level 15, State 1, Procedure DeleteProcedure, Line 10 Incorrect syntax near '@procedureName'.</p> <p>Any ideas how to do what I want?</p>
[ { "answer_id": 191753, "author": "StingyJack", "author_id": 16391, "author_profile": "https://Stackoverflow.com/users/16391", "pm_score": 2, "selected": false, "text": "EXEC( 'DROP PROCEDURE ''' + @procName + '''') ( all single quotes)\n" }, { "answer_id": 191793, "author": "Tim C", "author_id": 7585, "author_profile": "https://Stackoverflow.com/users/7585", "pm_score": 2, "selected": false, "text": "CREATE PROCEDURE DropIfRequired\n( \n @procedureName varchar\n)\n CREATE PROCEDURE DropIfRequired\n( \n @procedureName varchar(1000)\n)\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191740", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24063/" ]