qid
int64
4
8.14M
question
stringlengths
20
48.3k
answers
list
date
stringlengths
10
10
metadata
list
input
stringlengths
12
45k
output
stringlengths
2
31.8k
90,092
<p>I have a table in <code>MySQL</code> that has 3 fields and I want to enforce uniqueness among two of the fields. Here is the table <code>DDL</code>:</p> <pre><code>CREATE TABLE `CLIENT_NAMES` ( `ID` int(11) NOT NULL auto_increment, `CLIENT_NAME` varchar(500) NOT NULL, `OWNER_ID` int(11) NOT NULL, PRIMARY KEY (`ID`), ) ENGINE=InnoDB DEFAULT CHARSET=utf8; </code></pre> <p>The <code>ID</code> field is a surrogate key (this table is being loaded with ETL). The <code>CLIENT_NAME</code> is a field that contains names of clients The <code>OWNER_ID</code> is an id indicates a clients owner.</p> <p>I thought I could enforce this with a unique index on <code>CLIENT_NAME</code> and <code>OWNER_ID</code>, </p> <pre><code>ALTER TABLE `DW`.`CLIENT_NAMES` ADD UNIQUE INDEX enforce_unique_idx(`CLIENT_NAME`, `OWNER_ID`); </code></pre> <p>but MySQL gives me an error: </p> <blockquote> <p>Error executing SQL commands to update table. Specified key was too long; max key length is 765 bytes (error 1071)</p> </blockquote> <p>Anyone else have any ideas?</p>
[ { "answer_id": 90111, "author": "J D OConal", "author_id": 17023, "author_profile": "https://Stackoverflow.com/users/17023", "pm_score": 0, "selected": false, "text": "<p>Have you looked at CONSTRAINT ... UNIQUE?</p>\n" }, { "answer_id": 90116, "author": "Gili", "author_id": 14731, "author_profile": "https://Stackoverflow.com/users/14731", "pm_score": 4, "selected": true, "text": "<p>MySQL cannot enforce uniqueness on keys that are longer than 765 bytes (and apparently 500 UTF8 characters can surpass this limit).</p>\n\n<ol>\n<li>Does CLIENT_NAME really need to be 500 characters long? Seems a bit excessive.</li>\n<li>Add a new (shorter) column that is hash(CLIENT_NAME). Get MySQL to enforce uniqueness on that hash instead.</li>\n</ol>\n" }, { "answer_id": 90129, "author": "Terry G Lorber", "author_id": 809, "author_profile": "https://Stackoverflow.com/users/809", "pm_score": -1, "selected": false, "text": "<p><a href=\"http://www.xaprb.com/blog/2006/04/17/max-key-length-in-mysql/\" rel=\"nofollow noreferrer\">Here</a>. For the UTF8 charset, MySQL may use up to 3 bytes per character. CLIENT_NAME is 3 x 500 = 1500 bytes. Shorten <code>CLIENT_NAME</code> to 250.</p>\n\n<p><em>later:</em> +1 to creating a hash of the name and using that as the key.</p>\n" }, { "answer_id": 90189, "author": "Aeon", "author_id": 13289, "author_profile": "https://Stackoverflow.com/users/13289", "pm_score": 0, "selected": false, "text": "<p>Something seems a bit odd about this table; I would actually think about refactoring it. What do ID and OWNER_ID refer to, and what is the relationship between them? </p>\n\n<p>Would it make sense to have </p>\n\n<pre><code>CREATE TABLE `CLIENTS` (\n`ID` int(11) NOT NULL auto_increment,\n`CLIENT_NAME` varchar(500) NOT NULL,\n# other client fields - address, phone, whatever\nPRIMARY KEY (`ID`),\n) ENGINE=InnoDB DEFAULT CHARSET=utf8;\n\nCREATE TABLE `CLIENTS_OWNERS` (\n`CLIENT_ID` int(11) NOT NULL,\n`OWNER_ID` int(11) NOT NULL,\nPRIMARY KEY (`CLIENT_ID`,`OWNER_ID`),\n) ENGINE=InnoDB DEFAULT CHARSET=utf8;\n</code></pre>\n\n<p>I would really avoid adding a unique key like that on a 500 character string. It's much more efficient to enforce uniqueness on two ints, plus an id in a table should really refer to something that needs an id; in your version, the <code>ID</code> field seems to identify just the client/owner relationship, which really doesn't need a separate id, since it's just a mapping.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90092", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4082/" ]
I have a table in `MySQL` that has 3 fields and I want to enforce uniqueness among two of the fields. Here is the table `DDL`: ``` CREATE TABLE `CLIENT_NAMES` ( `ID` int(11) NOT NULL auto_increment, `CLIENT_NAME` varchar(500) NOT NULL, `OWNER_ID` int(11) NOT NULL, PRIMARY KEY (`ID`), ) ENGINE=InnoDB DEFAULT CHARSET=utf8; ``` The `ID` field is a surrogate key (this table is being loaded with ETL). The `CLIENT_NAME` is a field that contains names of clients The `OWNER_ID` is an id indicates a clients owner. I thought I could enforce this with a unique index on `CLIENT_NAME` and `OWNER_ID`, ``` ALTER TABLE `DW`.`CLIENT_NAMES` ADD UNIQUE INDEX enforce_unique_idx(`CLIENT_NAME`, `OWNER_ID`); ``` but MySQL gives me an error: > > Error executing SQL commands to update table. > Specified key was too long; max key length is 765 bytes (error 1071) > > > Anyone else have any ideas?
MySQL cannot enforce uniqueness on keys that are longer than 765 bytes (and apparently 500 UTF8 characters can surpass this limit). 1. Does CLIENT\_NAME really need to be 500 characters long? Seems a bit excessive. 2. Add a new (shorter) column that is hash(CLIENT\_NAME). Get MySQL to enforce uniqueness on that hash instead.
90,151
<p>Anyone got a working example of using ruby to post to a presigned URL on s3</p>
[ { "answer_id": 90708, "author": "Dan Harper", "author_id": 14530, "author_profile": "https://Stackoverflow.com/users/14530", "pm_score": 0, "selected": false, "text": "<p>Does anything on the <a href=\"http://amazon.rubyforge.org/\" rel=\"nofollow noreferrer\">s3 library page</a> cover what you need? There are loads of examples there.</p>\n" }, { "answer_id": 98952, "author": "Dan Harper", "author_id": 14530, "author_profile": "https://Stackoverflow.com/users/14530", "pm_score": 1, "selected": false, "text": "<p>Can you provide more information on how a \"presigned URL\" works? Is it like this:</p>\n\n<pre><code>AWS::S3::S3Object.url_for(self.full_filename,\n self.bucket_name, {\n :use_ssl =&gt; true,\n :expires_in =&gt; ttl_seconds\n })\n</code></pre>\n\n<p>I use this code to send authenticated clients the URL to their S3 file. I believe this is the \"presigned URL\" that you're asking about. I haven't used this code for a PUT, so I'm not exactly sure if it's right for you, but it might get you close.</p>\n" }, { "answer_id": 106744, "author": "macarthy", "author_id": 17232, "author_profile": "https://Stackoverflow.com/users/17232", "pm_score": -1, "selected": false, "text": "<p>I've managed to sort it out. Turns out the HTTP:Net in Ruby is has some short comings. Lot of Monkeypatch later I got it working.. More details when I have time. thank</p>\n" }, { "answer_id": 216555, "author": "Pistos", "author_id": 28558, "author_profile": "https://Stackoverflow.com/users/28558", "pm_score": 0, "selected": false, "text": "<p>There are some generic REST libraries for Ruby; Google for \"ruby rest client\". See also <a href=\"http://railstips.org/2008/7/29/it-s-an-httparty-and-everyone-is-invited\" rel=\"nofollow noreferrer\">HTTParty</a>.</p>\n" }, { "answer_id": 14748463, "author": "CantGetANick", "author_id": 228589, "author_profile": "https://Stackoverflow.com/users/228589", "pm_score": 2, "selected": false, "text": "<p>I have used aws-sdk and right_aws both.</p>\n\n<p>Here is the code to do this.</p>\n\n<pre><code>require 'rubygems'\nrequire 'aws-sdk'\nrequire 'right_aws'\nrequire 'net/http'\nrequire 'uri'\nrequire 'rack'\n\n\naccess_key_id = 'AAAAAAAAAAAAAAAAA'\nsecret_access_key = 'ASDFASDFAS4646ASDFSAFASDFASDFSADF'\n\n\ns3 = AWS::S3.new( :access_key_id =&gt; access_key_id, :secret_access_key =&gt; secret_access_key)\n\nright_s3 = RightAws::S3Interface.new(access_key_id, secret_access_key, {:multi_thread =&gt; true, :logger =&gt; nil} ) \n\n\n\nbucket_name = 'your-bucket-name'\nkey = \"your-file-name.ext\"\n\nright_url = right_s3.put_link(bucket_name, key)\nright_scan_command = \"curl -I --upload-file #{key} '#{right_url.to_s}'\"\nsystem(right_scan_command)\n\nbucket = s3.buckets[bucket_name]\nform = bucket.presigned_post(:key =&gt; key)\nuri = URI(form.url.to_s + '/' + key)\nuri.query = Rack::Utils.build_query(form.fields)\nscan_command = \"curl -I --upload-file #{key} '#{uri.to_s}'\"\nsystem(scan_command)\n</code></pre>\n" }, { "answer_id": 50590108, "author": "J. Lovell", "author_id": 9865885, "author_profile": "https://Stackoverflow.com/users/9865885", "pm_score": 1, "selected": false, "text": "<p>I know this is an older question, but I was wondering the same thing and found an elegant solution in the <a href=\"https://docs.aws.amazon.com/AmazonS3/latest/dev/UploadObjectPreSignedURLRubySDK.html\" rel=\"nofollow noreferrer\">AWS S3 Documentation</a>.</p>\n\n<pre><code>require 'net/http'\n\nfile = \"somefile.ext\"\nurl = URI.parse(presigned_url)\nNet::HTTP.start(url.host) do |http|\n http.send_request(\"PUT\", url.request_uri, File.read(file), {\"content-type\" =&gt; \"\",})\nend\n</code></pre>\n\n<p>This worked great for my Device Farm uploads.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90151", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17232/" ]
Anyone got a working example of using ruby to post to a presigned URL on s3
I have used aws-sdk and right\_aws both. Here is the code to do this. ``` require 'rubygems' require 'aws-sdk' require 'right_aws' require 'net/http' require 'uri' require 'rack' access_key_id = 'AAAAAAAAAAAAAAAAA' secret_access_key = 'ASDFASDFAS4646ASDFSAFASDFASDFSADF' s3 = AWS::S3.new( :access_key_id => access_key_id, :secret_access_key => secret_access_key) right_s3 = RightAws::S3Interface.new(access_key_id, secret_access_key, {:multi_thread => true, :logger => nil} ) bucket_name = 'your-bucket-name' key = "your-file-name.ext" right_url = right_s3.put_link(bucket_name, key) right_scan_command = "curl -I --upload-file #{key} '#{right_url.to_s}'" system(right_scan_command) bucket = s3.buckets[bucket_name] form = bucket.presigned_post(:key => key) uri = URI(form.url.to_s + '/' + key) uri.query = Rack::Utils.build_query(form.fields) scan_command = "curl -I --upload-file #{key} '#{uri.to_s}'" system(scan_command) ```
90,178
<p>I am working on a web application where I want the content to fill the height of the entire screen.</p> <p>The page has a header, which contains a logo, and account information. This could be an arbitrary height. I want the content div to fill the rest of the page to the bottom.</p> <p>I have a header <code>div</code> and a content <code>div</code>. At the moment I am using a table for the layout like so:</p> <p>CSS and HTML</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>#page { height: 100%; width: 100% } #tdcontent { height: 100%; } #content { overflow: auto; /* or overflow: hidden; */ }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;table id="page"&gt; &lt;tr&gt; &lt;td id="tdheader"&gt; &lt;div id="header"&gt;...&lt;/div&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td id="tdcontent"&gt; &lt;div id="content"&gt;...&lt;/div&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt;</code></pre> </div> </div> </p> <p>The entire height of the page is filled, and no scrolling is required.</p> <p>For anything inside the content div, setting <code>top: 0;</code> will put it right underneath the header. Sometimes the content will be a real table, with its height set to 100%. Putting <code>header</code> inside <code>content</code> will not allow this to work.</p> <p>Is there a way to achieve the same effect without using the <code>table</code>?</p> <p><strong>Update:</strong></p> <p>Elements inside the content <code>div</code> will have heights set to percentages as well. So something at 100% inside the <code>div</code> will fill it to the bottom. As will two elements at 50%.</p> <p><strong>Update 2:</strong></p> <p>For instance, if the header takes up 20% of the screen's height, a table specified at 50% inside <code>#content</code> would take up 40% of the screen space. So far, wrapping the entire thing in a table is the only thing that works.</p>
[ { "answer_id": 90414, "author": "Jerph", "author_id": 1701, "author_profile": "https://Stackoverflow.com/users/1701", "pm_score": 4, "selected": false, "text": "<pre><code>&lt;!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt;\n&lt;html xmlns=\"http://www.w3.org/1999/xhtml\"&gt;\n&lt;head&gt;\n&lt;title&gt;Test&lt;/title&gt;\n&lt;style type=\"text/css\"&gt;\nbody\n,html\n{\n height: 100%;\n margin: 0;\n padding: 0;\n color: #FFF;\n}\n\n#header\n{\n float: left;\n width: 100%;\n background: red;\n}\n\n#content\n{\n height: 100%;\n overflow: auto;\n background: blue;\n}\n\n&lt;/style&gt;\n&lt;/head&gt;\n&lt;body&gt;\n\n &lt;div id=\"content\"&gt;\n &lt;div id=\"header\"&gt;\n Header\n &lt;p&gt;Header stuff&lt;/p&gt;\n &lt;/div&gt;\n Content\n &lt;p&gt;Content stuff&lt;/p&gt;\n &lt;/div&gt;\n\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>In all sane browsers, you can put the \"header\" div before the content, as a sibling, and the same CSS will work. However, IE7- does not interpret the height correctly if the float is 100% in that case, so the header needs to be IN the content, as above. The overflow: auto will cause double scroll bars on IE (which always has the viewport scrollbar visible, but disabled), but without it, the content will clip if it overflows.</p>\n" }, { "answer_id": 90886, "author": "NICCAI", "author_id": 1629400, "author_profile": "https://Stackoverflow.com/users/1629400", "pm_score": 8, "selected": false, "text": "<p>There really isn't a sound, cross-browser way to do this in CSS. Assuming your layout has complexities, you need to use JavaScript to set the element's height. The essence of what you need to do is:</p>\n\n<pre><code>Element Height = Viewport height - element.offset.top - desired bottom margin\n</code></pre>\n\n<p>Once you can get this value and set the element's height, you need to attach event handlers to both the window onload and onresize so that you can fire your resize function.</p>\n\n<p>Also, assuming your content could be larger than the viewport, you will need to set overflow-y to scroll.</p>\n" }, { "answer_id": 94925, "author": "Jerph", "author_id": 1701, "author_profile": "https://Stackoverflow.com/users/1701", "pm_score": 3, "selected": false, "text": "<p>Vincent, I'll answer again using your new requirements. Since you don't care about the content being hidden if it's too long, you don't need to float the header. Just put overflow hidden on the html and body tags, and set <code>#content</code> height to 100%. The content will always be longer than the viewport by the height of the header, but it'll be hidden and won't cause scrollbars.</p>\n\n<pre><code>&lt;!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt;\n&lt;html xmlns=\"http://www.w3.org/1999/xhtml\"&gt;\n &lt;head&gt;\n &lt;title&gt;Test&lt;/title&gt;\n &lt;style type=\"text/css\"&gt;\n body, html {\n height: 100%;\n margin: 0;\n padding: 0;\n overflow: hidden;\n color: #FFF;\n }\n p {\n margin: 0;\n }\n\n #header {\n background: red;\n }\n\n #content {\n position: relative;\n height: 100%;\n background: blue;\n }\n\n #content #positioned {\n position: absolute;\n top: 0;\n right: 0;\n }\n &lt;/style&gt;\n&lt;/head&gt;\n\n&lt;body&gt;\n &lt;div id=\"header\"&gt;\n Header\n &lt;p&gt;Header stuff&lt;/p&gt;\n &lt;/div&gt;\n\n &lt;div id=\"content\"&gt;\n Content\n &lt;p&gt;Content stuff&lt;/p&gt;\n &lt;div id=\"positioned\"&gt;Positioned Content&lt;/div&gt;\n &lt;/div&gt;\n\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n" }, { "answer_id": 5623913, "author": "Chris", "author_id": 13700, "author_profile": "https://Stackoverflow.com/users/13700", "pm_score": 5, "selected": false, "text": "<p>I've been searching for an answer for this as well. If you are fortunate enough to be able to target IE8 and up, you can use <code>display:table</code> and related values to get the rendering rules of tables with block-level elements including div.</p>\n\n<p>If you are even luckier and your users are using top-tier browsers (for example, if this is an intranet app on computers you control, like my latest project is), you can use the new <a href=\"http://www.w3.org/TR/css3-flexbox/\" rel=\"noreferrer\">Flexible Box Layout</a> in CSS3!</p>\n" }, { "answer_id": 6409310, "author": "B_G", "author_id": 806386, "author_profile": "https://Stackoverflow.com/users/806386", "pm_score": 4, "selected": false, "text": "<p>I wresteled with this for a while and ended up with the following:</p>\n\n<p>Since it is easy to make the content DIV the same height as the parent but apparently difficult to make it the parent height minus the header height I decided to make content div full height but position it absolutely in the top left corner and then define a padding for the top which has the height of the header. This way the content displays neatly under the header and fills the whole remaining space:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>body {\n padding: 0;\n margin: 0;\n height: 100%;\n overflow: hidden;\n}\n\n#header {\n position: absolute;\n top: 0;\n left: 0;\n height: 50px;\n}\n\n#content {\n position: absolute;\n top: 0;\n left: 0;\n padding-top: 50px;\n height: 100%;\n}\n</code></pre>\n" }, { "answer_id": 6964558, "author": "STeN", "author_id": 384115, "author_profile": "https://Stackoverflow.com/users/384115", "pm_score": -1, "selected": false, "text": "<p>it <strong>never worked for me in other way then with use of the JavaScript</strong> as NICCAI suggested in the very first answer. I am using that approach to rescale the <code>&lt;div&gt;</code> with the Google Maps. </p>\n\n<p>Here is the full example how to do that (works in Safari/FireFox/IE/iPhone/Andorid (works with rotation)):</p>\n\n<p>CSS</p>\n\n<pre><code>body {\n height: 100%;\n margin: 0;\n padding: 0;\n}\n\n.header {\n height: 100px;\n background-color: red;\n}\n\n.content {\n height: 100%;\n background-color: green;\n}\n</code></pre>\n\n<p>JS</p>\n\n<pre><code>function resize() {\n // Get elements and necessary element heights\n var contentDiv = document.getElementById(\"contentId\");\n var headerDiv = document.getElementById(\"headerId\");\n var headerHeight = headerDiv.offsetHeight;\n\n // Get view height\n var viewportHeight = document.getElementsByTagName('body')[0].clientHeight;\n\n // Compute the content height - we want to fill the whole remaining area\n // in browser window\n contentDiv.style.height = viewportHeight - headerHeight;\n}\n\nwindow.onload = resize;\nwindow.onresize = resize;\n</code></pre>\n\n<p>HTML</p>\n\n<pre><code>&lt;body&gt;\n &lt;div class=\"header\" id=\"headerId\"&gt;Hello&lt;/div&gt;\n &lt;div class=\"content\" id=\"contentId\"&gt;&lt;/div&gt;\n&lt;/body&gt;\n</code></pre>\n" }, { "answer_id": 7794900, "author": "Tonye - True Vine Productions", "author_id": 999297, "author_profile": "https://Stackoverflow.com/users/999297", "pm_score": 5, "selected": false, "text": "<p>What worked for me (with a div within another div and I assume in all other circumstances) is to set the bottom padding to 100%. That is, add this to your css / stylesheet:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>padding-bottom: 100%;\n</code></pre>\n" }, { "answer_id": 7851347, "author": "h--n", "author_id": 375230, "author_profile": "https://Stackoverflow.com/users/375230", "pm_score": 8, "selected": false, "text": "<p>The original post is more than 3 years ago. I guess many people who come to this post like me are looking for an app-like layout solution, say a somehow fixed header, footer, and full height content taking up the rest screen. If so, this post may help, it works on IE7+, etc.</p>\n\n<p><a href=\"http://blog.stevensanderson.com/2011/10/05/full-height-app-layouts-a-css-trick-to-make-it-easier/\" rel=\"noreferrer\">http://blog.stevensanderson.com/2011/10/05/full-height-app-layouts-a-css-trick-to-make-it-easier/</a></p>\n\n<p>And here are some snippets from that post:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>@media screen { \r\n \r\n /* start of screen rules. */ \r\n \r\n /* Generic pane rules */\r\n body { margin: 0 }\r\n .row, .col { overflow: hidden; position: absolute; }\r\n .row { left: 0; right: 0; }\r\n .col { top: 0; bottom: 0; }\r\n .scroll-x { overflow-x: auto; }\r\n .scroll-y { overflow-y: auto; }\r\n\r\n .header.row { height: 75px; top: 0; }\r\n .body.row { top: 75px; bottom: 50px; }\r\n .footer.row { height: 50px; bottom: 0; }\r\n \r\n /* end of screen rules. */ \r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div class=\"header row\" style=\"background:yellow;\"&gt;\r\n &lt;h2&gt;My header&lt;/h2&gt;\r\n&lt;/div&gt; \r\n&lt;div class=\"body row scroll-y\" style=\"background:lightblue;\"&gt;\r\n &lt;p&gt;The body&lt;/p&gt;\r\n&lt;/div&gt; \r\n&lt;div class=\"footer row\" style=\"background:#e9e9e9;\"&gt;\r\n My footer\r\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 9358676, "author": "Thaoms", "author_id": 1220637, "author_profile": "https://Stackoverflow.com/users/1220637", "pm_score": 4, "selected": false, "text": "<p>Why not just like this?</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>html, body {\n height: 100%;\n}\n\n#containerInput {\n background-image: url('../img/edit_bg.jpg');\n height: 40%;\n}\n\n#containerControl {\n background-image: url('../img/control_bg.jpg');\n height: 60%;\n}\n</code></pre>\n\n<p>Giving you html and body (in that order) a height and then just give your elements a height?</p>\n\n<p>Works for me</p>\n" }, { "answer_id": 12420383, "author": "htho", "author_id": 1635906, "author_profile": "https://Stackoverflow.com/users/1635906", "pm_score": 2, "selected": false, "text": "<p>I found a quite simple solution, because for me it was just a design issue.\nI wanted the rest of the Page not to be white below the red footer.\nSo i set the pages background color to red. And the contents backgroundcolor to white.\nWith the contents height set to eg. 20em or 50% an almost empty page won't leave the whole page red. </p>\n" }, { "answer_id": 16251731, "author": "Arun", "author_id": 161633, "author_profile": "https://Stackoverflow.com/users/161633", "pm_score": 3, "selected": false, "text": "<p>Try this</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>var sizeFooter = function(){\n $(\".webfooter\")\n .css(\"padding-bottom\", \"0px\")\n .css(\"padding-bottom\", $(window).height() - $(\"body\").height())\n}\n$(window).resize(sizeFooter);\n</code></pre>\n" }, { "answer_id": 16357269, "author": "Mikko Rantalainen", "author_id": 334451, "author_profile": "https://Stackoverflow.com/users/334451", "pm_score": 5, "selected": false, "text": "<p>If you can deal with not supporting old browsers (that is, MSIE 9 or older), you can do this with <a href=\"http://caniuse.com/#feat=flexbox\" rel=\"noreferrer\">Flexible Box Layout Module</a> which is already W3C CR. That module allows other nice tricks, too, such as re-ordering content.</p>\n<p>Unfortunately, MSIE 9 or lesser do not support this and you have to use vendor prefix for the CSS property for every browser other than Firefox. Hopefully other vendors drop the prefix soon, too.</p>\n<p>An another choice would be <a href=\"http://caniuse.com/#search=grid\" rel=\"noreferrer\">CSS Grid Layout</a> but that has even less support from stable versions of browsers. In practice, only MSIE 10 supports this.</p>\n<p><strong>Update year 2020</strong>: All modern browsers support both <code>display: flex</code> and <code>display: grid</code>. The only one missing is support for <code>subgrid</code> which in only supported by Firefox. Note that MSIE does not support either by the spec but if you're willing to add MSIE specific CSS hacks, it can be made to behave. I would suggest simply ignoring MSIE because even Microsoft says it should not be used anymore. Microsoft Edge supports these features just fine (except for subgrid support since is shares the Blink rendering engine with Chrome).</p>\n<p><strong>Example using <code>display: grid</code>:</strong></p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>html, body\n{\n min-height: 100vh;\n padding: 0;\n margin: 0;\n}\n\nbody\n{\n display: grid;\n grid:\n \"myheader\" auto\n \"mymain\" minmax(0,1fr)\n \"myfooter\" auto /\n minmax(10rem, 90rem);\n}\n\nheader\n{\n grid-area: myheader;\n background: yellow;\n}\n\nmain\n{\n grid-area: mymain;\n background: pink;\n align-self: center\n /* or stretch\n + display: flex;\n + flex-direction: column;\n + justify-content: center; */\n}\n\nfooter\n{\n grid-area: myfooter;\n background: cyan;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;header&gt;Header content&lt;/header&gt;\n&lt;main&gt;Main content which should be centered and the content length may change.\n&lt;details&gt;&lt;summary&gt;Collapsible content&lt;/summary&gt;\n&lt;p&gt;Here's some text to cause more vertical space to be used.&lt;/p&gt;\n&lt;p&gt;Here's some text to cause more vertical space to be used (2).&lt;/p&gt;\n&lt;p&gt;Here's some text to cause more vertical space to be used (3).&lt;/p&gt;\n&lt;p&gt;Here's some text to cause more vertical space to be used (4).&lt;/p&gt;\n&lt;p&gt;Here's some text to cause more vertical space to be used (5).&lt;/p&gt;\n&lt;/details&gt;\n&lt;/main&gt;\n&lt;footer&gt;Footer content&lt;/footer&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p><strong>Example using <code>display: flex</code>:</strong></p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>html, body\n{\n min-height: 100vh;\n padding: 0;\n margin: 0;\n}\n\nbody\n{\n display: flex; \n}\n\nmain\n{\n background: pink;\n align-self: center;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;main&gt;Main content which should be centered and the content length may change.\n&lt;details&gt;&lt;summary&gt;Collapsible content&lt;/summary&gt;\n&lt;p&gt;Here's some text to cause more vertical space to be used.&lt;/p&gt;\n&lt;p&gt;Here's some text to cause more vertical space to be used (2).&lt;/p&gt;\n&lt;p&gt;Here's some text to cause more vertical space to be used (3).&lt;/p&gt;\n&lt;p&gt;Here's some text to cause more vertical space to be used (4).&lt;/p&gt;\n&lt;p&gt;Here's some text to cause more vertical space to be used (5).&lt;/p&gt;\n&lt;/details&gt;\n&lt;/main&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 16960823, "author": "Danield", "author_id": 703717, "author_profile": "https://Stackoverflow.com/users/703717", "pm_score": 7, "selected": false, "text": "<p>Instead of using tables in the markup, you could use CSS tables.</p>\n\n<h2>Markup</h2>\n\n<pre><code>&lt;body&gt; \n &lt;div&gt;hello &lt;/div&gt;\n &lt;div&gt;there&lt;/div&gt;\n&lt;/body&gt;\n</code></pre>\n\n<h2>(Relevant) CSS</h2>\n\n<pre><code>body\n{\n display:table;\n width:100%;\n}\ndiv\n{\n display:table-row;\n}\ndiv+ div\n{\n height:100%; \n}\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/danield770/FC7eY/\"><strong>FIDDLE1</strong></a> and <strong><a href=\"http://jsfiddle.net/danield770/FC7eY/1/\">FIDDLE2</a></strong></p>\n\n<p><strong>Some advantages of this method are:</strong></p>\n\n<p>1) Less markup</p>\n\n<p>2) Markup is more semantic than tables, because this is not tabular data.</p>\n\n<p>3) Browser support is <strong>very good</strong>: IE8+, All modern browsers and mobile devices (<a href=\"http://caniuse.com/css-table\">caniuse</a>) </p>\n\n<p><hr>\nJust for completeness, here are the equivalent Html elements to css properties for the <a href=\"http://www.w3.org/TR/CSS2/tables.html#table-display\">The CSS table model</a></p>\n\n<pre><code>table { display: table }\ntr { display: table-row }\nthead { display: table-header-group }\ntbody { display: table-row-group }\ntfoot { display: table-footer-group }\ncol { display: table-column }\ncolgroup { display: table-column-group }\ntd, th { display: table-cell }\ncaption { display: table-caption } \n</code></pre>\n" }, { "answer_id": 17496982, "author": "Greg", "author_id": 745250, "author_profile": "https://Stackoverflow.com/users/745250", "pm_score": 3, "selected": false, "text": "<p>You can actually use <code>display: table</code> to split the area into two elements (header and content), where the header can vary in height and the content fills the remaining space. This works with the whole page, as well as when the area is simply the content of another element positioned with <code>position</code> set to <code>relative</code>, <code>absolute</code> or <code>fixed</code>. It will work as long as the parent element has a non-zero height.</p>\n\n<p><a href=\"http://jsfiddle.net/amiramix/aD6gE/\" rel=\"noreferrer\">See this fiddle</a> and also the code below:</p>\n\n<p>CSS:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>body, html {\n height: 100%;\n margin: 0;\n padding: 0;\n}\n\np {\n margin: 0;\n padding: 0;\n}\n\n.additional-padding {\n height: 50px;\n background-color: #DE9;\n}\n\n.as-table {\n display: table;\n height: 100%;\n width: 100%;\n}\n\n.as-table-row {\n display: table-row;\n height: 100%;\n}\n\n#content {\n width: 100%;\n height: 100%;\n background-color: #33DD44;\n}\n</code></pre>\n\n<p>HTML:</p>\n\n<pre class=\"lang-html prettyprint-override\"><code>&lt;div class=\"as-table\"&gt;\n &lt;div id=\"header\"&gt;\n &lt;p&gt;This header can vary in height, it also doesn't have to be displayed as table-row. It will simply take the necessary space and the rest below will be taken by the second div which is displayed as table-row. Now adding some copy to artificially expand the header.&lt;/p&gt;\n &lt;div class=\"additional-padding\"&gt;&lt;/div&gt;\n &lt;/div&gt;\n &lt;div class=\"as-table-row\"&gt;\n &lt;div id=\"content\"&gt;\n &lt;p&gt;This is the actual content that takes the rest of the available space.&lt;/p&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n" }, { "answer_id": 23323175, "author": "Mr. Alien", "author_id": 1542290, "author_profile": "https://Stackoverflow.com/users/1542290", "pm_score": 7, "selected": false, "text": "<h2>CSS only Approach (If height is known/fixed)</h2>\n\n<p>When you want the middle element to span across entire page vertically, you can use <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/calc\" rel=\"noreferrer\"><code>calc()</code></a> which is introduced in CSS3.</p>\n\n<p>Assuming we have a <em>fixed height</em> <code>header</code> and <code>footer</code> elements and we want the <code>section</code> tag to take entire available vertical height...</p>\n\n<p><a href=\"http://jsfiddle.net/WdrDH/\" rel=\"noreferrer\"><strong>Demo</strong></a></p>\n\n<p><strong>Assumed markup</strong> and your CSS should be</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>html,\r\nbody {\r\n height: 100%;\r\n}\r\n\r\nheader {\r\n height: 100px;\r\n background: grey;\r\n}\r\n\r\nsection {\r\n height: calc(100% - (100px + 150px));\r\n /* Adding 100px of header and 150px of footer */\r\n background: tomato;\r\n}\r\n\r\nfooter {\r\n height: 150px;\r\n background-color: blue;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;header&gt;100px&lt;/header&gt;\r\n&lt;section&gt;Expand me for remaining space&lt;/section&gt;\r\n&lt;footer&gt;150px&lt;/footer&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>So here, what am doing is, adding up the height of elements and than deducting from <code>100%</code> using <code>calc()</code> function.</p>\n\n<p>Just make sure that you use <code>height: 100%;</code> for the parent elements.</p>\n" }, { "answer_id": 24979148, "author": "Pebbl", "author_id": 1490904, "author_profile": "https://Stackoverflow.com/users/1490904", "pm_score": 12, "selected": true, "text": "<h3>2015 update: the flexbox approach</h3>\n\n<p>There are two other answers briefly mentioning <a href=\"https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Flexible_boxes\" rel=\"noreferrer\">flexbox</a>; however, that was more than two years ago, and they don't provide any examples. The specification for flexbox has definitely settled now.</p>\n\n<blockquote>\n <p>Note: Though CSS Flexible Boxes Layout specification is at the Candidate Recommendation stage, not all browsers have implemented it. WebKit implementation must be prefixed with -webkit-; Internet Explorer implements an old version of the spec, prefixed with -ms-; Opera 12.10 implements the latest version of the spec, unprefixed. See the compatibility table on each property for an up-to-date compatibility status.</p>\n \n <p>(taken from <a href=\"https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Flexible_boxes\" rel=\"noreferrer\">https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Flexible_boxes</a>)</p>\n</blockquote>\n\n<p>All major browsers and IE11+ support Flexbox. For IE 10 or older, you can use the FlexieJS shim.</p>\n\n<p>To check current support you can also see here:\n<a href=\"http://caniuse.com/#feat=flexbox\" rel=\"noreferrer\">http://caniuse.com/#feat=flexbox</a></p>\n\n<h3>Working example</h3>\n\n<p>With flexbox you can easily switch between any of your rows or columns either having fixed dimensions, content-sized dimensions or remaining-space dimensions. In my example I have set the header to snap to its content (as per the OPs question), I've added a footer to show how to add a fixed-height region and then set the content area to fill up the remaining space.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>html,\r\nbody {\r\n height: 100%;\r\n margin: 0;\r\n}\r\n\r\n.box {\r\n display: flex;\r\n flex-flow: column;\r\n height: 100%;\r\n}\r\n\r\n.box .row {\r\n border: 1px dotted grey;\r\n}\r\n\r\n.box .row.header {\r\n flex: 0 1 auto;\r\n /* The above is shorthand for:\r\n flex-grow: 0,\r\n flex-shrink: 1,\r\n flex-basis: auto\r\n */\r\n}\r\n\r\n.box .row.content {\r\n flex: 1 1 auto;\r\n}\r\n\r\n.box .row.footer {\r\n flex: 0 1 40px;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;!-- Obviously, you could use HTML5 tags like `header`, `footer` and `section` --&gt;\r\n\r\n&lt;div class=\"box\"&gt;\r\n &lt;div class=\"row header\"&gt;\r\n &lt;p&gt;&lt;b&gt;header&lt;/b&gt;\r\n &lt;br /&gt;\r\n &lt;br /&gt;(sized to content)&lt;/p&gt;\r\n &lt;/div&gt;\r\n &lt;div class=\"row content\"&gt;\r\n &lt;p&gt;\r\n &lt;b&gt;content&lt;/b&gt;\r\n (fills remaining space)\r\n &lt;/p&gt;\r\n &lt;/div&gt;\r\n &lt;div class=\"row footer\"&gt;\r\n &lt;p&gt;&lt;b&gt;footer&lt;/b&gt; (fixed height)&lt;/p&gt;\r\n &lt;/div&gt;\r\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>In the CSS above, the <a href=\"https://developer.mozilla.org/en/CSS/flex\" rel=\"noreferrer\">flex</a> property shorthands the <a href=\"https://developer.mozilla.org/en/CSS/flex-grow\" rel=\"noreferrer\">flex-grow</a>, <a href=\"https://developer.mozilla.org/en/CSS/flex-shrink\" rel=\"noreferrer\">flex-shrink</a>, and <a href=\"https://developer.mozilla.org/en/CSS/flex-basis\" rel=\"noreferrer\">flex-basis</a> properties to establish the flexibility of the flex items. Mozilla has a <a href=\"https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Flexible_boxes\" rel=\"noreferrer\">good introduction to the flexible boxes model</a>.</p>\n" }, { "answer_id": 25838052, "author": "Ormoz", "author_id": 1600305, "author_profile": "https://Stackoverflow.com/users/1600305", "pm_score": 5, "selected": false, "text": "<p>It could be done purely by <code>CSS</code> using <code>vh</code>:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>#page {\n display:block; \n width:100%; \n height:95vh !important; \n overflow:hidden;\n}\n\n#tdcontent {\n float:left; \n width:100%; \n display:block;\n}\n\n#content { \n float:left; \n width:100%; \n height:100%; \n display:block; \n overflow:scroll;\n}\n</code></pre>\n\n<p>and the <code>HTML</code></p>\n\n<pre><code>&lt;div id=\"page\"&gt;\n\n &lt;div id=\"tdcontent\"&gt;&lt;/div&gt;\n &lt;div id=\"content\"&gt;&lt;/div&gt;\n\n&lt;/div&gt;\n</code></pre>\n\n<p>I checked it, It works in all major browsers: <code>Chrome</code>, <code>IE</code>, and <code>FireFox</code></p>\n" }, { "answer_id": 28634506, "author": "John Kurlak", "author_id": 55732, "author_profile": "https://Stackoverflow.com/users/55732", "pm_score": 5, "selected": false, "text": "<p>None of the solutions posted work when you need the bottom div to scroll when the content is too tall. Here's a solution that works in that case:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.table {\r\n display: table;\r\n}\r\n\r\n.table-row {\r\n display: table-row;\r\n}\r\n\r\n.table-cell {\r\n display: table-cell;\r\n}\r\n\r\n.container {\r\n width: 400px;\r\n height: 300px;\r\n}\r\n\r\n.header {\r\n background: cyan;\r\n}\r\n\r\n.body {\r\n background: yellow;\r\n height: 100%;\r\n}\r\n\r\n.body-content-outer-wrapper {\r\n height: 100%;\r\n}\r\n\r\n.body-content-inner-wrapper {\r\n height: 100%;\r\n position: relative;\r\n overflow: auto;\r\n}\r\n\r\n.body-content {\r\n position: absolute;\r\n top: 0;\r\n bottom: 0;\r\n left: 0;\r\n right: 0;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div class=\"table container\"&gt;\r\n &lt;div class=\"table-row header\"&gt;\r\n &lt;div&gt;This is the header whose height is unknown&lt;/div&gt;\r\n &lt;div&gt;This is the header whose height is unknown&lt;/div&gt;\r\n &lt;div&gt;This is the header whose height is unknown&lt;/div&gt;\r\n &lt;/div&gt;\r\n &lt;div class=\"table-row body\"&gt;\r\n &lt;div class=\"table-cell body-content-outer-wrapper\"&gt;\r\n &lt;div class=\"body-content-inner-wrapper\"&gt;\r\n &lt;div class=\"body-content\"&gt;\r\n &lt;div&gt;This is the scrollable content whose height is unknown&lt;/div&gt;\r\n &lt;div&gt;This is the scrollable content whose height is unknown&lt;/div&gt;\r\n &lt;div&gt;This is the scrollable content whose height is unknown&lt;/div&gt;\r\n &lt;div&gt;This is the scrollable content whose height is unknown&lt;/div&gt;\r\n &lt;div&gt;This is the scrollable content whose height is unknown&lt;/div&gt;\r\n &lt;div&gt;This is the scrollable content whose height is unknown&lt;/div&gt;\r\n &lt;div&gt;This is the scrollable content whose height is unknown&lt;/div&gt;\r\n &lt;div&gt;This is the scrollable content whose height is unknown&lt;/div&gt;\r\n &lt;div&gt;This is the scrollable content whose height is unknown&lt;/div&gt;\r\n &lt;div&gt;This is the scrollable content whose height is unknown&lt;/div&gt;\r\n &lt;div&gt;This is the scrollable content whose height is unknown&lt;/div&gt;\r\n &lt;div&gt;This is the scrollable content whose height is unknown&lt;/div&gt;\r\n &lt;div&gt;This is the scrollable content whose height is unknown&lt;/div&gt;\r\n &lt;div&gt;This is the scrollable content whose height is unknown&lt;/div&gt;\r\n &lt;div&gt;This is the scrollable content whose height is unknown&lt;/div&gt;\r\n &lt;div&gt;This is the scrollable content whose height is unknown&lt;/div&gt;\r\n &lt;div&gt;This is the scrollable content whose height is unknown&lt;/div&gt;\r\n &lt;div&gt;This is the scrollable content whose height is unknown&lt;/div&gt;\r\n &lt;/div&gt;\r\n &lt;/div&gt;\r\n &lt;/div&gt;\r\n &lt;/div&gt;\r\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p><a href=\"http://blogs.msdn.com/b/kurlak/archive/2015/02/20/filling-the-remaining-height-of-a-container-while-handling-overflow-in-css.aspx\" rel=\"noreferrer\">Original source: Filling the Remaining Height of a Container While Handling Overflow in CSS</a></p>\n\n<p><a href=\"http://jsfiddle.net/352ntoz2/\" rel=\"noreferrer\">JSFiddle live preview</a></p>\n" }, { "answer_id": 28771764, "author": "zok", "author_id": 795398, "author_profile": "https://Stackoverflow.com/users/795398", "pm_score": 6, "selected": false, "text": "<p>A simple solution, using flexbox:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>html,\r\nbody {\r\n height: 100%;\r\n}\r\n\r\nbody {\r\n display: flex;\r\n flex-direction: column;\r\n}\r\n\r\n.content {\r\n flex-grow: 1;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;body&gt;\r\n &lt;div&gt;header&lt;/div&gt;\r\n &lt;div class=\"content\"&gt;&lt;/div&gt;\r\n&lt;/body&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p><a href=\"http://codepen.io/isaacalves/pen/myKpVK\" rel=\"noreferrer\">Codepen sample</a></p>\n\n<p><a href=\"http://codepen.io/isaacalves/pen/MYXENq\" rel=\"noreferrer\">An alternate solution, with a div centered within the content div</a></p>\n" }, { "answer_id": 32182925, "author": "dev.meghraj", "author_id": 1435800, "author_profile": "https://Stackoverflow.com/users/1435800", "pm_score": 5, "selected": false, "text": "<p><strong>CSS3 Simple Way</strong></p>\n\n<pre><code>height: calc(100% - 10px); // 10px is height of your first div...\n</code></pre>\n\n<p>all major browsers these days support it, so go ahead if you don't have requirement to support vintage browsers.</p>\n" }, { "answer_id": 33439733, "author": "puiu", "author_id": 1727232, "author_profile": "https://Stackoverflow.com/users/1727232", "pm_score": 4, "selected": false, "text": "<p>There's a ton of answers now, but I found using <code>height: 100vh;</code> to work on the div element that needs to fill up the entire vertical space available.</p>\n\n<p>In this way, I do not need to play around with display or positioning. This came in handy when using Bootstrap to make a dashboard wherein I had a sidebar and a main. I wanted the main to stretch and fill the entire vertical space so that I could apply a background colour.</p>\n\n<pre><code>div {\n height: 100vh;\n}\n</code></pre>\n\n<p>Supports IE9 and up: <a href=\"http://caniuse.com/#feat=viewport-units\" rel=\"noreferrer\">click to see the link</a></p>\n" }, { "answer_id": 34579298, "author": "Michael P. Bazos", "author_id": 3120193, "author_profile": "https://Stackoverflow.com/users/3120193", "pm_score": 5, "selected": false, "text": "<blockquote>\n <p><em>Disclaimer: The accepted answer gives the idea of the solution, but I'm finding it a bit bloated with an unnecessary wrapper and css rules. Below is a solution with very few css rules.</em></p>\n</blockquote>\n\n<p><strong>HTML 5</strong></p>\n\n<pre><code>&lt;body&gt;\n &lt;header&gt;Header with an arbitrary height&lt;/header&gt;\n &lt;main&gt;\n This container will grow so as to take the remaining height\n &lt;/main&gt;\n&lt;/body&gt;\n</code></pre>\n\n<p><strong>CSS</strong></p>\n\n<pre><code>body {\n display: flex;\n flex-direction: column;\n min-height: 100vh; /* body takes whole viewport's height */\n}\n\nmain {\n flex: 1; /* this will make the container take the free space */\n}\n</code></pre>\n\n<p>Solution above uses <a href=\"http://caniuse.com/#feat=viewport-units\" rel=\"noreferrer\">viewport units</a> and <a href=\"http://caniuse.com/#feat=flexbox\" rel=\"noreferrer\">flexbox</a>, and is therefore IE10+, providing you use the old syntax for IE10.</p>\n\n<p><strong>Codepen to play with: <a href=\"http://codepen.io/michaelbazos/pen/mVRBXM\" rel=\"noreferrer\">link to codepen</a></strong></p>\n\n<p><strong>Or this one, for those needing the main container to be scrollable in case of overflowing content: <a href=\"http://codepen.io/michaelbazos/pen/pgRWVG\" rel=\"noreferrer\">link to codepen</a></strong></p>\n" }, { "answer_id": 37370197, "author": "nguyên", "author_id": 572180, "author_profile": "https://Stackoverflow.com/users/572180", "pm_score": 6, "selected": false, "text": "<p>Used: \n<code>height: calc(100vh - 110px);</code></p>\n\n<p>code: \n<div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code> \r\n.header { height: 60px; top: 0; background-color: green}\r\n.body {\r\n height: calc(100vh - 110px); /*50+60*/\r\n background-color: gray;\r\n}\r\n.footer { height: 50px; bottom: 0; }\r\n </code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div class=\"header\"&gt;\r\n &lt;h2&gt;My header&lt;/h2&gt;\r\n&lt;/div&gt; \r\n&lt;div class=\"body\"&gt;\r\n &lt;p&gt;The body&lt;/p&gt;\r\n&lt;/div&gt; \r\n&lt;div class=\"footer\"&gt;\r\n My footer\r\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 38153735, "author": "Pat M", "author_id": 4155124, "author_profile": "https://Stackoverflow.com/users/4155124", "pm_score": 3, "selected": false, "text": "<p>Spinning off the idea of Mr. Alien...</p>\n\n<p>This seems a cleaner solution than the popular flex box one for CSS3 enabled browsers.</p>\n\n<p>Simply use min-height(instead of height) with calc() to the content block. </p>\n\n<p>The calc() starts with 100% and subtracts heights of headers and footers (need to include padding values)</p>\n\n<p>Using \"min-height\" instead of \"height\" is particularly useful so it can work with javascript rendered content and JS frameworks like Angular2. Otherwise, the calculation will not push the footer to the bottom of the page once the javascript rendered content is visible.</p>\n\n<p>Here is a simple example of a header and footer using 50px height and 20px padding for both.</p>\n\n<p>Html:</p>\n\n<pre><code>&lt;body&gt;\n &lt;header&gt;&lt;/header&gt;\n &lt;div class=\"content\"&gt;&lt;/div&gt;\n &lt;footer&gt;&lt;/footer&gt;\n&lt;/body&gt;\n</code></pre>\n\n<p>Css:</p>\n\n<pre><code>.content {\n min-height: calc(100% - (50px + 20px + 20px + 50px + 20px + 20px));\n}\n</code></pre>\n\n<p>Of course, the math can be simplified but you get the idea...</p>\n" }, { "answer_id": 39150121, "author": "Anthony Brenelière", "author_id": 3433751, "author_profile": "https://Stackoverflow.com/users/3433751", "pm_score": 3, "selected": false, "text": "<p>I had the same problem but I could not make work the solution with flexboxes above. So I created my own template, that includes:</p>\n\n<ul>\n<li>a header with a fixed size element</li>\n<li>a footer</li>\n<li>a side bar with a scrollbar that occupies the remaining height</li>\n<li>content</li>\n</ul>\n\n<p>I used flexboxes but in a more simple way, using only properties <strong>display: flex</strong> and <strong>flex-direction: row|column</strong>:</p>\n\n<p>I do use angular and I want my component sizes to be 100% of their parent element.</p>\n\n<p>The key is to set the size (in percents) for all parents inorder to limit their size. In the following example myapp height has 100% of the viewport.</p>\n\n<p>The main component has 90% of the viewport, because header and footer have 5%.</p>\n\n<p>I posted my template here: <a href=\"https://jsfiddle.net/abreneliere/mrjh6y2e/3\" rel=\"noreferrer\">https://jsfiddle.net/abreneliere/mrjh6y2e/3</a></p>\n\n<pre><code> body{\n margin: 0;\n color: white;\n height: 100%;\n }\n div#myapp\n {\n display: flex;\n flex-direction: column;\n background-color: red; /* &lt;-- painful color for your eyes ! */\n height: 100%; /* &lt;-- if you remove this line, myapp has no limited height */\n }\n div#main /* parent div for sidebar and content */\n {\n display: flex;\n width: 100%;\n height: 90%; \n }\n div#header {\n background-color: #333;\n height: 5%;\n }\n div#footer {\n background-color: #222;\n height: 5%;\n }\n div#sidebar {\n background-color: #666;\n width: 20%;\n overflow-y: auto;\n }\n div#content {\n background-color: #888;\n width: 80%;\n overflow-y: auto;\n }\n div.fized_size_element {\n background-color: #AAA;\n display: block;\n width: 100px;\n height: 50px;\n margin: 5px;\n }\n</code></pre>\n\n<p>Html:</p>\n\n<pre><code>&lt;body&gt;\n&lt;div id=\"myapp\"&gt;\n &lt;div id=\"header\"&gt;\n HEADER\n &lt;div class=\"fized_size_element\"&gt;&lt;/div&gt;\n\n &lt;/div&gt;\n &lt;div id=\"main\"&gt;\n &lt;div id=\"sidebar\"&gt;\n SIDEBAR\n &lt;div class=\"fized_size_element\"&gt;&lt;/div&gt;\n &lt;div class=\"fized_size_element\"&gt;&lt;/div&gt;\n &lt;div class=\"fized_size_element\"&gt;&lt;/div&gt;\n &lt;div class=\"fized_size_element\"&gt;&lt;/div&gt;\n &lt;div class=\"fized_size_element\"&gt;&lt;/div&gt;\n &lt;div class=\"fized_size_element\"&gt;&lt;/div&gt;\n &lt;div class=\"fized_size_element\"&gt;&lt;/div&gt;\n &lt;div class=\"fized_size_element\"&gt;&lt;/div&gt;\n &lt;/div&gt;\n &lt;div id=\"content\"&gt;\n CONTENT\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;div id=\"footer\"&gt;\n FOOTER\n &lt;/div&gt;\n&lt;/div&gt;\n&lt;/body&gt;\n</code></pre>\n" }, { "answer_id": 40011321, "author": "James Yang", "author_id": 4612829, "author_profile": "https://Stackoverflow.com/users/4612829", "pm_score": 0, "selected": false, "text": "<p>It's dynamic calc the remining screen space, better using Javascript.</p>\n\n<p>You can use CSS-IN-JS technology, like below lib:</p>\n\n<p><a href=\"https://github.com/cssobj/cssobj\" rel=\"nofollow\">https://github.com/cssobj/cssobj</a></p>\n\n<p>DEMO: <a href=\"https://cssobj.github.io/cssobj-demo/\" rel=\"nofollow\">https://cssobj.github.io/cssobj-demo/</a></p>\n" }, { "answer_id": 41984205, "author": "grinmax", "author_id": 7309671, "author_profile": "https://Stackoverflow.com/users/7309671", "pm_score": 3, "selected": false, "text": "<p>For mobile app i use only VH and VW</p>\n<pre class=\"lang-html prettyprint-override\"><code>&lt;div class=&quot;container&quot;&gt;\n &lt;div class=&quot;title&quot;&gt;Title&lt;/div&gt;\n &lt;div class=&quot;content&quot;&gt;Content&lt;/div&gt;\n &lt;div class=&quot;footer&quot;&gt;Footer&lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n<pre class=\"lang-css prettyprint-override\"><code>.container {\n width: 100vw;\n height: 100vh;\n font-size: 5vh;\n}\n \n.title {\n height: 20vh;\n background-color: red;\n}\n \n.content {\n height: 60vh;\n background: blue;\n}\n \n.footer {\n height: 20vh;\n background: green;\n}\n</code></pre>\n<p>Demo - <a href=\"https://jsfiddle.net/u763ck92/\" rel=\"nofollow noreferrer\">https://jsfiddle.net/u763ck92/</a></p>\n" }, { "answer_id": 44607939, "author": "Alireza", "author_id": 5423108, "author_profile": "https://Stackoverflow.com/users/5423108", "pm_score": 6, "selected": false, "text": "<p>How about you simply use <code>vh</code> which stands for <code>view height</code> in <strong>CSS</strong>...</p>\n\n<p>Look at the <strong>code snippet</strong> I created for you below and run it:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>body {\r\n padding: 0;\r\n margin: 0;\r\n}\r\n\r\n.full-height {\r\n width: 100px;\r\n height: 100vh;\r\n background: red;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div class=\"full-height\"&gt;\r\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Also, look at the image below which I created for you:</p>\n\n<p><a href=\"https://i.stack.imgur.com/Oy7mP.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/Oy7mP.jpg\" alt=\"Make a div fill the height of the remaining screen space\"></a></p>\n" }, { "answer_id": 44908512, "author": "Paulie_D", "author_id": 2802040, "author_profile": "https://Stackoverflow.com/users/2802040", "pm_score": 4, "selected": false, "text": "<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout\" rel=\"noreferrer\"><strong>CSS Grid Solution</strong></a></p>\n\n<p>Just defining the <code>body</code> with <code>display:grid</code> and the <code>grid-template-rows</code> using <code>auto</code> and the <code>fr</code> value property.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>* {\r\n margin: 0;\r\n padding: 0;\r\n}\r\n\r\nhtml {\r\n height: 100%;\r\n}\r\n\r\nbody {\r\n min-height: 100%;\r\n display: grid;\r\n grid-template-rows: auto 1fr auto;\r\n}\r\n\r\nheader {\r\n padding: 1em;\r\n background: pink;\r\n}\r\n\r\nmain {\r\n padding: 1em;\r\n background: lightblue;\r\n}\r\n\r\nfooter {\r\n padding: 2em;\r\n background: lightgreen;\r\n}\r\n\r\nmain:hover {\r\n height: 2000px;\r\n /* demos expansion of center element */\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;header&gt;HEADER&lt;/header&gt;\r\n&lt;main&gt;MAIN&lt;/main&gt;\r\n&lt;footer&gt;FOOTER&lt;/footer&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p><a href=\"https://css-tricks.com/snippets/css/complete-guide-grid/\" rel=\"noreferrer\"><strong>A Complete Guide to Grids @ CSS-Tricks.com</strong></a></p>\n" }, { "answer_id": 49447848, "author": "Zohab Ali", "author_id": 5361964, "author_profile": "https://Stackoverflow.com/users/5361964", "pm_score": 3, "selected": false, "text": "<pre><code> style=\"height:100vh\"\n</code></pre>\n\n<p>solved the problem for me. In my case I applied this to the required div</p>\n" }, { "answer_id": 60403264, "author": "gadolf", "author_id": 5889767, "author_profile": "https://Stackoverflow.com/users/5889767", "pm_score": 5, "selected": false, "text": "<p><strong>In Bootstrap:</strong></p>\n<p>CSS Styles:</p>\n<pre><code>html, body {\n height: 100%;\n}\n</code></pre>\n<hr />\n<p><em>1) Just fill the height of the remaining screen space:</em></p>\n<pre><code>&lt;body class=&quot;d-flex flex-column&quot;&gt;\n &lt;div class=&quot;d-flex flex-column flex-grow-1&quot;&gt;\n\n &lt;header&gt;Header&lt;/header&gt;\n &lt;div&gt;Content&lt;/div&gt;\n &lt;footer class=&quot;mt-auto&quot;&gt;Footer&lt;/footer&gt;\n\n &lt;/div&gt;\n&lt;/body&gt;\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/3vE98m.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/3vE98m.png\" alt=\"![enter image description here\" /></a></p>\n<hr />\n<p><em>2) fill the height of the remaining screen space and aligning content to the middle of the parent element:</em></p>\n<pre><code>&lt;body class=&quot;d-flex flex-column&quot;&gt;\n &lt;div class=&quot;d-flex flex-column flex-grow-1&quot;&gt;\n\n &lt;header&gt;Header&lt;/header&gt;\n &lt;div class=&quot;d-flex flex-column flex-grow-1 justify-content-center&quot;&gt;Content&lt;/div&gt;\n &lt;footer class=&quot;mt-auto&quot;&gt;Footer&lt;/footer&gt;\n\n &lt;/div&gt;\n&lt;/body&gt;\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/P9o0fm.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/P9o0fm.png\" alt=\"![enter image description here\" /></a></p>\n" }, { "answer_id": 61217322, "author": "Michael Schade", "author_id": 1236252, "author_profile": "https://Stackoverflow.com/users/1236252", "pm_score": 4, "selected": false, "text": "<p>This is my own minimal version of Pebbl's solution. Took forever to find the trick to get it to work in IE11. (Also tested in Chrome, Firefox, Edge, and Safari.)</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>html {\n height: 100%;\n}\n\nbody {\n height: 100%;\n margin: 0;\n}\n\nsection {\n display: flex;\n flex-direction: column;\n height: 100%;\n}\n\ndiv:first-child {\n background: gold;\n}\n\ndiv:last-child {\n background: plum;\n flex-grow: 1;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;body&gt;\n &lt;section&gt;\n &lt;div&gt;FIT&lt;/div&gt;\n &lt;div&gt;GROW&lt;/div&gt;\n &lt;/section&gt;\n&lt;/body&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 64374418, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>One more solution using <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout\" rel=\"nofollow noreferrer\">CSS Grid</a></p>\n<p>Define grid</p>\n<pre><code>.root {\n display: grid;\n grid-template-rows: minmax(60px, auto) minmax(0, 100%);\n}\n</code></pre>\n<p>First row(header): Min height can be set-up and max height will depend on content.\nSecond row(content) will try to fit free space that left after header.</p>\n<p>The advantage of this approach is content can be scrolled independently of header, so header is always at the top of the page</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>body, html {\n margin: 0;\n height: 100%;\n}\n\n.root {\n display: grid;\n grid-template-rows: minmax(60px, auto) minmax(0, 100%);\n height: 100%;\n}\n\n.header {\n background-color: lightblue;\n}\n\nbutton {\n background-color: darkslateblue;\n color: white;\n padding: 10px 50px;\n margin: 10px 30px;\n border-radius: 15px;\n border: none;\n}\n\n.content {\n background-color: antiquewhite;\n overflow: auto;\n}\n\n.block {\n width: calc(100% - 20px);\n height: 120px;\n border: solid aquamarine;\n margin: 10px;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div class=\"root\"&gt;\n &lt;div class=\"header\"&gt;\n &lt;button&gt;click&lt;/button&gt;\n &lt;button&gt;click&lt;/button&gt;\n &lt;button&gt;click&lt;/button&gt;\n &lt;button&gt;click&lt;/button&gt;\n &lt;button&gt;click&lt;/button&gt;\n &lt;/div&gt;\n &lt;div class=\"content\"&gt;\n &lt;div class=\"block\"&gt;&lt;/div&gt;\n &lt;div class=\"block\"&gt;&lt;/div&gt;\n &lt;div class=\"block\"&gt;&lt;/div&gt;\n &lt;div class=\"block\"&gt;&lt;/div&gt;\n &lt;div class=\"block\"&gt;&lt;/div&gt;\n &lt;div class=\"block\"&gt;&lt;/div&gt;\n &lt;div class=\"block\"&gt;&lt;/div&gt;\n &lt;div class=\"block\"&gt;&lt;/div&gt;\n&lt;/div&gt;\n &lt;div class=\"footer\"&gt;&lt;/div&gt;\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 66466661, "author": "Chukwuemeka Maduekwe", "author_id": 12490386, "author_profile": "https://Stackoverflow.com/users/12490386", "pm_score": -1, "selected": false, "text": "<p>All you have to do if you're using display: flex on the parent div is to simply set height to stretch or fill like so</p>\n<pre><code>.divName {\n height: stretch\n}\n</code></pre>\n" }, { "answer_id": 66524544, "author": "Just a coder", "author_id": 433073, "author_profile": "https://Stackoverflow.com/users/433073", "pm_score": 2, "selected": false, "text": "<p>Here is an answer that uses grids.</p>\n<pre class=\"lang-css prettyprint-override\"><code>.the-container-div {\n display: grid;\n grid-template-columns: 1fr;\n grid-template-rows: auto min-content;\n height: 100vh;\n}\n.view-to-remain-small {\n grid-row: 2;\n}\n\n.view-to-be-stretched {\n grid-row: 1\n}\n</code></pre>\n" }, { "answer_id": 69921961, "author": "Chong Lip Phang", "author_id": 2435020, "author_profile": "https://Stackoverflow.com/users/2435020", "pm_score": 0, "selected": false, "text": "<p>Some of my components were loaded dynamically, and this caused me problems with setting the height of the navigation bar.</p>\n<p>What I did was to use <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Resize_Observer_API\" rel=\"nofollow noreferrer\">the ResizeObserver API</a>.</p>\n<pre><code>function observeMainResize(){\n const resizeObserver = new ResizeObserver(entries =&gt; {\n for (let entry of entries) {\n $(&quot;nav&quot;).height(Math.max($(&quot;main&quot;).height(),\n $(&quot;nav&quot;) .height()));\n }\n });\n resizeObserver.observe(document.querySelector('main'));\n}\n</code></pre>\n<p>then:</p>\n<pre><code>...\n&lt;body onload=&quot;observeMainResize()&quot;&gt;\n &lt;nav&gt;...&lt;/nav&gt;\n &lt;main&gt;...&lt;/main&gt;\n...\n</code></pre>\n" }, { "answer_id": 71203452, "author": "yoty66", "author_id": 12624118, "author_profile": "https://Stackoverflow.com/users/12624118", "pm_score": 1, "selected": false, "text": "<p>A nice hack would be to set the css margin property to &quot;auto&quot;.\nIt will make the div take up all the remaining height &amp; width .</p>\n<p>The downside is that it would be computed as margin and not the content .</p>\n<p>See attached screenshots:</p>\n<p><a href=\"https://i.stack.imgur.com/jLDC2.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/jLDC2.png\" alt=\"before1\" /></a>\n<a href=\"https://i.stack.imgur.com/hoFa7.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/hoFa7.png\" alt=\"before2\" /></a></p>\n<p><a href=\"https://i.stack.imgur.com/SulwP.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/SulwP.png\" alt=\"after1\" /></a></p>\n<p><a href=\"https://i.stack.imgur.com/tw7n7.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/tw7n7.png\" alt=\"after2\" /></a></p>\n" }, { "answer_id": 73698597, "author": "Chong Lip Phang", "author_id": 2435020, "author_profile": "https://Stackoverflow.com/users/2435020", "pm_score": -1, "selected": false, "text": "<p>Consider setting all the 'position's to 'fixed', and then using {top:0; bottom:0;}</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;!DOCTYPE html&gt;\n&lt;html&gt;&lt;head&gt;\n&lt;style&gt;\n#B {\n position:fixed;\n width: 100%;\n height: 100%;\n background-color: orange;\n}\n#B1 {\n position:fixed;\n top:0;\n bottom: 0;\n width: 100%;\n background-color: cyan; \n}\n#B2 {\n position:fixed;\n bottom: 0;\n height: 35px;\n width: 100%;\n background: green;\n}\n\n}&lt;/style&gt;&lt;/head&gt;\n&lt;body&gt;\n &lt;div id=\"B1\"&gt;B1&lt;/div&gt;\n &lt;div id=\"B2\"&gt;B2&lt;/div&gt;\n&lt;/body&gt;\n&lt;/html&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Note that there is some overlapping, so be careful.</p>\n<p>If you want to vertically occupy the available space of a parent &lt; div&gt;, use absolute positioning instead.</p>\n" }, { "answer_id": 74196906, "author": "yongrui", "author_id": 2079846, "author_profile": "https://Stackoverflow.com/users/2079846", "pm_score": -1, "selected": false, "text": "<p>height: calc(100% - 650px);\nposition: absolute;</p>\n" }, { "answer_id": 74304362, "author": "Nyi Nyi Hmue Aung", "author_id": 15247669, "author_profile": "https://Stackoverflow.com/users/15247669", "pm_score": 1, "selected": false, "text": "<p>For me the easiest way to do this is by using Grid. But, I am looking for an easier approach. Here is How I am doing it and it works. But, it becomes too much of pain if we have a lot of nested divs.</p>\n<pre><code> &lt;div style={{\n display:grid,\n gridTemplateRows:'max-content 1fr',\n}}&gt;\n &lt;div&gt;\n Header\n &lt;/div&gt;\n &lt;div style={{height:'100%',minHeight:'0'}}&gt;\n Content\n &lt;/div&gt;\n &lt;/div&gt;\n\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90178", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16299/" ]
I am working on a web application where I want the content to fill the height of the entire screen. The page has a header, which contains a logo, and account information. This could be an arbitrary height. I want the content div to fill the rest of the page to the bottom. I have a header `div` and a content `div`. At the moment I am using a table for the layout like so: CSS and HTML ```css #page { height: 100%; width: 100% } #tdcontent { height: 100%; } #content { overflow: auto; /* or overflow: hidden; */ } ``` ```html <table id="page"> <tr> <td id="tdheader"> <div id="header">...</div> </td> </tr> <tr> <td id="tdcontent"> <div id="content">...</div> </td> </tr> </table> ``` The entire height of the page is filled, and no scrolling is required. For anything inside the content div, setting `top: 0;` will put it right underneath the header. Sometimes the content will be a real table, with its height set to 100%. Putting `header` inside `content` will not allow this to work. Is there a way to achieve the same effect without using the `table`? **Update:** Elements inside the content `div` will have heights set to percentages as well. So something at 100% inside the `div` will fill it to the bottom. As will two elements at 50%. **Update 2:** For instance, if the header takes up 20% of the screen's height, a table specified at 50% inside `#content` would take up 40% of the screen space. So far, wrapping the entire thing in a table is the only thing that works.
### 2015 update: the flexbox approach There are two other answers briefly mentioning [flexbox](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Flexible_boxes); however, that was more than two years ago, and they don't provide any examples. The specification for flexbox has definitely settled now. > > Note: Though CSS Flexible Boxes Layout specification is at the Candidate Recommendation stage, not all browsers have implemented it. WebKit implementation must be prefixed with -webkit-; Internet Explorer implements an old version of the spec, prefixed with -ms-; Opera 12.10 implements the latest version of the spec, unprefixed. See the compatibility table on each property for an up-to-date compatibility status. > > > (taken from <https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Flexible_boxes>) > > > All major browsers and IE11+ support Flexbox. For IE 10 or older, you can use the FlexieJS shim. To check current support you can also see here: <http://caniuse.com/#feat=flexbox> ### Working example With flexbox you can easily switch between any of your rows or columns either having fixed dimensions, content-sized dimensions or remaining-space dimensions. In my example I have set the header to snap to its content (as per the OPs question), I've added a footer to show how to add a fixed-height region and then set the content area to fill up the remaining space. ```css html, body { height: 100%; margin: 0; } .box { display: flex; flex-flow: column; height: 100%; } .box .row { border: 1px dotted grey; } .box .row.header { flex: 0 1 auto; /* The above is shorthand for: flex-grow: 0, flex-shrink: 1, flex-basis: auto */ } .box .row.content { flex: 1 1 auto; } .box .row.footer { flex: 0 1 40px; } ``` ```html <!-- Obviously, you could use HTML5 tags like `header`, `footer` and `section` --> <div class="box"> <div class="row header"> <p><b>header</b> <br /> <br />(sized to content)</p> </div> <div class="row content"> <p> <b>content</b> (fills remaining space) </p> </div> <div class="row footer"> <p><b>footer</b> (fixed height)</p> </div> </div> ``` In the CSS above, the [flex](https://developer.mozilla.org/en/CSS/flex) property shorthands the [flex-grow](https://developer.mozilla.org/en/CSS/flex-grow), [flex-shrink](https://developer.mozilla.org/en/CSS/flex-shrink), and [flex-basis](https://developer.mozilla.org/en/CSS/flex-basis) properties to establish the flexibility of the flex items. Mozilla has a [good introduction to the flexible boxes model](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Flexible_boxes).
90,181
<p>I've just run into a display glitch in IE6 with the ExtJS framework. - Hopefully someone can point me in the right direction.</p> <p>In the following example, the bbar for the panel is displayed 2ems narrower than the panel it is attached to (it's left aligned) in IE6, where as in Firefox it is displayed as the same width as the panel.</p> <p>Can anyone suggest how to fix this?</p> <p>I seem to be able to work around either by specifying the width of the panel in ems or the padding in pixels, but I assume it would be expected to work as I have it below.</p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt; &lt;html&gt; &lt;head&gt; &lt;link rel="stylesheet" type="text/css" href="ext/resources/css/ext-all.css"/&gt; &lt;script type="text/javascript" src="ext/ext-base.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="ext/ext-all-debug.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; Ext.onReady(function(){ var main = new Ext.Panel({ renderTo: 'content', bodyStyle: 'padding: 1em;', width: 500, html: "Alignment issue in IE - The bbar's width is 2ems less than the main panel in IE6.", bbar: [ "-&gt;", {id: "continue", text: 'Continue'} ] }); }); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="content"&gt;&lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[ { "answer_id": 90414, "author": "Jerph", "author_id": 1701, "author_profile": "https://Stackoverflow.com/users/1701", "pm_score": 4, "selected": false, "text": "<pre><code>&lt;!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt;\n&lt;html xmlns=\"http://www.w3.org/1999/xhtml\"&gt;\n&lt;head&gt;\n&lt;title&gt;Test&lt;/title&gt;\n&lt;style type=\"text/css\"&gt;\nbody\n,html\n{\n height: 100%;\n margin: 0;\n padding: 0;\n color: #FFF;\n}\n\n#header\n{\n float: left;\n width: 100%;\n background: red;\n}\n\n#content\n{\n height: 100%;\n overflow: auto;\n background: blue;\n}\n\n&lt;/style&gt;\n&lt;/head&gt;\n&lt;body&gt;\n\n &lt;div id=\"content\"&gt;\n &lt;div id=\"header\"&gt;\n Header\n &lt;p&gt;Header stuff&lt;/p&gt;\n &lt;/div&gt;\n Content\n &lt;p&gt;Content stuff&lt;/p&gt;\n &lt;/div&gt;\n\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>In all sane browsers, you can put the \"header\" div before the content, as a sibling, and the same CSS will work. However, IE7- does not interpret the height correctly if the float is 100% in that case, so the header needs to be IN the content, as above. The overflow: auto will cause double scroll bars on IE (which always has the viewport scrollbar visible, but disabled), but without it, the content will clip if it overflows.</p>\n" }, { "answer_id": 90886, "author": "NICCAI", "author_id": 1629400, "author_profile": "https://Stackoverflow.com/users/1629400", "pm_score": 8, "selected": false, "text": "<p>There really isn't a sound, cross-browser way to do this in CSS. Assuming your layout has complexities, you need to use JavaScript to set the element's height. The essence of what you need to do is:</p>\n\n<pre><code>Element Height = Viewport height - element.offset.top - desired bottom margin\n</code></pre>\n\n<p>Once you can get this value and set the element's height, you need to attach event handlers to both the window onload and onresize so that you can fire your resize function.</p>\n\n<p>Also, assuming your content could be larger than the viewport, you will need to set overflow-y to scroll.</p>\n" }, { "answer_id": 94925, "author": "Jerph", "author_id": 1701, "author_profile": "https://Stackoverflow.com/users/1701", "pm_score": 3, "selected": false, "text": "<p>Vincent, I'll answer again using your new requirements. Since you don't care about the content being hidden if it's too long, you don't need to float the header. Just put overflow hidden on the html and body tags, and set <code>#content</code> height to 100%. The content will always be longer than the viewport by the height of the header, but it'll be hidden and won't cause scrollbars.</p>\n\n<pre><code>&lt;!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt;\n&lt;html xmlns=\"http://www.w3.org/1999/xhtml\"&gt;\n &lt;head&gt;\n &lt;title&gt;Test&lt;/title&gt;\n &lt;style type=\"text/css\"&gt;\n body, html {\n height: 100%;\n margin: 0;\n padding: 0;\n overflow: hidden;\n color: #FFF;\n }\n p {\n margin: 0;\n }\n\n #header {\n background: red;\n }\n\n #content {\n position: relative;\n height: 100%;\n background: blue;\n }\n\n #content #positioned {\n position: absolute;\n top: 0;\n right: 0;\n }\n &lt;/style&gt;\n&lt;/head&gt;\n\n&lt;body&gt;\n &lt;div id=\"header\"&gt;\n Header\n &lt;p&gt;Header stuff&lt;/p&gt;\n &lt;/div&gt;\n\n &lt;div id=\"content\"&gt;\n Content\n &lt;p&gt;Content stuff&lt;/p&gt;\n &lt;div id=\"positioned\"&gt;Positioned Content&lt;/div&gt;\n &lt;/div&gt;\n\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n" }, { "answer_id": 5623913, "author": "Chris", "author_id": 13700, "author_profile": "https://Stackoverflow.com/users/13700", "pm_score": 5, "selected": false, "text": "<p>I've been searching for an answer for this as well. If you are fortunate enough to be able to target IE8 and up, you can use <code>display:table</code> and related values to get the rendering rules of tables with block-level elements including div.</p>\n\n<p>If you are even luckier and your users are using top-tier browsers (for example, if this is an intranet app on computers you control, like my latest project is), you can use the new <a href=\"http://www.w3.org/TR/css3-flexbox/\" rel=\"noreferrer\">Flexible Box Layout</a> in CSS3!</p>\n" }, { "answer_id": 6409310, "author": "B_G", "author_id": 806386, "author_profile": "https://Stackoverflow.com/users/806386", "pm_score": 4, "selected": false, "text": "<p>I wresteled with this for a while and ended up with the following:</p>\n\n<p>Since it is easy to make the content DIV the same height as the parent but apparently difficult to make it the parent height minus the header height I decided to make content div full height but position it absolutely in the top left corner and then define a padding for the top which has the height of the header. This way the content displays neatly under the header and fills the whole remaining space:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>body {\n padding: 0;\n margin: 0;\n height: 100%;\n overflow: hidden;\n}\n\n#header {\n position: absolute;\n top: 0;\n left: 0;\n height: 50px;\n}\n\n#content {\n position: absolute;\n top: 0;\n left: 0;\n padding-top: 50px;\n height: 100%;\n}\n</code></pre>\n" }, { "answer_id": 6964558, "author": "STeN", "author_id": 384115, "author_profile": "https://Stackoverflow.com/users/384115", "pm_score": -1, "selected": false, "text": "<p>it <strong>never worked for me in other way then with use of the JavaScript</strong> as NICCAI suggested in the very first answer. I am using that approach to rescale the <code>&lt;div&gt;</code> with the Google Maps. </p>\n\n<p>Here is the full example how to do that (works in Safari/FireFox/IE/iPhone/Andorid (works with rotation)):</p>\n\n<p>CSS</p>\n\n<pre><code>body {\n height: 100%;\n margin: 0;\n padding: 0;\n}\n\n.header {\n height: 100px;\n background-color: red;\n}\n\n.content {\n height: 100%;\n background-color: green;\n}\n</code></pre>\n\n<p>JS</p>\n\n<pre><code>function resize() {\n // Get elements and necessary element heights\n var contentDiv = document.getElementById(\"contentId\");\n var headerDiv = document.getElementById(\"headerId\");\n var headerHeight = headerDiv.offsetHeight;\n\n // Get view height\n var viewportHeight = document.getElementsByTagName('body')[0].clientHeight;\n\n // Compute the content height - we want to fill the whole remaining area\n // in browser window\n contentDiv.style.height = viewportHeight - headerHeight;\n}\n\nwindow.onload = resize;\nwindow.onresize = resize;\n</code></pre>\n\n<p>HTML</p>\n\n<pre><code>&lt;body&gt;\n &lt;div class=\"header\" id=\"headerId\"&gt;Hello&lt;/div&gt;\n &lt;div class=\"content\" id=\"contentId\"&gt;&lt;/div&gt;\n&lt;/body&gt;\n</code></pre>\n" }, { "answer_id": 7794900, "author": "Tonye - True Vine Productions", "author_id": 999297, "author_profile": "https://Stackoverflow.com/users/999297", "pm_score": 5, "selected": false, "text": "<p>What worked for me (with a div within another div and I assume in all other circumstances) is to set the bottom padding to 100%. That is, add this to your css / stylesheet:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>padding-bottom: 100%;\n</code></pre>\n" }, { "answer_id": 7851347, "author": "h--n", "author_id": 375230, "author_profile": "https://Stackoverflow.com/users/375230", "pm_score": 8, "selected": false, "text": "<p>The original post is more than 3 years ago. I guess many people who come to this post like me are looking for an app-like layout solution, say a somehow fixed header, footer, and full height content taking up the rest screen. If so, this post may help, it works on IE7+, etc.</p>\n\n<p><a href=\"http://blog.stevensanderson.com/2011/10/05/full-height-app-layouts-a-css-trick-to-make-it-easier/\" rel=\"noreferrer\">http://blog.stevensanderson.com/2011/10/05/full-height-app-layouts-a-css-trick-to-make-it-easier/</a></p>\n\n<p>And here are some snippets from that post:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>@media screen { \r\n \r\n /* start of screen rules. */ \r\n \r\n /* Generic pane rules */\r\n body { margin: 0 }\r\n .row, .col { overflow: hidden; position: absolute; }\r\n .row { left: 0; right: 0; }\r\n .col { top: 0; bottom: 0; }\r\n .scroll-x { overflow-x: auto; }\r\n .scroll-y { overflow-y: auto; }\r\n\r\n .header.row { height: 75px; top: 0; }\r\n .body.row { top: 75px; bottom: 50px; }\r\n .footer.row { height: 50px; bottom: 0; }\r\n \r\n /* end of screen rules. */ \r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div class=\"header row\" style=\"background:yellow;\"&gt;\r\n &lt;h2&gt;My header&lt;/h2&gt;\r\n&lt;/div&gt; \r\n&lt;div class=\"body row scroll-y\" style=\"background:lightblue;\"&gt;\r\n &lt;p&gt;The body&lt;/p&gt;\r\n&lt;/div&gt; \r\n&lt;div class=\"footer row\" style=\"background:#e9e9e9;\"&gt;\r\n My footer\r\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 9358676, "author": "Thaoms", "author_id": 1220637, "author_profile": "https://Stackoverflow.com/users/1220637", "pm_score": 4, "selected": false, "text": "<p>Why not just like this?</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>html, body {\n height: 100%;\n}\n\n#containerInput {\n background-image: url('../img/edit_bg.jpg');\n height: 40%;\n}\n\n#containerControl {\n background-image: url('../img/control_bg.jpg');\n height: 60%;\n}\n</code></pre>\n\n<p>Giving you html and body (in that order) a height and then just give your elements a height?</p>\n\n<p>Works for me</p>\n" }, { "answer_id": 12420383, "author": "htho", "author_id": 1635906, "author_profile": "https://Stackoverflow.com/users/1635906", "pm_score": 2, "selected": false, "text": "<p>I found a quite simple solution, because for me it was just a design issue.\nI wanted the rest of the Page not to be white below the red footer.\nSo i set the pages background color to red. And the contents backgroundcolor to white.\nWith the contents height set to eg. 20em or 50% an almost empty page won't leave the whole page red. </p>\n" }, { "answer_id": 16251731, "author": "Arun", "author_id": 161633, "author_profile": "https://Stackoverflow.com/users/161633", "pm_score": 3, "selected": false, "text": "<p>Try this</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>var sizeFooter = function(){\n $(\".webfooter\")\n .css(\"padding-bottom\", \"0px\")\n .css(\"padding-bottom\", $(window).height() - $(\"body\").height())\n}\n$(window).resize(sizeFooter);\n</code></pre>\n" }, { "answer_id": 16357269, "author": "Mikko Rantalainen", "author_id": 334451, "author_profile": "https://Stackoverflow.com/users/334451", "pm_score": 5, "selected": false, "text": "<p>If you can deal with not supporting old browsers (that is, MSIE 9 or older), you can do this with <a href=\"http://caniuse.com/#feat=flexbox\" rel=\"noreferrer\">Flexible Box Layout Module</a> which is already W3C CR. That module allows other nice tricks, too, such as re-ordering content.</p>\n<p>Unfortunately, MSIE 9 or lesser do not support this and you have to use vendor prefix for the CSS property for every browser other than Firefox. Hopefully other vendors drop the prefix soon, too.</p>\n<p>An another choice would be <a href=\"http://caniuse.com/#search=grid\" rel=\"noreferrer\">CSS Grid Layout</a> but that has even less support from stable versions of browsers. In practice, only MSIE 10 supports this.</p>\n<p><strong>Update year 2020</strong>: All modern browsers support both <code>display: flex</code> and <code>display: grid</code>. The only one missing is support for <code>subgrid</code> which in only supported by Firefox. Note that MSIE does not support either by the spec but if you're willing to add MSIE specific CSS hacks, it can be made to behave. I would suggest simply ignoring MSIE because even Microsoft says it should not be used anymore. Microsoft Edge supports these features just fine (except for subgrid support since is shares the Blink rendering engine with Chrome).</p>\n<p><strong>Example using <code>display: grid</code>:</strong></p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>html, body\n{\n min-height: 100vh;\n padding: 0;\n margin: 0;\n}\n\nbody\n{\n display: grid;\n grid:\n \"myheader\" auto\n \"mymain\" minmax(0,1fr)\n \"myfooter\" auto /\n minmax(10rem, 90rem);\n}\n\nheader\n{\n grid-area: myheader;\n background: yellow;\n}\n\nmain\n{\n grid-area: mymain;\n background: pink;\n align-self: center\n /* or stretch\n + display: flex;\n + flex-direction: column;\n + justify-content: center; */\n}\n\nfooter\n{\n grid-area: myfooter;\n background: cyan;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;header&gt;Header content&lt;/header&gt;\n&lt;main&gt;Main content which should be centered and the content length may change.\n&lt;details&gt;&lt;summary&gt;Collapsible content&lt;/summary&gt;\n&lt;p&gt;Here's some text to cause more vertical space to be used.&lt;/p&gt;\n&lt;p&gt;Here's some text to cause more vertical space to be used (2).&lt;/p&gt;\n&lt;p&gt;Here's some text to cause more vertical space to be used (3).&lt;/p&gt;\n&lt;p&gt;Here's some text to cause more vertical space to be used (4).&lt;/p&gt;\n&lt;p&gt;Here's some text to cause more vertical space to be used (5).&lt;/p&gt;\n&lt;/details&gt;\n&lt;/main&gt;\n&lt;footer&gt;Footer content&lt;/footer&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p><strong>Example using <code>display: flex</code>:</strong></p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>html, body\n{\n min-height: 100vh;\n padding: 0;\n margin: 0;\n}\n\nbody\n{\n display: flex; \n}\n\nmain\n{\n background: pink;\n align-self: center;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;main&gt;Main content which should be centered and the content length may change.\n&lt;details&gt;&lt;summary&gt;Collapsible content&lt;/summary&gt;\n&lt;p&gt;Here's some text to cause more vertical space to be used.&lt;/p&gt;\n&lt;p&gt;Here's some text to cause more vertical space to be used (2).&lt;/p&gt;\n&lt;p&gt;Here's some text to cause more vertical space to be used (3).&lt;/p&gt;\n&lt;p&gt;Here's some text to cause more vertical space to be used (4).&lt;/p&gt;\n&lt;p&gt;Here's some text to cause more vertical space to be used (5).&lt;/p&gt;\n&lt;/details&gt;\n&lt;/main&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 16960823, "author": "Danield", "author_id": 703717, "author_profile": "https://Stackoverflow.com/users/703717", "pm_score": 7, "selected": false, "text": "<p>Instead of using tables in the markup, you could use CSS tables.</p>\n\n<h2>Markup</h2>\n\n<pre><code>&lt;body&gt; \n &lt;div&gt;hello &lt;/div&gt;\n &lt;div&gt;there&lt;/div&gt;\n&lt;/body&gt;\n</code></pre>\n\n<h2>(Relevant) CSS</h2>\n\n<pre><code>body\n{\n display:table;\n width:100%;\n}\ndiv\n{\n display:table-row;\n}\ndiv+ div\n{\n height:100%; \n}\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/danield770/FC7eY/\"><strong>FIDDLE1</strong></a> and <strong><a href=\"http://jsfiddle.net/danield770/FC7eY/1/\">FIDDLE2</a></strong></p>\n\n<p><strong>Some advantages of this method are:</strong></p>\n\n<p>1) Less markup</p>\n\n<p>2) Markup is more semantic than tables, because this is not tabular data.</p>\n\n<p>3) Browser support is <strong>very good</strong>: IE8+, All modern browsers and mobile devices (<a href=\"http://caniuse.com/css-table\">caniuse</a>) </p>\n\n<p><hr>\nJust for completeness, here are the equivalent Html elements to css properties for the <a href=\"http://www.w3.org/TR/CSS2/tables.html#table-display\">The CSS table model</a></p>\n\n<pre><code>table { display: table }\ntr { display: table-row }\nthead { display: table-header-group }\ntbody { display: table-row-group }\ntfoot { display: table-footer-group }\ncol { display: table-column }\ncolgroup { display: table-column-group }\ntd, th { display: table-cell }\ncaption { display: table-caption } \n</code></pre>\n" }, { "answer_id": 17496982, "author": "Greg", "author_id": 745250, "author_profile": "https://Stackoverflow.com/users/745250", "pm_score": 3, "selected": false, "text": "<p>You can actually use <code>display: table</code> to split the area into two elements (header and content), where the header can vary in height and the content fills the remaining space. This works with the whole page, as well as when the area is simply the content of another element positioned with <code>position</code> set to <code>relative</code>, <code>absolute</code> or <code>fixed</code>. It will work as long as the parent element has a non-zero height.</p>\n\n<p><a href=\"http://jsfiddle.net/amiramix/aD6gE/\" rel=\"noreferrer\">See this fiddle</a> and also the code below:</p>\n\n<p>CSS:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>body, html {\n height: 100%;\n margin: 0;\n padding: 0;\n}\n\np {\n margin: 0;\n padding: 0;\n}\n\n.additional-padding {\n height: 50px;\n background-color: #DE9;\n}\n\n.as-table {\n display: table;\n height: 100%;\n width: 100%;\n}\n\n.as-table-row {\n display: table-row;\n height: 100%;\n}\n\n#content {\n width: 100%;\n height: 100%;\n background-color: #33DD44;\n}\n</code></pre>\n\n<p>HTML:</p>\n\n<pre class=\"lang-html prettyprint-override\"><code>&lt;div class=\"as-table\"&gt;\n &lt;div id=\"header\"&gt;\n &lt;p&gt;This header can vary in height, it also doesn't have to be displayed as table-row. It will simply take the necessary space and the rest below will be taken by the second div which is displayed as table-row. Now adding some copy to artificially expand the header.&lt;/p&gt;\n &lt;div class=\"additional-padding\"&gt;&lt;/div&gt;\n &lt;/div&gt;\n &lt;div class=\"as-table-row\"&gt;\n &lt;div id=\"content\"&gt;\n &lt;p&gt;This is the actual content that takes the rest of the available space.&lt;/p&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n" }, { "answer_id": 23323175, "author": "Mr. Alien", "author_id": 1542290, "author_profile": "https://Stackoverflow.com/users/1542290", "pm_score": 7, "selected": false, "text": "<h2>CSS only Approach (If height is known/fixed)</h2>\n\n<p>When you want the middle element to span across entire page vertically, you can use <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/calc\" rel=\"noreferrer\"><code>calc()</code></a> which is introduced in CSS3.</p>\n\n<p>Assuming we have a <em>fixed height</em> <code>header</code> and <code>footer</code> elements and we want the <code>section</code> tag to take entire available vertical height...</p>\n\n<p><a href=\"http://jsfiddle.net/WdrDH/\" rel=\"noreferrer\"><strong>Demo</strong></a></p>\n\n<p><strong>Assumed markup</strong> and your CSS should be</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>html,\r\nbody {\r\n height: 100%;\r\n}\r\n\r\nheader {\r\n height: 100px;\r\n background: grey;\r\n}\r\n\r\nsection {\r\n height: calc(100% - (100px + 150px));\r\n /* Adding 100px of header and 150px of footer */\r\n background: tomato;\r\n}\r\n\r\nfooter {\r\n height: 150px;\r\n background-color: blue;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;header&gt;100px&lt;/header&gt;\r\n&lt;section&gt;Expand me for remaining space&lt;/section&gt;\r\n&lt;footer&gt;150px&lt;/footer&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>So here, what am doing is, adding up the height of elements and than deducting from <code>100%</code> using <code>calc()</code> function.</p>\n\n<p>Just make sure that you use <code>height: 100%;</code> for the parent elements.</p>\n" }, { "answer_id": 24979148, "author": "Pebbl", "author_id": 1490904, "author_profile": "https://Stackoverflow.com/users/1490904", "pm_score": 12, "selected": true, "text": "<h3>2015 update: the flexbox approach</h3>\n\n<p>There are two other answers briefly mentioning <a href=\"https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Flexible_boxes\" rel=\"noreferrer\">flexbox</a>; however, that was more than two years ago, and they don't provide any examples. The specification for flexbox has definitely settled now.</p>\n\n<blockquote>\n <p>Note: Though CSS Flexible Boxes Layout specification is at the Candidate Recommendation stage, not all browsers have implemented it. WebKit implementation must be prefixed with -webkit-; Internet Explorer implements an old version of the spec, prefixed with -ms-; Opera 12.10 implements the latest version of the spec, unprefixed. See the compatibility table on each property for an up-to-date compatibility status.</p>\n \n <p>(taken from <a href=\"https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Flexible_boxes\" rel=\"noreferrer\">https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Flexible_boxes</a>)</p>\n</blockquote>\n\n<p>All major browsers and IE11+ support Flexbox. For IE 10 or older, you can use the FlexieJS shim.</p>\n\n<p>To check current support you can also see here:\n<a href=\"http://caniuse.com/#feat=flexbox\" rel=\"noreferrer\">http://caniuse.com/#feat=flexbox</a></p>\n\n<h3>Working example</h3>\n\n<p>With flexbox you can easily switch between any of your rows or columns either having fixed dimensions, content-sized dimensions or remaining-space dimensions. In my example I have set the header to snap to its content (as per the OPs question), I've added a footer to show how to add a fixed-height region and then set the content area to fill up the remaining space.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>html,\r\nbody {\r\n height: 100%;\r\n margin: 0;\r\n}\r\n\r\n.box {\r\n display: flex;\r\n flex-flow: column;\r\n height: 100%;\r\n}\r\n\r\n.box .row {\r\n border: 1px dotted grey;\r\n}\r\n\r\n.box .row.header {\r\n flex: 0 1 auto;\r\n /* The above is shorthand for:\r\n flex-grow: 0,\r\n flex-shrink: 1,\r\n flex-basis: auto\r\n */\r\n}\r\n\r\n.box .row.content {\r\n flex: 1 1 auto;\r\n}\r\n\r\n.box .row.footer {\r\n flex: 0 1 40px;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;!-- Obviously, you could use HTML5 tags like `header`, `footer` and `section` --&gt;\r\n\r\n&lt;div class=\"box\"&gt;\r\n &lt;div class=\"row header\"&gt;\r\n &lt;p&gt;&lt;b&gt;header&lt;/b&gt;\r\n &lt;br /&gt;\r\n &lt;br /&gt;(sized to content)&lt;/p&gt;\r\n &lt;/div&gt;\r\n &lt;div class=\"row content\"&gt;\r\n &lt;p&gt;\r\n &lt;b&gt;content&lt;/b&gt;\r\n (fills remaining space)\r\n &lt;/p&gt;\r\n &lt;/div&gt;\r\n &lt;div class=\"row footer\"&gt;\r\n &lt;p&gt;&lt;b&gt;footer&lt;/b&gt; (fixed height)&lt;/p&gt;\r\n &lt;/div&gt;\r\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>In the CSS above, the <a href=\"https://developer.mozilla.org/en/CSS/flex\" rel=\"noreferrer\">flex</a> property shorthands the <a href=\"https://developer.mozilla.org/en/CSS/flex-grow\" rel=\"noreferrer\">flex-grow</a>, <a href=\"https://developer.mozilla.org/en/CSS/flex-shrink\" rel=\"noreferrer\">flex-shrink</a>, and <a href=\"https://developer.mozilla.org/en/CSS/flex-basis\" rel=\"noreferrer\">flex-basis</a> properties to establish the flexibility of the flex items. Mozilla has a <a href=\"https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Flexible_boxes\" rel=\"noreferrer\">good introduction to the flexible boxes model</a>.</p>\n" }, { "answer_id": 25838052, "author": "Ormoz", "author_id": 1600305, "author_profile": "https://Stackoverflow.com/users/1600305", "pm_score": 5, "selected": false, "text": "<p>It could be done purely by <code>CSS</code> using <code>vh</code>:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>#page {\n display:block; \n width:100%; \n height:95vh !important; \n overflow:hidden;\n}\n\n#tdcontent {\n float:left; \n width:100%; \n display:block;\n}\n\n#content { \n float:left; \n width:100%; \n height:100%; \n display:block; \n overflow:scroll;\n}\n</code></pre>\n\n<p>and the <code>HTML</code></p>\n\n<pre><code>&lt;div id=\"page\"&gt;\n\n &lt;div id=\"tdcontent\"&gt;&lt;/div&gt;\n &lt;div id=\"content\"&gt;&lt;/div&gt;\n\n&lt;/div&gt;\n</code></pre>\n\n<p>I checked it, It works in all major browsers: <code>Chrome</code>, <code>IE</code>, and <code>FireFox</code></p>\n" }, { "answer_id": 28634506, "author": "John Kurlak", "author_id": 55732, "author_profile": "https://Stackoverflow.com/users/55732", "pm_score": 5, "selected": false, "text": "<p>None of the solutions posted work when you need the bottom div to scroll when the content is too tall. Here's a solution that works in that case:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.table {\r\n display: table;\r\n}\r\n\r\n.table-row {\r\n display: table-row;\r\n}\r\n\r\n.table-cell {\r\n display: table-cell;\r\n}\r\n\r\n.container {\r\n width: 400px;\r\n height: 300px;\r\n}\r\n\r\n.header {\r\n background: cyan;\r\n}\r\n\r\n.body {\r\n background: yellow;\r\n height: 100%;\r\n}\r\n\r\n.body-content-outer-wrapper {\r\n height: 100%;\r\n}\r\n\r\n.body-content-inner-wrapper {\r\n height: 100%;\r\n position: relative;\r\n overflow: auto;\r\n}\r\n\r\n.body-content {\r\n position: absolute;\r\n top: 0;\r\n bottom: 0;\r\n left: 0;\r\n right: 0;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div class=\"table container\"&gt;\r\n &lt;div class=\"table-row header\"&gt;\r\n &lt;div&gt;This is the header whose height is unknown&lt;/div&gt;\r\n &lt;div&gt;This is the header whose height is unknown&lt;/div&gt;\r\n &lt;div&gt;This is the header whose height is unknown&lt;/div&gt;\r\n &lt;/div&gt;\r\n &lt;div class=\"table-row body\"&gt;\r\n &lt;div class=\"table-cell body-content-outer-wrapper\"&gt;\r\n &lt;div class=\"body-content-inner-wrapper\"&gt;\r\n &lt;div class=\"body-content\"&gt;\r\n &lt;div&gt;This is the scrollable content whose height is unknown&lt;/div&gt;\r\n &lt;div&gt;This is the scrollable content whose height is unknown&lt;/div&gt;\r\n &lt;div&gt;This is the scrollable content whose height is unknown&lt;/div&gt;\r\n &lt;div&gt;This is the scrollable content whose height is unknown&lt;/div&gt;\r\n &lt;div&gt;This is the scrollable content whose height is unknown&lt;/div&gt;\r\n &lt;div&gt;This is the scrollable content whose height is unknown&lt;/div&gt;\r\n &lt;div&gt;This is the scrollable content whose height is unknown&lt;/div&gt;\r\n &lt;div&gt;This is the scrollable content whose height is unknown&lt;/div&gt;\r\n &lt;div&gt;This is the scrollable content whose height is unknown&lt;/div&gt;\r\n &lt;div&gt;This is the scrollable content whose height is unknown&lt;/div&gt;\r\n &lt;div&gt;This is the scrollable content whose height is unknown&lt;/div&gt;\r\n &lt;div&gt;This is the scrollable content whose height is unknown&lt;/div&gt;\r\n &lt;div&gt;This is the scrollable content whose height is unknown&lt;/div&gt;\r\n &lt;div&gt;This is the scrollable content whose height is unknown&lt;/div&gt;\r\n &lt;div&gt;This is the scrollable content whose height is unknown&lt;/div&gt;\r\n &lt;div&gt;This is the scrollable content whose height is unknown&lt;/div&gt;\r\n &lt;div&gt;This is the scrollable content whose height is unknown&lt;/div&gt;\r\n &lt;div&gt;This is the scrollable content whose height is unknown&lt;/div&gt;\r\n &lt;/div&gt;\r\n &lt;/div&gt;\r\n &lt;/div&gt;\r\n &lt;/div&gt;\r\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p><a href=\"http://blogs.msdn.com/b/kurlak/archive/2015/02/20/filling-the-remaining-height-of-a-container-while-handling-overflow-in-css.aspx\" rel=\"noreferrer\">Original source: Filling the Remaining Height of a Container While Handling Overflow in CSS</a></p>\n\n<p><a href=\"http://jsfiddle.net/352ntoz2/\" rel=\"noreferrer\">JSFiddle live preview</a></p>\n" }, { "answer_id": 28771764, "author": "zok", "author_id": 795398, "author_profile": "https://Stackoverflow.com/users/795398", "pm_score": 6, "selected": false, "text": "<p>A simple solution, using flexbox:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>html,\r\nbody {\r\n height: 100%;\r\n}\r\n\r\nbody {\r\n display: flex;\r\n flex-direction: column;\r\n}\r\n\r\n.content {\r\n flex-grow: 1;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;body&gt;\r\n &lt;div&gt;header&lt;/div&gt;\r\n &lt;div class=\"content\"&gt;&lt;/div&gt;\r\n&lt;/body&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p><a href=\"http://codepen.io/isaacalves/pen/myKpVK\" rel=\"noreferrer\">Codepen sample</a></p>\n\n<p><a href=\"http://codepen.io/isaacalves/pen/MYXENq\" rel=\"noreferrer\">An alternate solution, with a div centered within the content div</a></p>\n" }, { "answer_id": 32182925, "author": "dev.meghraj", "author_id": 1435800, "author_profile": "https://Stackoverflow.com/users/1435800", "pm_score": 5, "selected": false, "text": "<p><strong>CSS3 Simple Way</strong></p>\n\n<pre><code>height: calc(100% - 10px); // 10px is height of your first div...\n</code></pre>\n\n<p>all major browsers these days support it, so go ahead if you don't have requirement to support vintage browsers.</p>\n" }, { "answer_id": 33439733, "author": "puiu", "author_id": 1727232, "author_profile": "https://Stackoverflow.com/users/1727232", "pm_score": 4, "selected": false, "text": "<p>There's a ton of answers now, but I found using <code>height: 100vh;</code> to work on the div element that needs to fill up the entire vertical space available.</p>\n\n<p>In this way, I do not need to play around with display or positioning. This came in handy when using Bootstrap to make a dashboard wherein I had a sidebar and a main. I wanted the main to stretch and fill the entire vertical space so that I could apply a background colour.</p>\n\n<pre><code>div {\n height: 100vh;\n}\n</code></pre>\n\n<p>Supports IE9 and up: <a href=\"http://caniuse.com/#feat=viewport-units\" rel=\"noreferrer\">click to see the link</a></p>\n" }, { "answer_id": 34579298, "author": "Michael P. Bazos", "author_id": 3120193, "author_profile": "https://Stackoverflow.com/users/3120193", "pm_score": 5, "selected": false, "text": "<blockquote>\n <p><em>Disclaimer: The accepted answer gives the idea of the solution, but I'm finding it a bit bloated with an unnecessary wrapper and css rules. Below is a solution with very few css rules.</em></p>\n</blockquote>\n\n<p><strong>HTML 5</strong></p>\n\n<pre><code>&lt;body&gt;\n &lt;header&gt;Header with an arbitrary height&lt;/header&gt;\n &lt;main&gt;\n This container will grow so as to take the remaining height\n &lt;/main&gt;\n&lt;/body&gt;\n</code></pre>\n\n<p><strong>CSS</strong></p>\n\n<pre><code>body {\n display: flex;\n flex-direction: column;\n min-height: 100vh; /* body takes whole viewport's height */\n}\n\nmain {\n flex: 1; /* this will make the container take the free space */\n}\n</code></pre>\n\n<p>Solution above uses <a href=\"http://caniuse.com/#feat=viewport-units\" rel=\"noreferrer\">viewport units</a> and <a href=\"http://caniuse.com/#feat=flexbox\" rel=\"noreferrer\">flexbox</a>, and is therefore IE10+, providing you use the old syntax for IE10.</p>\n\n<p><strong>Codepen to play with: <a href=\"http://codepen.io/michaelbazos/pen/mVRBXM\" rel=\"noreferrer\">link to codepen</a></strong></p>\n\n<p><strong>Or this one, for those needing the main container to be scrollable in case of overflowing content: <a href=\"http://codepen.io/michaelbazos/pen/pgRWVG\" rel=\"noreferrer\">link to codepen</a></strong></p>\n" }, { "answer_id": 37370197, "author": "nguyên", "author_id": 572180, "author_profile": "https://Stackoverflow.com/users/572180", "pm_score": 6, "selected": false, "text": "<p>Used: \n<code>height: calc(100vh - 110px);</code></p>\n\n<p>code: \n<div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code> \r\n.header { height: 60px; top: 0; background-color: green}\r\n.body {\r\n height: calc(100vh - 110px); /*50+60*/\r\n background-color: gray;\r\n}\r\n.footer { height: 50px; bottom: 0; }\r\n </code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div class=\"header\"&gt;\r\n &lt;h2&gt;My header&lt;/h2&gt;\r\n&lt;/div&gt; \r\n&lt;div class=\"body\"&gt;\r\n &lt;p&gt;The body&lt;/p&gt;\r\n&lt;/div&gt; \r\n&lt;div class=\"footer\"&gt;\r\n My footer\r\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 38153735, "author": "Pat M", "author_id": 4155124, "author_profile": "https://Stackoverflow.com/users/4155124", "pm_score": 3, "selected": false, "text": "<p>Spinning off the idea of Mr. Alien...</p>\n\n<p>This seems a cleaner solution than the popular flex box one for CSS3 enabled browsers.</p>\n\n<p>Simply use min-height(instead of height) with calc() to the content block. </p>\n\n<p>The calc() starts with 100% and subtracts heights of headers and footers (need to include padding values)</p>\n\n<p>Using \"min-height\" instead of \"height\" is particularly useful so it can work with javascript rendered content and JS frameworks like Angular2. Otherwise, the calculation will not push the footer to the bottom of the page once the javascript rendered content is visible.</p>\n\n<p>Here is a simple example of a header and footer using 50px height and 20px padding for both.</p>\n\n<p>Html:</p>\n\n<pre><code>&lt;body&gt;\n &lt;header&gt;&lt;/header&gt;\n &lt;div class=\"content\"&gt;&lt;/div&gt;\n &lt;footer&gt;&lt;/footer&gt;\n&lt;/body&gt;\n</code></pre>\n\n<p>Css:</p>\n\n<pre><code>.content {\n min-height: calc(100% - (50px + 20px + 20px + 50px + 20px + 20px));\n}\n</code></pre>\n\n<p>Of course, the math can be simplified but you get the idea...</p>\n" }, { "answer_id": 39150121, "author": "Anthony Brenelière", "author_id": 3433751, "author_profile": "https://Stackoverflow.com/users/3433751", "pm_score": 3, "selected": false, "text": "<p>I had the same problem but I could not make work the solution with flexboxes above. So I created my own template, that includes:</p>\n\n<ul>\n<li>a header with a fixed size element</li>\n<li>a footer</li>\n<li>a side bar with a scrollbar that occupies the remaining height</li>\n<li>content</li>\n</ul>\n\n<p>I used flexboxes but in a more simple way, using only properties <strong>display: flex</strong> and <strong>flex-direction: row|column</strong>:</p>\n\n<p>I do use angular and I want my component sizes to be 100% of their parent element.</p>\n\n<p>The key is to set the size (in percents) for all parents inorder to limit their size. In the following example myapp height has 100% of the viewport.</p>\n\n<p>The main component has 90% of the viewport, because header and footer have 5%.</p>\n\n<p>I posted my template here: <a href=\"https://jsfiddle.net/abreneliere/mrjh6y2e/3\" rel=\"noreferrer\">https://jsfiddle.net/abreneliere/mrjh6y2e/3</a></p>\n\n<pre><code> body{\n margin: 0;\n color: white;\n height: 100%;\n }\n div#myapp\n {\n display: flex;\n flex-direction: column;\n background-color: red; /* &lt;-- painful color for your eyes ! */\n height: 100%; /* &lt;-- if you remove this line, myapp has no limited height */\n }\n div#main /* parent div for sidebar and content */\n {\n display: flex;\n width: 100%;\n height: 90%; \n }\n div#header {\n background-color: #333;\n height: 5%;\n }\n div#footer {\n background-color: #222;\n height: 5%;\n }\n div#sidebar {\n background-color: #666;\n width: 20%;\n overflow-y: auto;\n }\n div#content {\n background-color: #888;\n width: 80%;\n overflow-y: auto;\n }\n div.fized_size_element {\n background-color: #AAA;\n display: block;\n width: 100px;\n height: 50px;\n margin: 5px;\n }\n</code></pre>\n\n<p>Html:</p>\n\n<pre><code>&lt;body&gt;\n&lt;div id=\"myapp\"&gt;\n &lt;div id=\"header\"&gt;\n HEADER\n &lt;div class=\"fized_size_element\"&gt;&lt;/div&gt;\n\n &lt;/div&gt;\n &lt;div id=\"main\"&gt;\n &lt;div id=\"sidebar\"&gt;\n SIDEBAR\n &lt;div class=\"fized_size_element\"&gt;&lt;/div&gt;\n &lt;div class=\"fized_size_element\"&gt;&lt;/div&gt;\n &lt;div class=\"fized_size_element\"&gt;&lt;/div&gt;\n &lt;div class=\"fized_size_element\"&gt;&lt;/div&gt;\n &lt;div class=\"fized_size_element\"&gt;&lt;/div&gt;\n &lt;div class=\"fized_size_element\"&gt;&lt;/div&gt;\n &lt;div class=\"fized_size_element\"&gt;&lt;/div&gt;\n &lt;div class=\"fized_size_element\"&gt;&lt;/div&gt;\n &lt;/div&gt;\n &lt;div id=\"content\"&gt;\n CONTENT\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;div id=\"footer\"&gt;\n FOOTER\n &lt;/div&gt;\n&lt;/div&gt;\n&lt;/body&gt;\n</code></pre>\n" }, { "answer_id": 40011321, "author": "James Yang", "author_id": 4612829, "author_profile": "https://Stackoverflow.com/users/4612829", "pm_score": 0, "selected": false, "text": "<p>It's dynamic calc the remining screen space, better using Javascript.</p>\n\n<p>You can use CSS-IN-JS technology, like below lib:</p>\n\n<p><a href=\"https://github.com/cssobj/cssobj\" rel=\"nofollow\">https://github.com/cssobj/cssobj</a></p>\n\n<p>DEMO: <a href=\"https://cssobj.github.io/cssobj-demo/\" rel=\"nofollow\">https://cssobj.github.io/cssobj-demo/</a></p>\n" }, { "answer_id": 41984205, "author": "grinmax", "author_id": 7309671, "author_profile": "https://Stackoverflow.com/users/7309671", "pm_score": 3, "selected": false, "text": "<p>For mobile app i use only VH and VW</p>\n<pre class=\"lang-html prettyprint-override\"><code>&lt;div class=&quot;container&quot;&gt;\n &lt;div class=&quot;title&quot;&gt;Title&lt;/div&gt;\n &lt;div class=&quot;content&quot;&gt;Content&lt;/div&gt;\n &lt;div class=&quot;footer&quot;&gt;Footer&lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n<pre class=\"lang-css prettyprint-override\"><code>.container {\n width: 100vw;\n height: 100vh;\n font-size: 5vh;\n}\n \n.title {\n height: 20vh;\n background-color: red;\n}\n \n.content {\n height: 60vh;\n background: blue;\n}\n \n.footer {\n height: 20vh;\n background: green;\n}\n</code></pre>\n<p>Demo - <a href=\"https://jsfiddle.net/u763ck92/\" rel=\"nofollow noreferrer\">https://jsfiddle.net/u763ck92/</a></p>\n" }, { "answer_id": 44607939, "author": "Alireza", "author_id": 5423108, "author_profile": "https://Stackoverflow.com/users/5423108", "pm_score": 6, "selected": false, "text": "<p>How about you simply use <code>vh</code> which stands for <code>view height</code> in <strong>CSS</strong>...</p>\n\n<p>Look at the <strong>code snippet</strong> I created for you below and run it:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>body {\r\n padding: 0;\r\n margin: 0;\r\n}\r\n\r\n.full-height {\r\n width: 100px;\r\n height: 100vh;\r\n background: red;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div class=\"full-height\"&gt;\r\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Also, look at the image below which I created for you:</p>\n\n<p><a href=\"https://i.stack.imgur.com/Oy7mP.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/Oy7mP.jpg\" alt=\"Make a div fill the height of the remaining screen space\"></a></p>\n" }, { "answer_id": 44908512, "author": "Paulie_D", "author_id": 2802040, "author_profile": "https://Stackoverflow.com/users/2802040", "pm_score": 4, "selected": false, "text": "<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout\" rel=\"noreferrer\"><strong>CSS Grid Solution</strong></a></p>\n\n<p>Just defining the <code>body</code> with <code>display:grid</code> and the <code>grid-template-rows</code> using <code>auto</code> and the <code>fr</code> value property.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>* {\r\n margin: 0;\r\n padding: 0;\r\n}\r\n\r\nhtml {\r\n height: 100%;\r\n}\r\n\r\nbody {\r\n min-height: 100%;\r\n display: grid;\r\n grid-template-rows: auto 1fr auto;\r\n}\r\n\r\nheader {\r\n padding: 1em;\r\n background: pink;\r\n}\r\n\r\nmain {\r\n padding: 1em;\r\n background: lightblue;\r\n}\r\n\r\nfooter {\r\n padding: 2em;\r\n background: lightgreen;\r\n}\r\n\r\nmain:hover {\r\n height: 2000px;\r\n /* demos expansion of center element */\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;header&gt;HEADER&lt;/header&gt;\r\n&lt;main&gt;MAIN&lt;/main&gt;\r\n&lt;footer&gt;FOOTER&lt;/footer&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p><a href=\"https://css-tricks.com/snippets/css/complete-guide-grid/\" rel=\"noreferrer\"><strong>A Complete Guide to Grids @ CSS-Tricks.com</strong></a></p>\n" }, { "answer_id": 49447848, "author": "Zohab Ali", "author_id": 5361964, "author_profile": "https://Stackoverflow.com/users/5361964", "pm_score": 3, "selected": false, "text": "<pre><code> style=\"height:100vh\"\n</code></pre>\n\n<p>solved the problem for me. In my case I applied this to the required div</p>\n" }, { "answer_id": 60403264, "author": "gadolf", "author_id": 5889767, "author_profile": "https://Stackoverflow.com/users/5889767", "pm_score": 5, "selected": false, "text": "<p><strong>In Bootstrap:</strong></p>\n<p>CSS Styles:</p>\n<pre><code>html, body {\n height: 100%;\n}\n</code></pre>\n<hr />\n<p><em>1) Just fill the height of the remaining screen space:</em></p>\n<pre><code>&lt;body class=&quot;d-flex flex-column&quot;&gt;\n &lt;div class=&quot;d-flex flex-column flex-grow-1&quot;&gt;\n\n &lt;header&gt;Header&lt;/header&gt;\n &lt;div&gt;Content&lt;/div&gt;\n &lt;footer class=&quot;mt-auto&quot;&gt;Footer&lt;/footer&gt;\n\n &lt;/div&gt;\n&lt;/body&gt;\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/3vE98m.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/3vE98m.png\" alt=\"![enter image description here\" /></a></p>\n<hr />\n<p><em>2) fill the height of the remaining screen space and aligning content to the middle of the parent element:</em></p>\n<pre><code>&lt;body class=&quot;d-flex flex-column&quot;&gt;\n &lt;div class=&quot;d-flex flex-column flex-grow-1&quot;&gt;\n\n &lt;header&gt;Header&lt;/header&gt;\n &lt;div class=&quot;d-flex flex-column flex-grow-1 justify-content-center&quot;&gt;Content&lt;/div&gt;\n &lt;footer class=&quot;mt-auto&quot;&gt;Footer&lt;/footer&gt;\n\n &lt;/div&gt;\n&lt;/body&gt;\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/P9o0fm.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/P9o0fm.png\" alt=\"![enter image description here\" /></a></p>\n" }, { "answer_id": 61217322, "author": "Michael Schade", "author_id": 1236252, "author_profile": "https://Stackoverflow.com/users/1236252", "pm_score": 4, "selected": false, "text": "<p>This is my own minimal version of Pebbl's solution. Took forever to find the trick to get it to work in IE11. (Also tested in Chrome, Firefox, Edge, and Safari.)</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>html {\n height: 100%;\n}\n\nbody {\n height: 100%;\n margin: 0;\n}\n\nsection {\n display: flex;\n flex-direction: column;\n height: 100%;\n}\n\ndiv:first-child {\n background: gold;\n}\n\ndiv:last-child {\n background: plum;\n flex-grow: 1;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;body&gt;\n &lt;section&gt;\n &lt;div&gt;FIT&lt;/div&gt;\n &lt;div&gt;GROW&lt;/div&gt;\n &lt;/section&gt;\n&lt;/body&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 64374418, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>One more solution using <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout\" rel=\"nofollow noreferrer\">CSS Grid</a></p>\n<p>Define grid</p>\n<pre><code>.root {\n display: grid;\n grid-template-rows: minmax(60px, auto) minmax(0, 100%);\n}\n</code></pre>\n<p>First row(header): Min height can be set-up and max height will depend on content.\nSecond row(content) will try to fit free space that left after header.</p>\n<p>The advantage of this approach is content can be scrolled independently of header, so header is always at the top of the page</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>body, html {\n margin: 0;\n height: 100%;\n}\n\n.root {\n display: grid;\n grid-template-rows: minmax(60px, auto) minmax(0, 100%);\n height: 100%;\n}\n\n.header {\n background-color: lightblue;\n}\n\nbutton {\n background-color: darkslateblue;\n color: white;\n padding: 10px 50px;\n margin: 10px 30px;\n border-radius: 15px;\n border: none;\n}\n\n.content {\n background-color: antiquewhite;\n overflow: auto;\n}\n\n.block {\n width: calc(100% - 20px);\n height: 120px;\n border: solid aquamarine;\n margin: 10px;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div class=\"root\"&gt;\n &lt;div class=\"header\"&gt;\n &lt;button&gt;click&lt;/button&gt;\n &lt;button&gt;click&lt;/button&gt;\n &lt;button&gt;click&lt;/button&gt;\n &lt;button&gt;click&lt;/button&gt;\n &lt;button&gt;click&lt;/button&gt;\n &lt;/div&gt;\n &lt;div class=\"content\"&gt;\n &lt;div class=\"block\"&gt;&lt;/div&gt;\n &lt;div class=\"block\"&gt;&lt;/div&gt;\n &lt;div class=\"block\"&gt;&lt;/div&gt;\n &lt;div class=\"block\"&gt;&lt;/div&gt;\n &lt;div class=\"block\"&gt;&lt;/div&gt;\n &lt;div class=\"block\"&gt;&lt;/div&gt;\n &lt;div class=\"block\"&gt;&lt;/div&gt;\n &lt;div class=\"block\"&gt;&lt;/div&gt;\n&lt;/div&gt;\n &lt;div class=\"footer\"&gt;&lt;/div&gt;\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 66466661, "author": "Chukwuemeka Maduekwe", "author_id": 12490386, "author_profile": "https://Stackoverflow.com/users/12490386", "pm_score": -1, "selected": false, "text": "<p>All you have to do if you're using display: flex on the parent div is to simply set height to stretch or fill like so</p>\n<pre><code>.divName {\n height: stretch\n}\n</code></pre>\n" }, { "answer_id": 66524544, "author": "Just a coder", "author_id": 433073, "author_profile": "https://Stackoverflow.com/users/433073", "pm_score": 2, "selected": false, "text": "<p>Here is an answer that uses grids.</p>\n<pre class=\"lang-css prettyprint-override\"><code>.the-container-div {\n display: grid;\n grid-template-columns: 1fr;\n grid-template-rows: auto min-content;\n height: 100vh;\n}\n.view-to-remain-small {\n grid-row: 2;\n}\n\n.view-to-be-stretched {\n grid-row: 1\n}\n</code></pre>\n" }, { "answer_id": 69921961, "author": "Chong Lip Phang", "author_id": 2435020, "author_profile": "https://Stackoverflow.com/users/2435020", "pm_score": 0, "selected": false, "text": "<p>Some of my components were loaded dynamically, and this caused me problems with setting the height of the navigation bar.</p>\n<p>What I did was to use <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Resize_Observer_API\" rel=\"nofollow noreferrer\">the ResizeObserver API</a>.</p>\n<pre><code>function observeMainResize(){\n const resizeObserver = new ResizeObserver(entries =&gt; {\n for (let entry of entries) {\n $(&quot;nav&quot;).height(Math.max($(&quot;main&quot;).height(),\n $(&quot;nav&quot;) .height()));\n }\n });\n resizeObserver.observe(document.querySelector('main'));\n}\n</code></pre>\n<p>then:</p>\n<pre><code>...\n&lt;body onload=&quot;observeMainResize()&quot;&gt;\n &lt;nav&gt;...&lt;/nav&gt;\n &lt;main&gt;...&lt;/main&gt;\n...\n</code></pre>\n" }, { "answer_id": 71203452, "author": "yoty66", "author_id": 12624118, "author_profile": "https://Stackoverflow.com/users/12624118", "pm_score": 1, "selected": false, "text": "<p>A nice hack would be to set the css margin property to &quot;auto&quot;.\nIt will make the div take up all the remaining height &amp; width .</p>\n<p>The downside is that it would be computed as margin and not the content .</p>\n<p>See attached screenshots:</p>\n<p><a href=\"https://i.stack.imgur.com/jLDC2.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/jLDC2.png\" alt=\"before1\" /></a>\n<a href=\"https://i.stack.imgur.com/hoFa7.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/hoFa7.png\" alt=\"before2\" /></a></p>\n<p><a href=\"https://i.stack.imgur.com/SulwP.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/SulwP.png\" alt=\"after1\" /></a></p>\n<p><a href=\"https://i.stack.imgur.com/tw7n7.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/tw7n7.png\" alt=\"after2\" /></a></p>\n" }, { "answer_id": 73698597, "author": "Chong Lip Phang", "author_id": 2435020, "author_profile": "https://Stackoverflow.com/users/2435020", "pm_score": -1, "selected": false, "text": "<p>Consider setting all the 'position's to 'fixed', and then using {top:0; bottom:0;}</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;!DOCTYPE html&gt;\n&lt;html&gt;&lt;head&gt;\n&lt;style&gt;\n#B {\n position:fixed;\n width: 100%;\n height: 100%;\n background-color: orange;\n}\n#B1 {\n position:fixed;\n top:0;\n bottom: 0;\n width: 100%;\n background-color: cyan; \n}\n#B2 {\n position:fixed;\n bottom: 0;\n height: 35px;\n width: 100%;\n background: green;\n}\n\n}&lt;/style&gt;&lt;/head&gt;\n&lt;body&gt;\n &lt;div id=\"B1\"&gt;B1&lt;/div&gt;\n &lt;div id=\"B2\"&gt;B2&lt;/div&gt;\n&lt;/body&gt;\n&lt;/html&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Note that there is some overlapping, so be careful.</p>\n<p>If you want to vertically occupy the available space of a parent &lt; div&gt;, use absolute positioning instead.</p>\n" }, { "answer_id": 74196906, "author": "yongrui", "author_id": 2079846, "author_profile": "https://Stackoverflow.com/users/2079846", "pm_score": -1, "selected": false, "text": "<p>height: calc(100% - 650px);\nposition: absolute;</p>\n" }, { "answer_id": 74304362, "author": "Nyi Nyi Hmue Aung", "author_id": 15247669, "author_profile": "https://Stackoverflow.com/users/15247669", "pm_score": 1, "selected": false, "text": "<p>For me the easiest way to do this is by using Grid. But, I am looking for an easier approach. Here is How I am doing it and it works. But, it becomes too much of pain if we have a lot of nested divs.</p>\n<pre><code> &lt;div style={{\n display:grid,\n gridTemplateRows:'max-content 1fr',\n}}&gt;\n &lt;div&gt;\n Header\n &lt;/div&gt;\n &lt;div style={{height:'100%',minHeight:'0'}}&gt;\n Content\n &lt;/div&gt;\n &lt;/div&gt;\n\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/797/" ]
I've just run into a display glitch in IE6 with the ExtJS framework. - Hopefully someone can point me in the right direction. In the following example, the bbar for the panel is displayed 2ems narrower than the panel it is attached to (it's left aligned) in IE6, where as in Firefox it is displayed as the same width as the panel. Can anyone suggest how to fix this? I seem to be able to work around either by specifying the width of the panel in ems or the padding in pixels, but I assume it would be expected to work as I have it below. ``` <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <link rel="stylesheet" type="text/css" href="ext/resources/css/ext-all.css"/> <script type="text/javascript" src="ext/ext-base.js"></script> <script type="text/javascript" src="ext/ext-all-debug.js"></script> <script type="text/javascript"> Ext.onReady(function(){ var main = new Ext.Panel({ renderTo: 'content', bodyStyle: 'padding: 1em;', width: 500, html: "Alignment issue in IE - The bbar's width is 2ems less than the main panel in IE6.", bbar: [ "->", {id: "continue", text: 'Continue'} ] }); }); </script> </head> <body> <div id="content"></div> </body> </html> ```
### 2015 update: the flexbox approach There are two other answers briefly mentioning [flexbox](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Flexible_boxes); however, that was more than two years ago, and they don't provide any examples. The specification for flexbox has definitely settled now. > > Note: Though CSS Flexible Boxes Layout specification is at the Candidate Recommendation stage, not all browsers have implemented it. WebKit implementation must be prefixed with -webkit-; Internet Explorer implements an old version of the spec, prefixed with -ms-; Opera 12.10 implements the latest version of the spec, unprefixed. See the compatibility table on each property for an up-to-date compatibility status. > > > (taken from <https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Flexible_boxes>) > > > All major browsers and IE11+ support Flexbox. For IE 10 or older, you can use the FlexieJS shim. To check current support you can also see here: <http://caniuse.com/#feat=flexbox> ### Working example With flexbox you can easily switch between any of your rows or columns either having fixed dimensions, content-sized dimensions or remaining-space dimensions. In my example I have set the header to snap to its content (as per the OPs question), I've added a footer to show how to add a fixed-height region and then set the content area to fill up the remaining space. ```css html, body { height: 100%; margin: 0; } .box { display: flex; flex-flow: column; height: 100%; } .box .row { border: 1px dotted grey; } .box .row.header { flex: 0 1 auto; /* The above is shorthand for: flex-grow: 0, flex-shrink: 1, flex-basis: auto */ } .box .row.content { flex: 1 1 auto; } .box .row.footer { flex: 0 1 40px; } ``` ```html <!-- Obviously, you could use HTML5 tags like `header`, `footer` and `section` --> <div class="box"> <div class="row header"> <p><b>header</b> <br /> <br />(sized to content)</p> </div> <div class="row content"> <p> <b>content</b> (fills remaining space) </p> </div> <div class="row footer"> <p><b>footer</b> (fixed height)</p> </div> </div> ``` In the CSS above, the [flex](https://developer.mozilla.org/en/CSS/flex) property shorthands the [flex-grow](https://developer.mozilla.org/en/CSS/flex-grow), [flex-shrink](https://developer.mozilla.org/en/CSS/flex-shrink), and [flex-basis](https://developer.mozilla.org/en/CSS/flex-basis) properties to establish the flexibility of the flex items. Mozilla has a [good introduction to the flexible boxes model](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Flexible_boxes).
90,238
<p>As an example in pseudocode:</p> <pre><code>if ((a mod 2) == 0) { isEven = true; } else { isEven = false; } </code></pre>
[ { "answer_id": 90242, "author": "martinatime", "author_id": 1353, "author_profile": "https://Stackoverflow.com/users/1353", "pm_score": 7, "selected": false, "text": "<p>Here is the representation of your pseudo-code in minimal Java code;</p>\n\n<pre><code>boolean isEven = a % 2 == 0;\n</code></pre>\n\n<p>I'll now break it down into its components. The modulus operator in Java is the percent character (%). Therefore taking an int % int returns another int. The double equals (==) operator is used to compare values, such as a pair of ints and returns a boolean. This is then assigned to the boolean variable 'isEven'. Based on operator precedence the modulus will be evaluated before the comparison.</p>\n" }, { "answer_id": 90243, "author": "jjrv", "author_id": 16509, "author_profile": "https://Stackoverflow.com/users/16509", "pm_score": -1, "selected": false, "text": "<p>The modulo operator is % (percent sign). To test for evenness or generally do modulo for a power of 2, you can also use &amp; (the and operator) like isEven = !( a &amp; 1 ).</p>\n" }, { "answer_id": 90244, "author": "J D OConal", "author_id": 17023, "author_profile": "https://Stackoverflow.com/users/17023", "pm_score": 3, "selected": false, "text": "<pre><code>if (a % 2 == 0) {\n} else {\n}\n</code></pre>\n" }, { "answer_id": 90247, "author": "Cody Hatch", "author_id": 17086, "author_profile": "https://Stackoverflow.com/users/17086", "pm_score": 10, "selected": true, "text": "<p>Instead of the modulo operator, which has slightly different semantics, for non-negative integers, you can use the <em>remainder</em> operator <code>%</code>. For your exact example:</p>\n\n<pre><code>if ((a % 2) == 0)\n{\n isEven = true;\n}\nelse\n{\n isEven = false;\n}\n</code></pre>\n\n<p>This can be simplified to a one-liner:</p>\n\n<pre><code>isEven = (a % 2) == 0;\n</code></pre>\n" }, { "answer_id": 90249, "author": "jjnguy", "author_id": 2598, "author_profile": "https://Stackoverflow.com/users/2598", "pm_score": 2, "selected": false, "text": "<p>Also, mod can be used like this:</p>\n\n<pre><code>int a = 7;\nb = a % 2;\n</code></pre>\n\n<p><code>b</code> would equal 1. Because <code>7 % 2 = 1</code>.</p>\n" }, { "answer_id": 95946, "author": "Jay Bazuzi", "author_id": 5314, "author_profile": "https://Stackoverflow.com/users/5314", "pm_score": -1, "selected": false, "text": "<p>An alternative to the code from @Cody: </p>\n\n<p>Using the modulus operator:</p>\n\n<pre><code>bool isEven = (a % 2) == 0;\n</code></pre>\n\n<p>I think this is marginally better code than writing if/else, because there is less duplication &amp; unused flexibility. It does require a bit more brain power to examine, but the good naming of <code>isEven</code> compensates.</p>\n" }, { "answer_id": 2073707, "author": "Greg Charles", "author_id": 175142, "author_profile": "https://Stackoverflow.com/users/175142", "pm_score": 4, "selected": false, "text": "<p>Java actually has no modulo operator the way C does. % in Java is a remainder operator. On positive integers, it works exactly like modulo, but it works differently on negative integers and, unlike modulo, can work with floating point numbers as well. Still, it's rare to use % on anything but positive integers, so if you want to call it a modulo, then feel free! </p>\n" }, { "answer_id": 2073758, "author": "Rob Rolnick", "author_id": 4798, "author_profile": "https://Stackoverflow.com/users/4798", "pm_score": 7, "selected": false, "text": "<p>Since everyone else already gave the answer, I'll add a bit of additional context. % the \"modulus\" operator is actually performing the remainder operation. The difference between mod and rem is subtle, but important.</p>\n\n<p>(-1 mod 2) would normally give 1. More specifically given two integers, X and Y, the operation (X mod Y) tends to return a value in the range [0, Y). Said differently, the modulus of X and Y is always greater than or equal to zero, and less than Y.</p>\n\n<p>Performing the same operation with the \"%\" or rem operator maintains the sign of the X value. If X is negative you get a result in the range (-Y, 0]. If X is positive you get a result in the range [0, Y). </p>\n\n<p>Often this subtle distinction doesn't matter. Going back to your code question, though, there are multiple ways of solving for \"evenness\".</p>\n\n<p>The first approach is good for beginners, because it is especially verbose.</p>\n\n<pre><code>// Option 1: Clearest way for beginners\nboolean isEven;\nif ((a % 2) == 0)\n{\n isEven = true\n}\nelse\n{\n isEven = false\n}\n</code></pre>\n\n<p>The second approach takes better advantage of the language, and leads to more succinct code. (Don't forget that the == operator returns a boolean.)</p>\n\n<pre><code>// Option 2: Clear, succinct, code\nboolean isEven = ((a % 2) == 0);\n</code></pre>\n\n<p>The third approach is here for completeness, and uses the <a href=\"http://java.sun.com/docs/books/tutorial/java/nutsandbolts/op2.html\" rel=\"noreferrer\">ternary</a> operator. Although the ternary operator is often very useful, in this case I consider the second approach superior.</p>\n\n<pre><code>// Option 3: Ternary operator\nboolean isEven = ((a % 2) == 0) ? true : false;\n</code></pre>\n\n<p>The fourth and final approach is to use knowledge of the <a href=\"http://en.wikipedia.org/wiki/Two&#39;s_complement\" rel=\"noreferrer\">binary representation of integers</a>. If the least significant bit is 0 then the number is even. This can be checked using the <a href=\"http://java.sun.com/docs/books/tutorial/java/nutsandbolts/op3.html\" rel=\"noreferrer\">bitwise-and operator</a> (&amp;). While this approach is the fastest (you are doing simple bit masking instead of division), it is perhaps a little advanced/complicated for a beginner.</p>\n\n<pre><code>// Option 4: Bitwise-and\nboolean isEven = ((a &amp; 1) == 0);\n</code></pre>\n\n<p>Here I used the bitwise-and operator, and represented it in the succinct form shown in option 2. Rewriting it in Option 1's form (and alternatively Option 3's) is left as an exercise to the reader. ;)</p>\n\n<p>Hope that helps.</p>\n" }, { "answer_id": 2172061, "author": "Zom-B", "author_id": 262928, "author_profile": "https://Stackoverflow.com/users/262928", "pm_score": 5, "selected": false, "text": "<p>To get Java's % (REM) operation to work like MOD for negative X and positive Y values, you can use this method:</p>\n\n<pre><code>private int mod(int x, int y)\n{\n int result = x % y;\n if (result &lt; 0)\n {\n result += y;\n }\n return result;\n}\n</code></pre>\n\n<p>or with the ternary operator (shorter, but not possible or less efficient in some situations):</p>\n\n<pre><code>private int mod(int x, int y)\n{\n int result = x % y;\n return result &lt; 0? result + y : result;\n}\n</code></pre>\n" }, { "answer_id": 3354251, "author": "eljenso", "author_id": 30316, "author_profile": "https://Stackoverflow.com/users/30316", "pm_score": 2, "selected": false, "text": "<p>The remainder operator in Java is <code>%</code> and the modulo operator can be expressed as</p>\n\n<pre><code>public int mod(int i, int j)\n{\n int rem = i % j;\n if (j &lt; 0 &amp;&amp; rem &gt; 0)\n {\n return rem + j;\n }\n if (j &gt; 0 &amp;&amp; rem &lt; 0)\n {\n return rem + j;\n }\n return rem;\n}\n</code></pre>\n" }, { "answer_id": 3917066, "author": "michael", "author_id": 473599, "author_profile": "https://Stackoverflow.com/users/473599", "pm_score": 4, "selected": false, "text": "<p>The code runs much faster without using modulo:</p>\n\n<pre><code>public boolean isEven(int a){\n return ( (a &amp; 1) == 0 );\n}\n\npublic boolean isOdd(int a){\n return ( (a &amp; 1) == 1 );\n}\n</code></pre>\n" }, { "answer_id": 4725976, "author": "kioto", "author_id": 578557, "author_profile": "https://Stackoverflow.com/users/578557", "pm_score": 2, "selected": false, "text": "<p>you should examine the specification before using 'remainder' operator % :</p>\n\n<p><a href=\"http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.17.3\" rel=\"nofollow\">http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.17.3</a></p>\n\n<pre><code>// bad enough implementation of isEven method, for fun. so any worse?\nboolean isEven(int num)\n{\n num %= 10;\n if(num == 1)\n return false;\n else if(num == 0)\n return true;\n else\n return isEven(num + 2);\n}\nisEven = isEven(a);\n</code></pre>\n" }, { "answer_id": 18935194, "author": "Stefan T", "author_id": 2802543, "author_profile": "https://Stackoverflow.com/users/2802543", "pm_score": 4, "selected": false, "text": "<p>While it's possible to do a proper modulo by checking whether the value is negative and correct it if it is (the way many have suggested), there is a more compact solution.</p>\n\n<pre><code>(a % b + b) % b\n</code></pre>\n\n<p>This will first do the modulo, limiting the value to the -b -> +b range and then add b in order to ensure that the value is positive, letting the next modulo limit it to the 0 -> b range.</p>\n\n<p>Note: If b is negative, the result will also be negative</p>\n" }, { "answer_id": 23610743, "author": "brothers28", "author_id": 3122309, "author_profile": "https://Stackoverflow.com/users/3122309", "pm_score": 1, "selected": false, "text": "<p>Another way is:</p>\n\n<pre><code>boolean isEven = false;\nif((a % 2) == 0)\n{\n isEven = true;\n}\n</code></pre>\n\n<p>But easiest way is still: </p>\n\n<pre><code>boolean isEven = (a % 2) == 0;\n</code></pre>\n\n<p>Like @Steve Kuo said.</p>\n" }, { "answer_id": 49095157, "author": "Roland", "author_id": 480894, "author_profile": "https://Stackoverflow.com/users/480894", "pm_score": 3, "selected": false, "text": "<p>In Java it is the <code>%</code> operator:\n<a href=\"https://docs.oracle.com/javase/specs/jls/se9/html/jls-15.html#jls-15.17.3\" rel=\"noreferrer\">15.17.3. Remainder Operator %</a></p>\n\n<p>Note that there is also <a href=\"https://docs.oracle.com/javase/9/docs/api/java/lang/Math.html#floorMod-int-int-\" rel=\"noreferrer\"><code>floorMod</code></a> in the <code>java.lang.Math</code> class which will give a different result from <code>%</code> for arguments with different signs:</p>\n\n<p><a href=\"https://docs.oracle.com/javase/9/docs/api/java/lang/Math.html#floorMod-int-int-\" rel=\"noreferrer\"><code>public static int floorMod​(int x, int y)</code></a></p>\n" }, { "answer_id": 56878005, "author": "Shant Dashjian", "author_id": 5614029, "author_profile": "https://Stackoverflow.com/users/5614029", "pm_score": 2, "selected": false, "text": "<p>In <code>Java</code>, the <strong>mod</strong> operation can be performed as such:</p>\n\n<pre><code>Math.floorMod(a, b)\n</code></pre>\n\n<p><strong>Note:</strong>\nThe <strong>mod</strong> operation is different from the <strong>remainder</strong> operation. In <code>Java</code>, the <strong>remainder</strong> operation can be performed as such:</p>\n\n<pre><code>a % b\n</code></pre>\n" }, { "answer_id": 57532749, "author": "m4110c", "author_id": 4338565, "author_profile": "https://Stackoverflow.com/users/4338565", "pm_score": 3, "selected": false, "text": "<p>As others have pointed out, the <code>%</code> (remainder) operator is not the same as the mathematical\n<code>mod</code> modulus operation/function.</p>\n\n<blockquote>\n <h3><code>mod</code> vs <code>%</code></h3>\n \n <p>The <code>x mod n</code> function maps <code>x</code> to <code>n</code> in the range of <code>[0,n)</code>.<br>\n Whereas the <code>x % n</code> operator maps <code>x</code> to <code>n</code> in the range of <code>(-n,n)</code>.</p>\n</blockquote>\n\n<p>In order to have a method to use the mathematical modulus operation and not \ncare about the sign in front of <code>x</code> one can use:</p>\n\n<pre><code>((x % n) + n) % n\n</code></pre>\n\n<p>Maybe this picture helps understand it better (I had a hard time wrapping my head around this first)</p>\n\n<p><a href=\"https://i.stack.imgur.com/bzlMt.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/bzlMt.png\" alt=\"enter image description here\"></a></p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17245/" ]
As an example in pseudocode: ``` if ((a mod 2) == 0) { isEven = true; } else { isEven = false; } ```
Instead of the modulo operator, which has slightly different semantics, for non-negative integers, you can use the *remainder* operator `%`. For your exact example: ``` if ((a % 2) == 0) { isEven = true; } else { isEven = false; } ``` This can be simplified to a one-liner: ``` isEven = (a % 2) == 0; ```
90,350
<p>I have 3 PDF documents that are generated on the fly by a legacy library that we use, and written to disk. What's the easiest way for my JAVA server code to grab these 3 documents and turn them into one long PDF document where it's just all the pages from document #1, followed by all the pages from document #2, etc.</p> <p>Ideally I would like this to happen in memory so I can return it as a stream to the client, but writing it to disk is also an option.</p>
[ { "answer_id": 90372, "author": "JohnnyLambada", "author_id": 9648, "author_profile": "https://Stackoverflow.com/users/9648", "pm_score": 2, "selected": false, "text": "<p>I've used <a href=\"http://www.accesspdf.com/pdftk/\" rel=\"nofollow noreferrer\">pdftk</a> to great effect. It's an external application that you'll have to run from your java app.</p>\n" }, { "answer_id": 90396, "author": "J D OConal", "author_id": 17023, "author_profile": "https://Stackoverflow.com/users/17023", "pm_score": 1, "selected": false, "text": "<p>Take a look at this <a href=\"http://java-source.net/open-source/pdf-libraries\" rel=\"nofollow noreferrer\">list of Java open source PDF libraries</a>.</p>\n\n<p>Also check out <a href=\"http://www.roseindia.net/java/itext/Comboine2page.shtml\" rel=\"nofollow noreferrer\">this article</a>.</p>\n\n<p>[Edit: There's always Ghostscript, which is easy to use, but who wants more dependencies?]</p>\n" }, { "answer_id": 90512, "author": "rustyshelf", "author_id": 6044, "author_profile": "https://Stackoverflow.com/users/6044", "pm_score": 3, "selected": true, "text": "<p>@J D OConal, thanks for the tip, the article you sent me was very outdated, but it did point me towards iText. I found this page that explains how to do exactly what I need:\n<a href=\"http://java-x.blogspot.com/2006/11/merge-pdf-files-with-itext.html\" rel=\"nofollow noreferrer\">http://java-x.blogspot.com/2006/11/merge-pdf-files-with-itext.html</a></p>\n\n<p>Thanks for the other answers, but I don't really want to have to spawn other processes if I can avoid it, and our project already has itext.jar, so I'm not adding any external dependancies</p>\n\n<p>Here's the code I ended up writing:</p>\n\n<pre><code>public class PdfMergeHelper {\n\n /**\n * Merges the passed in PDFs, in the order that they are listed in the java.util.List.\n * Writes the resulting PDF out to the OutputStream provided.\n * \n * Sample Usage:\n * List&lt;InputStream&gt; pdfs = new ArrayList&lt;InputStream&gt;();\n * pdfs.add(new FileInputStream(\"/location/of/pdf/OQS_FRSv1.5.pdf\"));\n * pdfs.add(new FileInputStream(\"/location/of/pdf/PPFP-Contract_Genericv0.5.pdf\"));\n * pdfs.add(new FileInputStream(\"/location/of/pdf/PPFP-Quotev0.6.pdf\"));\n * FileOutputStream output = new FileOutputStream(\"/location/to/write/to/merge.pdf\");\n * PdfMergeHelper.concatPDFs(pdfs, output, true);\n * \n * @param streamOfPDFFiles the list of files to merge, in the order that they should be merged\n * @param outputStream the output stream to write the merged PDF to\n * @param paginate true if you want page numbers to appear at the bottom of each page, false otherwise\n */\n public static void concatPDFs(List&lt;InputStream&gt; streamOfPDFFiles, OutputStream outputStream, boolean paginate) {\n Document document = new Document();\n try {\n List&lt;InputStream&gt; pdfs = streamOfPDFFiles;\n List&lt;PdfReader&gt; readers = new ArrayList&lt;PdfReader&gt;();\n int totalPages = 0;\n Iterator&lt;InputStream&gt; iteratorPDFs = pdfs.iterator();\n\n // Create Readers for the pdfs.\n while (iteratorPDFs.hasNext()) {\n InputStream pdf = iteratorPDFs.next();\n PdfReader pdfReader = new PdfReader(pdf);\n readers.add(pdfReader);\n totalPages += pdfReader.getNumberOfPages();\n }\n // Create a writer for the outputstream\n PdfWriter writer = PdfWriter.getInstance(document, outputStream);\n\n document.open();\n BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);\n PdfContentByte cb = writer.getDirectContent(); // Holds the PDF\n // data\n\n PdfImportedPage page;\n int currentPageNumber = 0;\n int pageOfCurrentReaderPDF = 0;\n Iterator&lt;PdfReader&gt; iteratorPDFReader = readers.iterator();\n\n // Loop through the PDF files and add to the output.\n while (iteratorPDFReader.hasNext()) {\n PdfReader pdfReader = iteratorPDFReader.next();\n\n // Create a new page in the target for each source page.\n while (pageOfCurrentReaderPDF &lt; pdfReader.getNumberOfPages()) {\n document.newPage();\n pageOfCurrentReaderPDF++;\n currentPageNumber++;\n page = writer.getImportedPage(pdfReader, pageOfCurrentReaderPDF);\n cb.addTemplate(page, 0, 0);\n\n // Code for pagination.\n if (paginate) {\n cb.beginText();\n cb.setFontAndSize(bf, 9);\n cb.showTextAligned(PdfContentByte.ALIGN_CENTER, \"\" + currentPageNumber + \" of \" + totalPages,\n 520, 5, 0);\n cb.endText();\n }\n }\n pageOfCurrentReaderPDF = 0;\n }\n outputStream.flush();\n document.close();\n outputStream.close();\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n if (document.isOpen()) {\n document.close();\n }\n try {\n if (outputStream != null) {\n outputStream.close();\n }\n } catch (IOException ioe) {\n ioe.printStackTrace();\n }\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 90867, "author": "trunkc", "author_id": 1961117, "author_profile": "https://Stackoverflow.com/users/1961117", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://itextdocs.lowagie.com/tutorial/general/copystamp/index.php\" rel=\"nofollow noreferrer\">iText PdfCopy</a></p>\n" }, { "answer_id": 10696525, "author": "Random", "author_id": 54092, "author_profile": "https://Stackoverflow.com/users/54092", "pm_score": 2, "selected": false, "text": "<p>iText seems to have changed and now has commercial licencing requirements, along with not that good help (Want documentation? Buy our book!).</p>\n\n<p>We ended up finding PDFSharp <a href=\"http://www.pdfsharp.net/\" rel=\"nofollow\">http://www.pdfsharp.net/</a> and using that. The sample for concatenating multiple pdf documents together is simple and easy to follow: <a href=\"http://www.pdfsharp.net/wiki/ConcatenateDocuments-sample.ashx\" rel=\"nofollow\">http://www.pdfsharp.net/wiki/ConcatenateDocuments-sample.ashx</a></p>\n\n<p>Enjoy\nRandom</p>\n" }, { "answer_id": 12031780, "author": "Matthew Pigram", "author_id": 1367229, "author_profile": "https://Stackoverflow.com/users/1367229", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://pdfbox.apache.org/\" rel=\"nofollow\">PDFBox</a> is by far the easiest way to achieve this, there is a utility called PDFMerger within the code which makes things very easy, all it took me was a for loop and 2 lines of code in it and all done :)</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6044/" ]
I have 3 PDF documents that are generated on the fly by a legacy library that we use, and written to disk. What's the easiest way for my JAVA server code to grab these 3 documents and turn them into one long PDF document where it's just all the pages from document #1, followed by all the pages from document #2, etc. Ideally I would like this to happen in memory so I can return it as a stream to the client, but writing it to disk is also an option.
@J D OConal, thanks for the tip, the article you sent me was very outdated, but it did point me towards iText. I found this page that explains how to do exactly what I need: <http://java-x.blogspot.com/2006/11/merge-pdf-files-with-itext.html> Thanks for the other answers, but I don't really want to have to spawn other processes if I can avoid it, and our project already has itext.jar, so I'm not adding any external dependancies Here's the code I ended up writing: ``` public class PdfMergeHelper { /** * Merges the passed in PDFs, in the order that they are listed in the java.util.List. * Writes the resulting PDF out to the OutputStream provided. * * Sample Usage: * List<InputStream> pdfs = new ArrayList<InputStream>(); * pdfs.add(new FileInputStream("/location/of/pdf/OQS_FRSv1.5.pdf")); * pdfs.add(new FileInputStream("/location/of/pdf/PPFP-Contract_Genericv0.5.pdf")); * pdfs.add(new FileInputStream("/location/of/pdf/PPFP-Quotev0.6.pdf")); * FileOutputStream output = new FileOutputStream("/location/to/write/to/merge.pdf"); * PdfMergeHelper.concatPDFs(pdfs, output, true); * * @param streamOfPDFFiles the list of files to merge, in the order that they should be merged * @param outputStream the output stream to write the merged PDF to * @param paginate true if you want page numbers to appear at the bottom of each page, false otherwise */ public static void concatPDFs(List<InputStream> streamOfPDFFiles, OutputStream outputStream, boolean paginate) { Document document = new Document(); try { List<InputStream> pdfs = streamOfPDFFiles; List<PdfReader> readers = new ArrayList<PdfReader>(); int totalPages = 0; Iterator<InputStream> iteratorPDFs = pdfs.iterator(); // Create Readers for the pdfs. while (iteratorPDFs.hasNext()) { InputStream pdf = iteratorPDFs.next(); PdfReader pdfReader = new PdfReader(pdf); readers.add(pdfReader); totalPages += pdfReader.getNumberOfPages(); } // Create a writer for the outputstream PdfWriter writer = PdfWriter.getInstance(document, outputStream); document.open(); BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); PdfContentByte cb = writer.getDirectContent(); // Holds the PDF // data PdfImportedPage page; int currentPageNumber = 0; int pageOfCurrentReaderPDF = 0; Iterator<PdfReader> iteratorPDFReader = readers.iterator(); // Loop through the PDF files and add to the output. while (iteratorPDFReader.hasNext()) { PdfReader pdfReader = iteratorPDFReader.next(); // Create a new page in the target for each source page. while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) { document.newPage(); pageOfCurrentReaderPDF++; currentPageNumber++; page = writer.getImportedPage(pdfReader, pageOfCurrentReaderPDF); cb.addTemplate(page, 0, 0); // Code for pagination. if (paginate) { cb.beginText(); cb.setFontAndSize(bf, 9); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, "" + currentPageNumber + " of " + totalPages, 520, 5, 0); cb.endText(); } } pageOfCurrentReaderPDF = 0; } outputStream.flush(); document.close(); outputStream.close(); } catch (Exception e) { e.printStackTrace(); } finally { if (document.isOpen()) { document.close(); } try { if (outputStream != null) { outputStream.close(); } } catch (IOException ioe) { ioe.printStackTrace(); } } } } ```
90,360
<p>I was investigating the rapid growth of a SQL Server 2005 transaction log when I found that transaction logs will only truncate correctly - if the sys.databases "log_reuse_wait" column is set to 0 - meaning that nothing is keeping the transaction log from reusing existing space. </p> <p>One day when I was intending to backup/truncate a log file, I found that this column had a 4, or ACTIVE_TRANSACTION going on in the tempdb. I then checked for any open transactions using DBCC OPENTRAN('tempdb'), and the open_tran column from sysprocesses. The result was that I could find no active transactions anywhere in the system.</p> <p>Are the settings in the log_reuse_wait column accurate? Are there transactions going on that are not detectable using the methods I described above? Am I just missing something obvious?</p>
[ { "answer_id": 91571, "author": "Jonas Lincoln", "author_id": 17436, "author_profile": "https://Stackoverflow.com/users/17436", "pm_score": -1, "selected": false, "text": "<p>Hm, tricky. Could it be that the question it self to sys.databases is causing the ACTIVE_TRANSACTION? In that case though, it should be in the MASTER and not the TEMPDB.</p>\n" }, { "answer_id": 93117, "author": "Michael K. Campbell", "author_id": 11191, "author_profile": "https://Stackoverflow.com/users/11191", "pm_score": 1, "selected": false, "text": "<p>There are a couple of links to additional tools/references you can use to help troubleshoot this problem on the References link for this video:<br>\n<a href=\"http://www.sqlservervideos.com/sqlserver-backups/sql2528-log-files\" rel=\"nofollow noreferrer\">Managing SQL Server 2005 and 2008 Log Files</a></p>\n\n<p>That said, the information in log_reuse_wait should be accurate. You likely just had a stalled or orphaned transaction that you weren't somehow able to spot. </p>\n" }, { "answer_id": 93269, "author": "Mike Dimmick", "author_id": 6970, "author_profile": "https://Stackoverflow.com/users/6970", "pm_score": 1, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/questions/72961/the-log-file-for-database-is-full#73421\">My answer</a> from <a href=\"https://stackoverflow.com/questions/72961/the-log-file-for-database-is-full\">The Log File for Database is Full</a>:</p>\n\n<p>As soon as you take a full backup of the database, and the database is not using the Simple recovery model, SQL Server keeps a complete record of all transactions ever performed on the database. It does this so that in the event of a catastrophic failure where you lose the data file, you can restore to the point of failure by backing up the log and, once you have restored an old data backup, restore the log to replay the lost transactions.</p>\n\n<p>To prevent this building up, you must back up the transaction log. Or, you can break the chain at the current point using the <code>TRUNCATE_ONLY</code> or <code>NO_LOG</code> options of BACKUP LOG.</p>\n\n<p>If you don't need this feature, set the recovery model to Simple.</p>\n" }, { "answer_id": 334281, "author": "MkUltra", "author_id": 40011, "author_profile": "https://Stackoverflow.com/users/40011", "pm_score": 0, "selected": false, "text": "<p>The data is probably accurate. What you need to do is have a regular transaction log backup. Contrary to other advice you should NOT use the NO_TRUNCATE option on 2005 as it clears the log of transactions committed but it doesn't back them up.</p>\n\n<p>What you should be doing is performing a tail-log backup by using the BACKUP LOG statement with NO_TRUNCATE option. You should be applying regular transaction logs throughout the day as well. This should help keep the size fairly manageable.</p>\n" }, { "answer_id": 335014, "author": "Clinemi", "author_id": 14947, "author_profile": "https://Stackoverflow.com/users/14947", "pm_score": 3, "selected": false, "text": "<p>I still don't know why I was seeing the ACTIVE_TRANSACTION in the sys.databases log_reuse_wait_desc column - when there were no transactions running, but my subsequent experience indicates that the log_reuse_wait column for the tempdb changes for reasons that are not very clear, and for my purposes, not very relevant. Also, I found that running DBCC OPENTRAN, or the \"select open_tran from sysprocess\" code, is a lot less informative than using the below statements when looking for transaction information:</p>\n\n<pre><code>select * from sys.dm_tran_active_transactions\n\nselect * from sys.dm_tran_session_transactions \n\nselect * from sys.dm_tran_locks\n</code></pre>\n" }, { "answer_id": 28365908, "author": "agdk26", "author_id": 2078359, "author_profile": "https://Stackoverflow.com/users/2078359", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://www.sqlskills.com/blogs/paul/worrying-cause-log-growth-log_reuse_wait_desc/\" rel=\"nofollow\">Here</a> there are explanations how log_reuse_wait_desc is working:</p>\n\n<blockquote>\n <p>We also need to understand how the log_reuse_wait_desc reporting mechanism works. It gives the reason why log truncation couldn’t happen the last time log truncation was attempted. This can be confusing – for instance if you see ACTIVE_BACKUP_OR_RESTORE and you know there isn’t a backup or restore operation running, this just means that there was one running the last time log truncation was attempted.</p>\n</blockquote>\n\n<p>So in your case there is no ACTIVE TRANSACTION right now, but it was when log truncation was attempted last time.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14947/" ]
I was investigating the rapid growth of a SQL Server 2005 transaction log when I found that transaction logs will only truncate correctly - if the sys.databases "log\_reuse\_wait" column is set to 0 - meaning that nothing is keeping the transaction log from reusing existing space. One day when I was intending to backup/truncate a log file, I found that this column had a 4, or ACTIVE\_TRANSACTION going on in the tempdb. I then checked for any open transactions using DBCC OPENTRAN('tempdb'), and the open\_tran column from sysprocesses. The result was that I could find no active transactions anywhere in the system. Are the settings in the log\_reuse\_wait column accurate? Are there transactions going on that are not detectable using the methods I described above? Am I just missing something obvious?
I still don't know why I was seeing the ACTIVE\_TRANSACTION in the sys.databases log\_reuse\_wait\_desc column - when there were no transactions running, but my subsequent experience indicates that the log\_reuse\_wait column for the tempdb changes for reasons that are not very clear, and for my purposes, not very relevant. Also, I found that running DBCC OPENTRAN, or the "select open\_tran from sysprocess" code, is a lot less informative than using the below statements when looking for transaction information: ``` select * from sys.dm_tran_active_transactions select * from sys.dm_tran_session_transactions select * from sys.dm_tran_locks ```
90,374
<p>Why doesn't this Google Chart API URL render both data sets on this XY scatter plot? </p> <pre><code>http://chart.apis.google.com/chart?cht=lxy&amp;chd=t:10,20,30,40,50,60,70,80,90,100,110,120,130,140,150,160,170,180,190,200|0.10,0.23,0.33,0.44,0.56,0.66,0.79,0.90,0.99,1.12,1.22,1.33,1.44,1.56,1.68,1.79,1.90,2.02,2.12,2.22|0.28,0.56,0.85,1.12,1.42,1.68,1.97,2.26,2.54,2.84,3.12,3.40,3.84,4.10,4.53,4.80,5.45,6.02,6.40,6.80&amp;chco=3072F3,ff0000,00aaaa&amp;chls=2,4,1&amp;chs=320x240&amp;chds=0,201,0,7&amp;chm=s,FF0000,0,-1,5|s,0000ff,1,-1,5|s,00aa00,2,-1,5 </code></pre> <p>I've read the <a href="http://code.google.com/apis/chart/" rel="nofollow noreferrer">documentation</a> over and over again, and I can't figure it out.</p>
[ { "answer_id": 90410, "author": "Christian Davén", "author_id": 12534, "author_profile": "https://Stackoverflow.com/users/12534", "pm_score": -1, "selected": true, "text": "<p>I think it actually does render both data sets, but you can only se one of them because there's only one scale on the y axis. (In other words, 0.10 is too small to show.)</p>\n\n<p>And, you should really be using percentages. 100 is the highest accepted value:</p>\n\n<blockquote>\n <p>Where chart data string consists of positive floating point numbers from zero (0.0) to one hundred (100.0)</p>\n</blockquote>\n" }, { "answer_id": 394406, "author": "Julien Chastang", "author_id": 32174, "author_profile": "https://Stackoverflow.com/users/32174", "pm_score": 2, "selected": false, "text": "<p>First a point of clarification. You talk about a \"XY scatter plot\", but these are actually 2 distinct chart types in the Google Chart API. Your URL refers to cht=lxy parameter which is an <a href=\"http://code.google.com/apis/chart/types.html#line_charts\" rel=\"nofollow noreferrer\">XY line chart</a>.</p>\n\n<p>The first problem with your URL is your data parameter (chd). Since it is an <a href=\"http://code.google.com/apis/chart/types.html#line_charts\" rel=\"nofollow noreferrer\">XY line chart</a>, data sets must be defined in <strong>pairs</strong> but I see an odd number of data sets (3).</p>\n\n<p>Christian D's response is incorrect. There is no percentage requirement.</p>\n\n<p>You may be better off using a <a href=\"http://groups.google.com/group/google-chart-api/web/useful-links-to-api-libraries\" rel=\"nofollow noreferrer\">wrapper API</a> which abstracts away many of these ugly details.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90374", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3499/" ]
Why doesn't this Google Chart API URL render both data sets on this XY scatter plot? ``` http://chart.apis.google.com/chart?cht=lxy&chd=t:10,20,30,40,50,60,70,80,90,100,110,120,130,140,150,160,170,180,190,200|0.10,0.23,0.33,0.44,0.56,0.66,0.79,0.90,0.99,1.12,1.22,1.33,1.44,1.56,1.68,1.79,1.90,2.02,2.12,2.22|0.28,0.56,0.85,1.12,1.42,1.68,1.97,2.26,2.54,2.84,3.12,3.40,3.84,4.10,4.53,4.80,5.45,6.02,6.40,6.80&chco=3072F3,ff0000,00aaaa&chls=2,4,1&chs=320x240&chds=0,201,0,7&chm=s,FF0000,0,-1,5|s,0000ff,1,-1,5|s,00aa00,2,-1,5 ``` I've read the [documentation](http://code.google.com/apis/chart/) over and over again, and I can't figure it out.
I think it actually does render both data sets, but you can only se one of them because there's only one scale on the y axis. (In other words, 0.10 is too small to show.) And, you should really be using percentages. 100 is the highest accepted value: > > Where chart data string consists of positive floating point numbers from zero (0.0) to one hundred (100.0) > > >
90,418
<p>I have a shell script that executes a number of commands. How do I make the shell script exit if any of the commands exit with a non-zero exit code?</p>
[ { "answer_id": 90434, "author": "Martin W", "author_id": 14199, "author_profile": "https://Stackoverflow.com/users/14199", "pm_score": 4, "selected": false, "text": "<p>In Bash this is easy. Just tie them together with <code>&amp;&amp;</code>:</p>\n<pre><code>command1 &amp;&amp; command2 &amp;&amp; command3\n</code></pre>\n<p>You can also use the nested <em>if</em> construct:</p>\n<pre><code>if command1\n then\n if command2\n then\n do_something\n else\n exit\n fi\n else\n exit\nfi\n</code></pre>\n" }, { "answer_id": 90435, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 10, "selected": true, "text": "<p>After each command, the exit code can be found in the <code>$?</code> variable so you would have something like:</p>\n\n<pre><code>ls -al file.ext\nrc=$?; if [[ $rc != 0 ]]; then exit $rc; fi\n</code></pre>\n\n<p>You need to be careful of piped commands since the <code>$?</code> only gives you the return code of the last element in the pipe so, in the code:</p>\n\n<pre><code>ls -al file.ext | sed 's/^/xx: /\"\n</code></pre>\n\n<p>will not return an error code if the file doesn't exist (since the <code>sed</code> part of the pipeline actually works, returning 0).</p>\n\n<p>The <code>bash</code> shell actually provides an array which can assist in that case, that being <code>PIPESTATUS</code>. This array has one element for each of the pipeline components, that you can access individually like <code>${PIPESTATUS[0]}</code>:</p>\n\n<pre><code>pax&gt; false | true ; echo ${PIPESTATUS[0]}\n1\n</code></pre>\n\n<p>Note that this is getting you the result of the <code>false</code> command, not the entire pipeline. You can also get the entire list to process as you see fit:</p>\n\n<pre><code>pax&gt; false | true | false; echo ${PIPESTATUS[*]}\n1 0 1\n</code></pre>\n\n<p>If you wanted to get the largest error code from a pipeline, you could use something like:</p>\n\n<pre><code>true | true | false | true | false\nrcs=${PIPESTATUS[*]}; rc=0; for i in ${rcs}; do rc=$(($i &gt; $rc ? $i : $rc)); done\necho $rc\n</code></pre>\n\n<p>This goes through each of the <code>PIPESTATUS</code> elements in turn, storing it in <code>rc</code> if it was greater than the previous <code>rc</code> value.</p>\n" }, { "answer_id": 90440, "author": "Allen", "author_id": 6043, "author_profile": "https://Stackoverflow.com/users/6043", "pm_score": 6, "selected": false, "text": "<p>\"<code>set -e</code>\" is probably the easiest way to do this. Just put that before any commands in your program.</p>\n" }, { "answer_id": 90441, "author": "Jeff Hill", "author_id": 14742, "author_profile": "https://Stackoverflow.com/users/14742", "pm_score": 8, "selected": false, "text": "<p>If you want to work with <code>$?</code>, you'll need to check it after each command, since <code>$?</code> is updated after each command exits. This means that if you execute a pipeline, you'll only get the exit code of the last process in the pipeline.</p>\n<p>Another approach is to do this:</p>\n<pre><code>set -e\nset -o pipefail\n</code></pre>\n<p>If you put this at the top of the shell script, it looks like Bash will take care of this for you. As a previous poster noted, &quot;set -e&quot; will cause Bash to exit with an error on any simple command. &quot;set -o pipefail&quot; will cause Bash to exit with an error on any command in a pipeline as well.</p>\n<p>See <a href=\"http://www.linuxquestions.org/questions/programming-9/bash-scripting-problem-with-exit-codes-444852/\" rel=\"nofollow noreferrer\">here</a> or <a href=\"http://steve-parker.org/sh/exitcodes.shtml\" rel=\"nofollow noreferrer\">here</a> for a little more discussion on this problem. <a href=\"http://www.gnu.org/software/bash/manual/bashref.html#The-Set-Builtin\" rel=\"nofollow noreferrer\">Here</a> is the Bash manual section on the <code>set</code> builtin.</p>\n" }, { "answer_id": 90447, "author": "Arvodan", "author_id": 5751, "author_profile": "https://Stackoverflow.com/users/5751", "pm_score": 5, "selected": false, "text": "<p>If you just call exit in Bash without any parameters, it will return the exit code of the last command. Combined with <code>OR</code>, Bash should only invoke exit, if the previous command fails. But I haven't tested this.</p>\n<pre>\ncommand1 || exit;\ncommand2 || exit;\n</pre>\n<p>Bash will also store the exit code of the last command in the variable <code>$?</code>.</p>\n" }, { "answer_id": 90475, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>For Bash:</p>\n<pre><code># This will trap any errors or commands with non-zero exit status\n# by calling function catch_errors()\ntrap catch_errors ERR;\n\n#\n# ... the rest of the script goes here\n#\n\nfunction catch_errors() {\n # Do whatever on errors\n #\n #\n echo &quot;script aborted, because of errors&quot;;\n exit 0;\n}\n</code></pre>\n" }, { "answer_id": 493676, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p><a href=\"http://cfaj.freeshell.org/shell/cus-faq-2.html#11\" rel=\"nofollow noreferrer\">http://cfaj.freeshell.org/shell/cus-faq-2.html#11</a></p>\n<ol start=\"11\">\n<li><p>How do I get the exit code of <code>cmd1</code> in <code>cmd1|cmd2</code></p>\n<p>First, note that <code>cmd1</code> exit code could be non-zero and still don't mean an error. This happens for instance in</p>\n<pre><code>cmd | head -1\n</code></pre>\n<p>You might observe a 141 (or 269 with ksh93) exit status of <code>cmd1</code>, but it's because <code>cmd</code> was interrupted by a SIGPIPE signal when <code>head -1</code> terminated after having read one line.</p>\n<p>To know the exit status of the elements of a pipeline\n<code>cmd1 | cmd2 | cmd3</code></p>\n<p>a. with <a href=\"https://en.wikipedia.org/wiki/Z_shell\" rel=\"nofollow noreferrer\">Z shell</a> (<code>zsh</code>):</p>\n<p>The exit codes are provided in the pipestatus special array.\n<code>cmd1</code> exit code is in <code>$pipestatus[1]</code>, <code>cmd3</code> exit code in\n<code>$pipestatus[3]</code>, so that <code>$?</code> is always the same as\n<code>$pipestatus[-1]</code>.</p>\n<p>b. with Bash:</p>\n<p>The exit codes are provided in the <code>PIPESTATUS</code> special array.\n<code>cmd1</code> exit code is in <code>${PIPESTATUS[0]}</code>, <code>cmd3</code> exit code in\n<code>${PIPESTATUS[2]}</code>, so that <code>$?</code> is always the same as\n<code>${PIPESTATUS: -1}</code>.</p>\n<p>...</p>\n<p>For more details see <em><a href=\"https://en.wikipedia.org/wiki/Z_shell\" rel=\"nofollow noreferrer\">Z shell</a></em>.</p>\n</li>\n</ol>\n" }, { "answer_id": 8045505, "author": "chemila", "author_id": 889064, "author_profile": "https://Stackoverflow.com/users/889064", "pm_score": 5, "selected": false, "text": "<pre><code>[ $? -eq 0 ] || exit $?; # Exit for nonzero return code\n</code></pre>\n" }, { "answer_id": 9353084, "author": "Yordan Georgiev", "author_id": 65706, "author_profile": "https://Stackoverflow.com/users/65706", "pm_score": 2, "selected": false, "text": "<pre><code>#\n#------------------------------------------------------------------------------\n# purpose: to run a command, log cmd output, exit on error\n# usage:\n# set -e; do_run_cmd_or_exit &quot;$cmd&quot; ; set +e\n#------------------------------------------------------------------------------\ndo_run_cmd_or_exit(){\n cmd=&quot;$@&quot; ;\n\n do_log &quot;DEBUG running cmd or exit: \\&quot;$cmd\\&quot;&quot;\n msg=$($cmd 2&gt;&amp;1)\n export exit_code=$?\n\n # If occurred during the execution, exit with error\n error_msg=&quot;Failed to run the command:\n \\&quot;$cmd\\&quot; with the output:\n \\&quot;$msg\\&quot; !!!&quot;\n\n if [ $exit_code -ne 0 ] ; then\n do_log &quot;ERROR $msg&quot;\n do_log &quot;FATAL $msg&quot;\n do_exit &quot;$exit_code&quot; &quot;$error_msg&quot;\n else\n # If no errors occurred, just log the message\n do_log &quot;DEBUG : cmdoutput : \\&quot;$msg\\&quot;&quot;\n fi\n\n}\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9940/" ]
I have a shell script that executes a number of commands. How do I make the shell script exit if any of the commands exit with a non-zero exit code?
After each command, the exit code can be found in the `$?` variable so you would have something like: ``` ls -al file.ext rc=$?; if [[ $rc != 0 ]]; then exit $rc; fi ``` You need to be careful of piped commands since the `$?` only gives you the return code of the last element in the pipe so, in the code: ``` ls -al file.ext | sed 's/^/xx: /" ``` will not return an error code if the file doesn't exist (since the `sed` part of the pipeline actually works, returning 0). The `bash` shell actually provides an array which can assist in that case, that being `PIPESTATUS`. This array has one element for each of the pipeline components, that you can access individually like `${PIPESTATUS[0]}`: ``` pax> false | true ; echo ${PIPESTATUS[0]} 1 ``` Note that this is getting you the result of the `false` command, not the entire pipeline. You can also get the entire list to process as you see fit: ``` pax> false | true | false; echo ${PIPESTATUS[*]} 1 0 1 ``` If you wanted to get the largest error code from a pipeline, you could use something like: ``` true | true | false | true | false rcs=${PIPESTATUS[*]}; rc=0; for i in ${rcs}; do rc=$(($i > $rc ? $i : $rc)); done echo $rc ``` This goes through each of the `PIPESTATUS` elements in turn, storing it in `rc` if it was greater than the previous `rc` value.
90,428
<p>I'm looking for an LDAP libracy in C or C++ that allows me to specify a list of LDAP hostnames instead of a single hostname. The library should then use the first one it can connect to in case one or more of the servers is/are down. I'm sure it'd be easy to wrap an existing library to create this, but why reinvent the wheel?</p>
[ { "answer_id": 90649, "author": "Kamil Kisiel", "author_id": 15061, "author_profile": "https://Stackoverflow.com/users/15061", "pm_score": -1, "selected": false, "text": "<p>I can't say I've ever heard of one. Furthermore, most LDAP-capable software I've used supported failover poorly or not at all. You might be better off trying to implement the failover at the server, by putting it behind a load balancer or similar.</p>\n" }, { "answer_id": 288838, "author": "geocar", "author_id": 37507, "author_profile": "https://Stackoverflow.com/users/37507", "pm_score": 2, "selected": false, "text": "<p>Use multiple A records, each with a different IP.</p>\n\n<pre><code>ldapserver.example.com. IN A 1.2.3.4\nldapserver.example.com. IN A 2.3.4.5\n</code></pre>\n\n<p>The OpenLDAP client libs will try each host in turn. Failover is (unfortunately) as slow as your TCP connection timeout...</p>\n" }, { "answer_id": 1329273, "author": "Stef", "author_id": 131414, "author_profile": "https://Stackoverflow.com/users/131414", "pm_score": 1, "selected": false, "text": "<p>The <a href=\"http://developer.novell.com/wiki/index.php/Cldap\" rel=\"nofollow noreferrer\">novell cldap libraries</a> (and java libraries) support a list of space separated hosts when connecting. It'll try each one in turn, as noted in the <a href=\"http://developer.novell.com/documentation/cldap/ldaplibc/index.html?page=/documentation/cldap/ldaplibc/data/a3m14np.html\" rel=\"nofollow noreferrer\"><code>ldap_init()</code></a> page.</p>\n\n<p>The openldap libldap library also supports a space separated list of hosts passed to <code>ldap_open()</code> or a comma separated list passed to <code>ldap_initialize()</code>.</p>\n\n<p>The only catch is to make sure to handle the <code>LDAP_SERVER_DOWN</code> error that gets returned after a connection goes away. I usually write a wrapper function that tries an operation (ie: a search), and tries to reconnect if <code>LDAP_SERVER_DOWN</code> occurs, and then does the operation again. </p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90428", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm looking for an LDAP libracy in C or C++ that allows me to specify a list of LDAP hostnames instead of a single hostname. The library should then use the first one it can connect to in case one or more of the servers is/are down. I'm sure it'd be easy to wrap an existing library to create this, but why reinvent the wheel?
Use multiple A records, each with a different IP. ``` ldapserver.example.com. IN A 1.2.3.4 ldapserver.example.com. IN A 2.3.4.5 ``` The OpenLDAP client libs will try each host in turn. Failover is (unfortunately) as slow as your TCP connection timeout...
90,493
<p>How can I cast long to HWND (C++ visual studio 8)?</p> <pre><code>Long lWindowHandler; HWND oHwnd = (HWND)lWindowHandler; </code></pre> <p>But I got the following warning:</p> <blockquote> <p>warning C4312: 'type cast' : conversion from 'LONG' to 'HWND' of greater size</p> </blockquote> <p>Thanks.</p>
[ { "answer_id": 90508, "author": "Roger Lipscombe", "author_id": 8446, "author_profile": "https://Stackoverflow.com/users/8446", "pm_score": 3, "selected": false, "text": "<p>As long as you're sure that the LONG you have is really an HWND, then it's as simple as:</p>\n\n<pre><code>HWND hWnd = (HWND)(LONG_PTR)lParam;\n</code></pre>\n" }, { "answer_id": 90533, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": true, "text": "<p>HWND is a handle to a window.\nThis type is declared in WinDef.h as follows:</p>\n\n<blockquote>\n <p>typedef HANDLE HWND;</p>\n</blockquote>\n\n<p>HANDLE is handle to an object.\nThis type is declared in WinNT.h as follows:</p>\n\n<blockquote>\n <p>typedef PVOID HANDLE;</p>\n</blockquote>\n\n<p>Finally, PVOID is a pointer to any type.\nThis type is declared in WinNT.h as follows:</p>\n\n<blockquote>\n <p>typedef void *PVOID;</p>\n</blockquote>\n\n<p>So, HWND is actually a pointer to void. You can cast a long to a HWND like this:</p>\n\n<blockquote>\n <p>HWND h = (HWND)my_long_var;</p>\n</blockquote>\n\n<p>but very careful of what information is stored in my_long_var. You have to make sure that you have a pointer in there.</p>\n\n<p>Later edit:\nThe warning suggest that you've got 64-bit portability checks turned on. If you're building a 32 bit application you can ignore them. </p>\n" }, { "answer_id": 90660, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 3, "selected": false, "text": "<p>Doing that is only safe if you are not running on a 64 bit version of windows. The LONG type is 32 bits, but the HANDLE type is probably 64 bits. You'll need to make your code 64 bit clean. In short, you will want to change the LONG to a LONG_PTR.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/aa384242(VS.85).aspx\" rel=\"noreferrer\">Rules for using pointer types</a>:</p>\n\n<blockquote>\n <p>Do not cast pointers to int, long,\n ULONG, or DWORD. If you must cast a\n pointer to test some bits, set or\n clear bits, or otherwise manipulate\n its contents, use the UINT_PTR or\n INT_PTR type. These types are integral\n types that scale to the size of a\n pointer for both 32- and 64-bit\n Windows (for example, ULONG for 32-bit\n Windows and _int64 for 64-bit\n Windows). For example, assume you are\n porting the following code:</p>\n \n <p>ImageBase = (PVOID)((ULONG)ImageBase |\n 1);</p>\n \n <p>As a part of the porting process, you\n would change the code as follows:</p>\n \n <p>ImageBase =\n (PVOID)((ULONG_PTR)ImageBase | 1);</p>\n \n <p>Use UINT_PTR and INT_PTR where\n appropriate (and if you are uncertain\n whether they are required, there is no\n harm in using them just in case). Do\n not cast your pointers to the types\n ULONG, LONG, INT, UINT, or DWORD.</p>\n \n <p>Note that HANDLE is defined as a\n void*, so typecasting a HANDLE value\n to a ULONG value to test, set, or\n clear the low-order 2 bits is an error\n on 64-bit Windows.</p>\n</blockquote>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90493", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
How can I cast long to HWND (C++ visual studio 8)? ``` Long lWindowHandler; HWND oHwnd = (HWND)lWindowHandler; ``` But I got the following warning: > > warning C4312: 'type cast' : conversion from 'LONG' to 'HWND' of greater size > > > Thanks.
HWND is a handle to a window. This type is declared in WinDef.h as follows: > > typedef HANDLE HWND; > > > HANDLE is handle to an object. This type is declared in WinNT.h as follows: > > typedef PVOID HANDLE; > > > Finally, PVOID is a pointer to any type. This type is declared in WinNT.h as follows: > > typedef void \*PVOID; > > > So, HWND is actually a pointer to void. You can cast a long to a HWND like this: > > HWND h = (HWND)my\_long\_var; > > > but very careful of what information is stored in my\_long\_var. You have to make sure that you have a pointer in there. Later edit: The warning suggest that you've got 64-bit portability checks turned on. If you're building a 32 bit application you can ignore them.
90,517
<p>When a user goes to my site, my script checks for 2 cookies which store the user id + part of the password, to automatically log them in. </p> <p>It's possible to edit the contents of cookies via a cookie editor, so I guess it's possible to add some malicious content to a written cookie?</p> <p>Should I add <code>mysql_real_escape_string</code> (or something else) to all my cookie calls or is there some kind of built in procedure that will not allow this to happen?</p>
[ { "answer_id": 90526, "author": "Jeremy Privett", "author_id": 560, "author_profile": "https://Stackoverflow.com/users/560", "pm_score": 0, "selected": false, "text": "<p>You should mysql_real_escape_string <strong><em>anything</em></strong> that could be potentially harmful. Never trust any type of input that can be altered by the user.</p>\n" }, { "answer_id": 90535, "author": "Marcel", "author_id": 131, "author_profile": "https://Stackoverflow.com/users/131", "pm_score": 0, "selected": false, "text": "<p>I agree with you. It is possible to modify the cookies and send in malicious data.</p>\n\n<p>I believe that it is good practice to filter the values you get from the cookies before you use them. As a rule of thumb I do filter any other input that may be tampered with.</p>\n" }, { "answer_id": 90555, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 1, "selected": false, "text": "<p>I only use mysql_real_escape_string before inserting variables into an SQL statement. You'll just get yourself confused if some of your variables are <em>already</em> escaped, and then you escape them again. It's a classic bug you see in newbies' blog webapps:</p>\n\n<blockquote>\n <p>When someone writes an apostrophe it keeps on adding slashes ruining the blog\\\\\\\\\\\\\\'s pages.</p>\n</blockquote>\n\n<p>The value of a variable isn't dangerous by itself: it's only when you put it into a string or something similar that you start straying into dangerous waters.</p>\n\n<p>Of course though, never trust anything that comes from the client-side.</p>\n" }, { "answer_id": 90556, "author": "timvw", "author_id": 15267, "author_profile": "https://Stackoverflow.com/users/15267", "pm_score": 0, "selected": false, "text": "<p>mysql_real_escape_string is so passé... These days you should really use parameter binding instead.</p>\n\n<p>I'll elaborate by mentionning that i was referring to <a href=\"http://dev.mysql.com/tech-resources/articles/4.1/prepared-statements.html\" rel=\"nofollow noreferrer\">prepared statements</a> and provide a link to an article that demonstrates that sometimes mysl_real_escape_string isn't sufficient enough: <a href=\"http://www.webappsec.org/projects/articles/091007.txt\" rel=\"nofollow noreferrer\"><a href=\"http://www.webappsec.org/projects/articles/091007.txt\" rel=\"nofollow noreferrer\">http://www.webappsec.org/projects/articles/091007.txt</a></a></p>\n" }, { "answer_id": 90582, "author": "J D OConal", "author_id": 17023, "author_profile": "https://Stackoverflow.com/users/17023", "pm_score": -1, "selected": false, "text": "<p>I would recommend using htmlentities($input, ENT_QUOTES) instead of mysql_real_escape_string as this will also prevent any accidental outputting of actual HTML code. Of course, you could use mysql_real_escape_string and htmlentities, but why would you?</p>\n" }, { "answer_id": 90609, "author": "joelhardi", "author_id": 11438, "author_profile": "https://Stackoverflow.com/users/11438", "pm_score": 4, "selected": true, "text": "<p>What you <em>really</em> need to do is not send these cookie values that are hackable in the first place. Instead, why not hash the username and password and a (secret) salt and set that as the cookie value? i.e.:</p>\n\n<pre><code>define('COOKIE_SALT', 'secretblahblahlkdsfklj');\n$cookie_value = sha1($username.$password.COOKIE_SALT);\n</code></pre>\n\n<p>Then you know the cookie value is always going to be a 40-character hexidecimal string, and can compare the value the user sends back with whatever's in the database to decide whether they're valid or not:</p>\n\n<pre><code>if ($user_cookie_value == sha1($username_from_db.$password_drom_db.COOKIE_SALT)) {\n # valid\n} else {\n #not valid\n}\n</code></pre>\n\n<p><code>mysql_real_escape_string</code> makes an additional hit to the database, BTW (a lot of people don't realize it requires a DB connection and queries MySQL).</p>\n\n<p>The best way to do what you want if you can't change your app and insist on using hackable cookie values is to use <a href=\"http://devzone.zend.com/node/view/id/686\" rel=\"noreferrer\">prepared statements with bound parameters</a>.</p>\n" }, { "answer_id": 90630, "author": "Nathan Strong", "author_id": 9780, "author_profile": "https://Stackoverflow.com/users/9780", "pm_score": 2, "selected": false, "text": "<p>The point of mysql_real_escape_string isn't to protect against injection attacks, it's to ensure your data is accurately stored in the database. Thus, it should be called on ANY string going into the database, regardless of its source.</p>\n\n<p>You should, however, <em>also</em> be using parameterized queries (via mysqli or PDO) to protect yourself from SQL injection. Otherwise you risk ending up like <a href=\"http://xkcd.com/327/\" rel=\"nofollow noreferrer\">little Bobby Tables' school</a>.</p>\n" }, { "answer_id": 90705, "author": "micahwittman", "author_id": 11181, "author_profile": "https://Stackoverflow.com/users/11181", "pm_score": 0, "selected": false, "text": "<p>Yegor, you can store the hash when a user account is created/updated, then whenever a login is initiated, you hash the data posted to the server and compare against what was stored in the database for that one username.</p>\n\n<p>(Off the top of my head in loose php - treat as pseudo code):</p>\n\n<pre><code>$usernameFromPostDbsafe = LimitToAlphaNumUnderscore($usernameFromPost);\n$result = Query(\"SELECT hash FROM userTable WHERE username='$usernameFromPostDbsafe' LIMIT 1;\");\n$hashFromDb = $result['hash'];\nif( (sha1($usernameFromPost.$passwordFromPost.SALT)) == $hashFromDb ){\n //Auth Success\n}else{\n //Auth Failure\n}\n</code></pre>\n\n<p>After a successful authentication, you could store the hash in $_SESSION or in a database table of cached authenticated username/hashes. Then send the hash back to the browser (in a cookie for instance) so subsequent page loads send the hash back to the server to be compared against the hash held in your chosen session storage.</p>\n" }, { "answer_id": 91090, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Prepared statements and parameter binding is always a good way to go.</p>\n\n<p>PEAR::MDB2 supports prepared statements, for example:</p>\n\n<pre><code>$db = MDB2::factory( $dsn );\n\n$types = array( 'integer', 'text' );\n$sth = $db-&gt;prepare( \"INSERT INTO table (ID,Text) (?,?)\", $types );\nif( PEAR::isError( $sth ) ) die( $sth-&gt;getMessage() );\n\n$data = array( 5, 'some text' );\n$result = $sth-&gt;execute( $data );\n$sth-&gt;free();\nif( PEAR::isError( $result ) ) die( $result-&gt;getMessage() );\n</code></pre>\n\n<p>This will only allow proper data and pre-set amount of variables to get into database.</p>\n\n<p>You of course should validate data before getting this far, but preparing statements is the final validation that should be done.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90517", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
When a user goes to my site, my script checks for 2 cookies which store the user id + part of the password, to automatically log them in. It's possible to edit the contents of cookies via a cookie editor, so I guess it's possible to add some malicious content to a written cookie? Should I add `mysql_real_escape_string` (or something else) to all my cookie calls or is there some kind of built in procedure that will not allow this to happen?
What you *really* need to do is not send these cookie values that are hackable in the first place. Instead, why not hash the username and password and a (secret) salt and set that as the cookie value? i.e.: ``` define('COOKIE_SALT', 'secretblahblahlkdsfklj'); $cookie_value = sha1($username.$password.COOKIE_SALT); ``` Then you know the cookie value is always going to be a 40-character hexidecimal string, and can compare the value the user sends back with whatever's in the database to decide whether they're valid or not: ``` if ($user_cookie_value == sha1($username_from_db.$password_drom_db.COOKIE_SALT)) { # valid } else { #not valid } ``` `mysql_real_escape_string` makes an additional hit to the database, BTW (a lot of people don't realize it requires a DB connection and queries MySQL). The best way to do what you want if you can't change your app and insist on using hackable cookie values is to use [prepared statements with bound parameters](http://devzone.zend.com/node/view/id/686).
90,553
<p>I've kind of backed myself into a corner here.</p> <p>I have a series of UserControls that inherit from a parent, which contains a couple of methods and events to simplify things so I don't have to write lines and lines of near-identical code. As you do. The parent contains no other controls.</p> <p>What I want to do is just have one event handler, in the parent UserControl, which goes and does stuff that only the parent control can do (that is, conditionally calling an event, as the event's defined in the parent). I'd then hook up this event handler to all my input boxes in my child controls, and the child controls would sort out the task of parsing the input and telling the parent control whether to throw that event. Nice and clean, no repetitive, copy-paste code (which for me <em>always</em> results in a bug).</p> <p>Here's my question. Visual Studio thinks I'm being too clever by half, and warns me that "the method 'CheckReadiness' [the event handler in the parent] cannot be the method for an event because a class this class derives from already defines the method." Yes, Visual Studio, <em>that's the point</em>. I <em>want</em> to have an event handler that only handles events thrown by child classes, and its only job is to enable me to hook up the children without having to write a single line of code. I don't need those extra handlers - all the functionality I need is naturally called as the children process the user input.</p> <p>I'm not sure why Visual Studio has started complaining about this now (as it let me do it before), and I'm not sure how to make it go away. Preferably, I'd like to do it without having to define a method that just calls CheckReadiness. What's causing this warning, what's causing it to come up now when it didn't an hour ago, and how can I make it go away without resorting to making little handlers in all the child classes?</p>
[ { "answer_id": 90566, "author": "Jon Limjap", "author_id": 372, "author_profile": "https://Stackoverflow.com/users/372", "pm_score": 0, "selected": false, "text": "<p>If your event is already defined in your parent class, you do not need to rewire it again in your child class. That will cause the event to fire twice.</p>\n\n<p>Do verify if this is what is happening. HTH :)</p>\n" }, { "answer_id": 90577, "author": "Dario Solera", "author_id": 16026, "author_profile": "https://Stackoverflow.com/users/16026", "pm_score": 0, "selected": false, "text": "<p>This article on MSDN should be a good starting points: <a href=\"http://msdn.microsoft.com/en-us/library/aa290043(VS.71).aspx\" rel=\"nofollow noreferrer\">Overriding Event Handlers with Visual Basic .NET</a>. Take a look at the <em>How the Handles Clause Can Cause Problems in the Derived Class</em> section.</p>\n" }, { "answer_id": 90594, "author": "Phil Wright", "author_id": 6276, "author_profile": "https://Stackoverflow.com/users/6276", "pm_score": 0, "selected": false, "text": "<p>Why not declare the method as virtual in the parent class and then you can override it in the derived classes to add extra functionality?</p>\n" }, { "answer_id": 90606, "author": "TK.", "author_id": 1816, "author_profile": "https://Stackoverflow.com/users/1816", "pm_score": 4, "selected": true, "text": "<p>Declare the parent method virtual, override it in the child classes and call</p>\n\n<pre><code>base.checkReadyness(sender, e);\n</code></pre>\n\n<p>(or derevation thereof) from within the child class. This allows for future design evolution say if you want to do some specific error checking code before calling the parent event handler. You might not need to write millions of event handlers like this for each control, you could just write one, hook all the controls to this event handler which in turn calls the parent's event handler. </p>\n\n<p>One thing that I have noted is that if all this code is being placed within a dll, then you might experience a performance hit trying to call an event handler from within a dll.</p>\n" }, { "answer_id": 90647, "author": "ima", "author_id": 5733, "author_profile": "https://Stackoverflow.com/users/5733", "pm_score": 0, "selected": false, "text": "<p>Forget that it's an event handler and just do proper regular method override in child class. </p>\n" }, { "answer_id": 565685, "author": "MrCranky", "author_id": 68430, "author_profile": "https://Stackoverflow.com/users/68430", "pm_score": 2, "selected": false, "text": "<p>I've just come across this one as well, I agree that it feels like you're doing everything correctly. Declaring the method virtual is a work-around at best, not a solution.</p>\n\n<p>What is being done is valid - a control which only exists in the derived class, and the derived class is attaching an event handler to one of that control's events. The fact that the method which is handling the event is defined in the base class is neither here nor there, it is available at the point of binding to the event. The event isn't being attached to twice or anything silly like that, it's simply a matter of where the method which handles the event is defined.</p>\n\n<p>Most definitely it is not a virtual method - I don't want the method to be overridable by a derived class. Very frustrating, and in my opinion, a bug in dev-studio.</p>\n" }, { "answer_id": 9621344, "author": "Steve Rehling", "author_id": 858533, "author_profile": "https://Stackoverflow.com/users/858533", "pm_score": 1, "selected": false, "text": "<p>I've just run into the exact problem Merus first raised and, like others who posted responses, I'm not at all clear why VS (I'm now using Visual C# 2010 Express) objects to having the event handler defined in the base class. The reason I'm posting a response is that in the process of getting around the problem by making the base class code a protected method that the derived classes simply invoke in their (essentially empty) event handlers, I did a refactor rename of the base class method and noticed that the VS designer stopped complaining. That is, it renamed the event handler registration (so it no longer followed the VS designer's convention of naming event handlers with ControlName_EventName), and that seemed to satisfy it. When I then tried to register the (now renamed) base event handler against derived class controls by entering the name in the appropriate VS event, the designer created a new event handler in the derived class which I then deleted, leaving the derived class control registered to the base class (event handler) method. Net, as you would expect, C# finds what we want to do legit. It's only the VS designer that doesn't like it when you following the designer's event handler naming convention. I don't see the need for the designer to work that way. Anywho, time to carry on.</p>\n" }, { "answer_id": 11704494, "author": "Bolek", "author_id": 1524524, "author_profile": "https://Stackoverflow.com/users/1524524", "pm_score": 0, "selected": false, "text": "<p>Here's what I did to get base methods called in several similar looking forms, each one of them having a few extra features to the common ones:</p>\n\n<pre><code> protected override void OnLoad(EventArgs e)\n {\n try\n {\n this.SuspendLayout();\n base.OnLoad(e);\n\n foreach (Control ctrl in Controls)\n {\n Button btn = ctrl as Button;\n if (btn == null) continue;\n\n if (string.Equals(btn.Name, \"btnAdd\", StringComparison.Ordinal))\n btn.Click += new EventHandler(btnAdd_Click);\n else if (string.Equals(btn.Name, \"btnEdit\", StringComparison.Ordinal))\n btn.Click += new EventHandler(btnEdit_Click);\n else if (string.Equals(btn.Name, \"btnDelete\", StringComparison.Ordinal))\n btn.Click += new EventHandler(btnDelete_Click);\n else if (string.Equals(btn.Name, \"btnPrint\", StringComparison.Ordinal))\n btn.Click += new EventHandler(btnPrint_Click);\n else if (string.Equals(btn.Name, \"btnExport\", StringComparison.Ordinal))\n btn.Click += new EventHandler(btnExport_Click);\n }\n</code></pre>\n\n<p>The chance of an omission of using the right fixed button name looks the same to me as the chance of not wiring the inherited handler manually. </p>\n\n<p>Note that you may need to test for this.DesignMode so that you skip the code in VS Designer at all, but it works fine for me even without the check.</p>\n" }, { "answer_id": 37685569, "author": "user6436572", "author_id": 6436572, "author_profile": "https://Stackoverflow.com/users/6436572", "pm_score": 2, "selected": false, "text": "<p>I too have experienced this issue because in earlier versions of VS, you could \"inherit\" the event handlers. So the solution I found without having to override methods is simply to assign the event handler somewhere in the initialization phase of the form. In my case, done in the constructor (I'm sure OnLoad() would work as well):</p>\n\n<pre><code> public MyForm()\n {\n InitializeComponent();\n btnOK.Click += Ok_Click;\n }\n</code></pre>\n\n<p>...where the Ok_Click handler resides in the base form. Food for thought.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90553", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5133/" ]
I've kind of backed myself into a corner here. I have a series of UserControls that inherit from a parent, which contains a couple of methods and events to simplify things so I don't have to write lines and lines of near-identical code. As you do. The parent contains no other controls. What I want to do is just have one event handler, in the parent UserControl, which goes and does stuff that only the parent control can do (that is, conditionally calling an event, as the event's defined in the parent). I'd then hook up this event handler to all my input boxes in my child controls, and the child controls would sort out the task of parsing the input and telling the parent control whether to throw that event. Nice and clean, no repetitive, copy-paste code (which for me *always* results in a bug). Here's my question. Visual Studio thinks I'm being too clever by half, and warns me that "the method 'CheckReadiness' [the event handler in the parent] cannot be the method for an event because a class this class derives from already defines the method." Yes, Visual Studio, *that's the point*. I *want* to have an event handler that only handles events thrown by child classes, and its only job is to enable me to hook up the children without having to write a single line of code. I don't need those extra handlers - all the functionality I need is naturally called as the children process the user input. I'm not sure why Visual Studio has started complaining about this now (as it let me do it before), and I'm not sure how to make it go away. Preferably, I'd like to do it without having to define a method that just calls CheckReadiness. What's causing this warning, what's causing it to come up now when it didn't an hour ago, and how can I make it go away without resorting to making little handlers in all the child classes?
Declare the parent method virtual, override it in the child classes and call ``` base.checkReadyness(sender, e); ``` (or derevation thereof) from within the child class. This allows for future design evolution say if you want to do some specific error checking code before calling the parent event handler. You might not need to write millions of event handlers like this for each control, you could just write one, hook all the controls to this event handler which in turn calls the parent's event handler. One thing that I have noted is that if all this code is being placed within a dll, then you might experience a performance hit trying to call an event handler from within a dll.
90,578
<p>I've recently started developing applications for the Blackberry. Consequently, I've had to jump to Java-ME and learn that and its associated tools. The syntax is easy, but I keep having issues with various gotchas and the environment. </p> <p>For instance, something that surprised me and wasted a lot of time is absence of real properties on a class object (something I assumed all OOP languages had). There are many gotchas. I've been to various places where they compare Java syntax vs C#, but there don't seem to be any sites that tell of things to look out for when moving to Java. </p> <p>The environment is a whole other issue all together. The Blackberry IDE is simply horrible. The look reminds me Borland C++ for Windows 3.1 - it's that outdated. Some of the other issues included spotty intellisense, weak debugging, etc... Blackberry does have a beta of the Eclipse plugin, but without debugging support, it's just an editor with fancy refactoring tools.</p> <p>So, any advice on how to blend in to Java-ME?</p>
[ { "answer_id": 90601, "author": "Noel Grandin", "author_id": 6591, "author_profile": "https://Stackoverflow.com/users/6591", "pm_score": 2, "selected": false, "text": "<p>The short answer is - it's going to be annoying, but not difficult.</p>\n\n<p>Java and C# have all the same underlying concepts, and a lot of the libraries are very close in style, but you're going to keep bumping your head across various differences.</p>\n\n<p>If you're talking about class properties, Java has those. The syntax is </p>\n\n<pre><code>public class MyClass {\n public static int MY_CLASS_PROPERTY = 12;\n}\n</code></pre>\n\n<p>I would seriously suggest you get a better IDE. \nAny of Netbeans, Eclipse, IDEA, JBuider is going to make your transition a lot more pleasant.</p>\n" }, { "answer_id": 90655, "author": "Marcio Aguiar", "author_id": 4213, "author_profile": "https://Stackoverflow.com/users/4213", "pm_score": 7, "selected": true, "text": "<p>This <a href=\"http://crfdesign.net/programming/top-10-differences-between-java-and-c\" rel=\"noreferrer\">guy here</a> had to make the inverse transition. So he listed the top 10 differences of Java and C#. I'll take his topics and show how it is made in Java:</p>\n\n<h2>Gotcha #10 - Give me my standard output!</h2>\n\n<p>To print to the standard output in Java:</p>\n\n<pre><code>System.out.println(\"Hello\");\n</code></pre>\n\n<h2>Gotcha #9 - Namespaces == Freedom</h2>\n\n<p>In Java you don't have the freedom of namespaces. The folder structure of your class must match the package name. For example, a class in the package <em>org.test</em> must be in the folder <em>org/test</em></p>\n\n<h2>Gotcha #8 - What happened to super?</h2>\n\n<p>In Java to refer to the superclass you use the reserved word <code>super</code> instead of <code>base</code></p>\n\n<h2>Gotcha #7 - Chaining constructors to a base constructor</h2>\n\n<p>You don't have this in Java. You have to call the constructor by yourself</p>\n\n<h2>Gotcha #6 - Dagnabit, how do I subclass an existing class?</h2>\n\n<p>To subclass a class in Java do this:</p>\n\n<pre><code>public class A extends B {\n}\n</code></pre>\n\n<p>That means class <code>A</code> is a subclass of class <code>B</code>. In C# would be <code>class A : B</code></p>\n\n<h2>Gotcha #5 - Why don’t constants remain constant?</h2>\n\n<p>To define a constant in Java use the keyword <code>final</code> instead of <code>const</code></p>\n\n<h2>Gotcha #4 - Where is <code>ArrayList</code>, <code>Vector</code> or <code>Hashtable</code>?</h2>\n\n<p>The most used data structures in java are <code>HashSet</code>, <code>ArrayList</code> and <code>HashMap</code>. They implement <code>Set</code>, <code>List</code> and <code>Map</code>. Of course, there is a bunch more. Read more about collections <a href=\"http://java.sun.com/docs/books/tutorial/collections/index.html\" rel=\"noreferrer\">here</a></p>\n\n<h2>Gotcha #3 - Of Accessors and Mutators (Getters and Setters)</h2>\n\n<p>You don't have the properties facility in Java. You have to declare the gets and sets methods for yourself. Of course, most IDEs can do that automatically.</p>\n\n<h2>Gotcha #2 - Can't I override!?</h2>\n\n<p>You don't have to declare a method <code>virtual</code> in Java. All methods - except those declared <code>final</code> - can be overridden in Java.</p>\n\n<h2>And the #1 gotcha…</h2>\n\n<p>In Java the primitive types <code>int</code>, <code>float</code>, <code>double</code>, <code>char</code> and <code>long</code> are not <code>Object</code>s like in C#. All of them have a respective object representation, like <code>Integer</code>, <code>Float</code>, <code>Double</code>, etc.</p>\n\n<p>That's it. Don't forget to see <a href=\"http://crfdesign.net/programming/top-10-differences-between-java-and-c\" rel=\"noreferrer\">the original link</a>, there's a more detailed discussion.</p>\n" }, { "answer_id": 91123, "author": "Tomer Gabel", "author_id": 11558, "author_profile": "https://Stackoverflow.com/users/11558", "pm_score": 5, "selected": false, "text": "<p>Java is not significantly different from C#. On a purely syntactic level, here are some pointers that may get you through the day:</p>\n\n<ol>\n<li><p>In Java you have two families of exceptions: <code>java.lang.Exception</code> and everything that derives from it, and <code>RuntimeException</code>. This is meaningful because in Java exceptions are <em>checked</em>; this means that in order to throw any non-runtime exception you also need to add a <code>throws</code> annotation to your method declaration. Consequently, any method using yours will have to catch that exception or declare that <em>it</em> also throws the same exception. A lot of exceptions you take for granted, such as <code>NullPointerException</code> or <code>IllegalArgumentException</code>, in fact derive from <code>RuntimeException</code> and you therefore don't need to declare them. Checked exceptions are a point of contention between two disciplines, so I'd recommend you try them out for yourself and see if it helps or annoys you. On a personal level, I think checked exceptions improve code factoring and robustness significantly.</p></li>\n<li><p>Although Java has supported autoboxing for quite a while, there are still quite a few differences between the C# and Java implementations that you should be aware of. Whereas in C# you can interchangeably use <code>int</code> as both a value type and reference type, in Java they're literally not the same type: you get the primitive value type <code>int</code> and the library reference type <code>java.lang.Integer</code>. This manifests in two common ways: you can't use the value types as a generic type parameter (so you'll use <code>ArrayList&lt;Integer&gt;</code> instead of <code>ArrayList&lt;int&gt;</code>), and the utility methods (such as <code>parse</code> or <code>toString</code>) are statically implemented in the reference type (so it's not <code>int a; a.toString();</code> but rather <code>int a; Integer.toString( a );</code>).</p></li>\n<li><p>Java has two distinct types of nested classes, C# only has one. In Java a static class that is not declared with the <code>static</code> modifier is called an <em>inner class</em>, and has implicit access to the enclosing class's instance. This is an important point because, unlike C#, Java has no concept of delegates, and inner classes are very often use to achieve the same result with relatively little syntactic pain.</p></li>\n<li><p>Generics in Java are implemented in a radically different manner than C#; when generics were developed for Java it was decided that the changes will be purely syntactic with no runtime support, in order to retain backwards compatibility with older VMs. With no direct generics support in the runtime, Java implements generics using a technique called <a href=\"http://download.oracle.com/javase/tutorial/java/generics/erasure.html\" rel=\"noreferrer\">type erasure</a>. There are quite a few disadvantages to type erasure over the C# implementation of generics, but the most important point to take from this is that <em>parameterized generic types in Java do not have different runtime types</em>. In other words, after compilation the types <code>ArrayList&lt;Integer&gt;</code> and <code>ArrayList&lt;String&gt;</code> are <em>equivalent</em>. If you work heavily with generics you'll encounter these differences a lot sooner than you'd think.</p></li>\n</ol>\n\n<p>There are, in my opinion, the three hardest aspects of the language for a C# developer to grok. Other than that there's the development tools and class library.</p>\n\n<ol>\n<li><p>In Java, there is a direct correlation between the package (namespace), class name and file name. Under a common root directory, the classes <code>com.example.SomeClass</code> and <code>org.apache.SomeOtherClass</code> will literally be found in <code>com/example/SomeClass.class</code> and <code>org/apache/SomeOtherClass.class</code> respectively. Be wary of trying to define multiple classes in a single Java file (it's possible for private classes, but not recommended), and stick to this directory structure until you're more comfortable with the development environment.</p></li>\n<li><p>In Java you have the concepts of class-path and class-loader which do not easily map to C# (there are rough equivalents which are not in common use by most .NET developers). Classpath tells the Java VM where libraries and classes are to be found (both yours and the system's shared libraries!), and you can think of class loaders as the context in which your types live. Class loaders are used to load types (class files) from various locations (local disk, internet, resource files, whatnot) but also constrain access to those files. For instance, an application server such as Tomcat will have a class loader for each registered application, or context; this means that a static class in application A will not be the same as a static class in application B, even if they have the same name and even if they share the same codebase. AppDomains provide somewhat similar functionality in .NET.</p></li>\n<li><p>The Java class library is similar to the BCL; a lot of the differences are cosmetic, but it's enough to get you running for the documentation (and/or Google) over and over again. Unfortunately I don't think there's anything to do here — you'll just build familiarity with the libraries as you go.</p></li>\n</ol>\n\n<p>Bottom line: the only way to grok Java is to use it. The learning curve isn't steep, but prepare to be surprised and frustrated quite often over the first two or three months of use.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9382/" ]
I've recently started developing applications for the Blackberry. Consequently, I've had to jump to Java-ME and learn that and its associated tools. The syntax is easy, but I keep having issues with various gotchas and the environment. For instance, something that surprised me and wasted a lot of time is absence of real properties on a class object (something I assumed all OOP languages had). There are many gotchas. I've been to various places where they compare Java syntax vs C#, but there don't seem to be any sites that tell of things to look out for when moving to Java. The environment is a whole other issue all together. The Blackberry IDE is simply horrible. The look reminds me Borland C++ for Windows 3.1 - it's that outdated. Some of the other issues included spotty intellisense, weak debugging, etc... Blackberry does have a beta of the Eclipse plugin, but without debugging support, it's just an editor with fancy refactoring tools. So, any advice on how to blend in to Java-ME?
This [guy here](http://crfdesign.net/programming/top-10-differences-between-java-and-c) had to make the inverse transition. So he listed the top 10 differences of Java and C#. I'll take his topics and show how it is made in Java: Gotcha #10 - Give me my standard output! ---------------------------------------- To print to the standard output in Java: ``` System.out.println("Hello"); ``` Gotcha #9 - Namespaces == Freedom --------------------------------- In Java you don't have the freedom of namespaces. The folder structure of your class must match the package name. For example, a class in the package *org.test* must be in the folder *org/test* Gotcha #8 - What happened to super? ----------------------------------- In Java to refer to the superclass you use the reserved word `super` instead of `base` Gotcha #7 - Chaining constructors to a base constructor ------------------------------------------------------- You don't have this in Java. You have to call the constructor by yourself Gotcha #6 - Dagnabit, how do I subclass an existing class? ---------------------------------------------------------- To subclass a class in Java do this: ``` public class A extends B { } ``` That means class `A` is a subclass of class `B`. In C# would be `class A : B` Gotcha #5 - Why don’t constants remain constant? ------------------------------------------------ To define a constant in Java use the keyword `final` instead of `const` Gotcha #4 - Where is `ArrayList`, `Vector` or `Hashtable`? ---------------------------------------------------------- The most used data structures in java are `HashSet`, `ArrayList` and `HashMap`. They implement `Set`, `List` and `Map`. Of course, there is a bunch more. Read more about collections [here](http://java.sun.com/docs/books/tutorial/collections/index.html) Gotcha #3 - Of Accessors and Mutators (Getters and Setters) ----------------------------------------------------------- You don't have the properties facility in Java. You have to declare the gets and sets methods for yourself. Of course, most IDEs can do that automatically. Gotcha #2 - Can't I override!? ------------------------------ You don't have to declare a method `virtual` in Java. All methods - except those declared `final` - can be overridden in Java. And the #1 gotcha… ------------------ In Java the primitive types `int`, `float`, `double`, `char` and `long` are not `Object`s like in C#. All of them have a respective object representation, like `Integer`, `Float`, `Double`, etc. That's it. Don't forget to see [the original link](http://crfdesign.net/programming/top-10-differences-between-java-and-c), there's a more detailed discussion.
90,579
<p>How to center text over an image in a table cell using javascript, css, and/or html?</p> <p>I have an HTML table containing images - all the same size - and I want to center a text label over each image. The text in the labels may vary in size. Horizontal centering is not difficult, but vertical centering is.</p> <p>ADDENDUM: i did end up having to use javascript to center the text reliably using a fixed-size div with absolute positioning; i just could not get it to work any other way</p>
[ { "answer_id": 90596, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 5, "selected": true, "text": "<p>you could try putting the images in the background.</p>\n\n<pre><code>&lt;table&gt;\n &lt;tr&gt;\n &lt;td style=\"background: url(myImg.jpg) no-repeat; vertical-align: middle; text-align: center\"&gt;\n Here is my text\n &lt;/td&gt;\n &lt;/tr&gt;\n&lt;/table&gt;\n</code></pre>\n\n<p>You'll just need to set the height and width on the cell and that should be it.</p>\n" }, { "answer_id": 90608, "author": "Dario Solera", "author_id": 16026, "author_profile": "https://Stackoverflow.com/users/16026", "pm_score": 0, "selected": false, "text": "<p>I would set the images as the cells' background via CSS, set the cells' size to the proper fixed value (again via CSS), and then insert the text label as the cell content. By default, the content of table cells is centered vertically, so I think you don't have to worry about it. Again, vertical and horizontal alignment can be easily set via CSS. This approach works because I applied it a lot of times.</p>\n\n<p>Another way would be to insert both the image and text in the table cells, wrapping the text in a DIV element and playing with its CSS properties (relative position and margins), but this is a bit tricky in my opinion.</p>\n" }, { "answer_id": 90625, "author": "sdkpoly", "author_id": 15640, "author_profile": "https://Stackoverflow.com/users/15640", "pm_score": 0, "selected": false, "text": "<p>You can use TD's option \"valign\" and it can be top, bottom or center... But as far as I know cell contents are centered vertically by default, so probably your CSS makes them show with bottom or top option.</p>\n\n<pre><code>&lt;TABLE&gt;&lt;TR valign=center&gt;\n &lt;TD align=center background=\"some image\"&gt; image label &lt;/TD&gt;\n&lt;/TR&gt;&lt;/TABLE&gt;\n</code></pre>\n" }, { "answer_id": 99848, "author": "Vincent McNabb", "author_id": 16299, "author_profile": "https://Stackoverflow.com/users/16299", "pm_score": 1, "selected": false, "text": "<p>There's no proper way of doing it in CSS (although there should be). But here's a method that works for me.</p>\n\n<p>CSS:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>#image1, #image1-text, #image1-container {\n overflow: hidden;\n height: 100px;\n width: 100px;\n}\n\n#image1 {\n top: -100px;\n position: relative;\n z-index: -1;\n}\n\n#image1-text {\n text-align: center;\n vertical-align: middle;\n display: table-cell;\n}\n</code></pre>\n\n<p>HTML:</p>\n\n<pre><code> &lt;div id=\"image1-container\"&gt;\n &lt;img src=\"image.jpeg\" id=\"image1\"&gt;\n &lt;div id=\"image1-text\"&gt;\n hello\n &lt;/div&gt;\n &lt;/div&gt;\n</code></pre>\n\n<p>The order of <code>image1</code> and <code>image1-text</code> in the container doesn't matter.</p>\n\n<p>It's a bit of a hack but it works anywhere, not just in a table. It doesn't properly work in IE however. It will display it at the top instead. But it works in FF, Safari and Chrome. Haven't tested in IE8.</p>\n\n<p>A hack for IE7 or less, which will only show 1 line, but it will be centred is to add the following inside the <code>&lt;head&gt;</code> tag:</p>\n\n<pre><code>&lt;!--[if lte IE 7]&gt;\n&lt;style&gt;\n #image1-text {\n line-height: 100px;\n }\n&lt;/style&gt;\n&lt;![endif]--&gt; \n</code></pre>\n" }, { "answer_id": 286324, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 0, "selected": false, "text": "<p>thanks everyone for the suggestions. </p>\n\n<p>i did end up having to use javascript to center the text reliably using a fixed-size div with absolute positioning; i just could not get it to work any other way.</p>\n\n<p>i also had to generate the text divs with visibility hidden and have a javascript loop at the end of the page to make them visible and place them over the appropriate table cell</p>\n\n<p>there are some serious holes in the layout capabilities of css/html, hopefully these will be addressed in future versions ;-)</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90579", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9345/" ]
How to center text over an image in a table cell using javascript, css, and/or html? I have an HTML table containing images - all the same size - and I want to center a text label over each image. The text in the labels may vary in size. Horizontal centering is not difficult, but vertical centering is. ADDENDUM: i did end up having to use javascript to center the text reliably using a fixed-size div with absolute positioning; i just could not get it to work any other way
you could try putting the images in the background. ``` <table> <tr> <td style="background: url(myImg.jpg) no-repeat; vertical-align: middle; text-align: center"> Here is my text </td> </tr> </table> ``` You'll just need to set the height and width on the cell and that should be it.
90,595
<p>How to implement a web page that scales when the browser window is resized?</p> <p>I can lay out the elements of the page using either a table or CSS float sections, but i want the display to rescale when the browser window is resized</p> <p>i have a working solution using AJAX PRO and DIVs with overflow:auto and an onwindowresize hook, but it is cumbersome. Is there a better way?</p> <ul> <li><p>thanks everyone for the answers so far, i intend to try them all (or at least most of them) and then choose the best solution as the answer to this thread</p></li> <li><p>using CSS and percentages seems to work best, which is what I did in the original solution; using a visibility:hidden div set to 100% by 100% gives a way to measure the client area of the window [difficult in IE otherwise], and an onwindowresize javascript function lets the AJAXPRO methods kick in when the window is resized to redraw the layout-cell contents at the new resolution</p></li> </ul> <p>EDIT: my apologies for not being completely clear; i needed a 'liquid layout' where the major elements ('panes') would scale as the browser window was resized. I found that i had to use an AJAX call to re-display the 'pane' contents after resizing, and keep overflow:auto turned on to avoid scrolling</p>
[ { "answer_id": 90603, "author": "Fire Lancer", "author_id": 6266, "author_profile": "https://Stackoverflow.com/users/6266", "pm_score": 5, "selected": true, "text": "<p>instead of using in css say \"width: 200px\", use stuff like \"width: 50%\"</p>\n\n<p>This makes it use 50% of whatever it's in, so in the case of:</p>\n\n<pre><code>&lt;body&gt;\n &lt;div style=\"width:50%\"&gt;\n &lt;!--some stuff--&gt;\n &lt;/div&gt;\n&lt;/body&gt;\n</code></pre>\n\n<p>The div will now always take up half the window horizontaly.</p>\n" }, { "answer_id": 90611, "author": "Loren Segal", "author_id": 6436, "author_profile": "https://Stackoverflow.com/users/6436", "pm_score": 3, "selected": false, "text": "<p>Unless you have some specific requirement here I'm not sure why JS is needed here. Tabular layouts are the easy (and archaic) way to make fluid layouts in html, but div layouts with css allow for fluid layouts as well, see <a href=\"http://www.glish.com/css/2.asp\" rel=\"noreferrer\">http://www.glish.com/css/2.asp</a></p>\n" }, { "answer_id": 90641, "author": "Ola Karlsson", "author_id": 10696, "author_profile": "https://Stackoverflow.com/users/10696", "pm_score": 3, "selected": false, "text": "<p>Yep sound like you want to look at a fluid CSS layout.\nFor resources on this, just google fluid CSS layout, should give you a whole lot of things to check.\nAlso have a look at <a href=\"https://stackoverflow.com/questions/61250/divs-vs-tables-or-css-vs-being-stupid\">this previous question</a> for some good pointers.</p>\n" }, { "answer_id": 90645, "author": "Zach", "author_id": 9128, "author_profile": "https://Stackoverflow.com/users/9128", "pm_score": 2, "selected": false, "text": "<p>Something else to consider is that JavaScript won't update continuously while the window is being resized, so there will be a noticeable delay/choppiness. With a fluid CSS layout, screen elements will update almost instantly for a seamless transition.</p>\n" }, { "answer_id": 90651, "author": "Peter Kelley", "author_id": 14893, "author_profile": "https://Stackoverflow.com/users/14893", "pm_score": 2, "selected": false, "text": "<p>The best way that I have seen to do this is to use the <a href=\"http://developer.yahoo.com/yui/\" rel=\"nofollow noreferrer\">YUI</a> CSS Tools and then use percentages for everything. <a href=\"http://developer.yahoo.com/yui/grids/\" rel=\"nofollow noreferrer\">YUI Grids</a> allow for various fixed width or fluid layouts with column sizes specified as fractions of the available space. There is a <a href=\"http://developer.yahoo.com/yui/grids/builder/\" rel=\"nofollow noreferrer\">YUI Grids Builder</a> to help lay things out. <a href=\"http://developer.yahoo.com/yui/fonts/\" rel=\"nofollow noreferrer\">YUI Fonts</a> gives you good font size controls. There are some nice <a href=\"http://yuiblog.com/assets/pdf/cheatsheets/css.pdf\" rel=\"nofollow noreferrer\">cheat sheets</a> available that show you how to lay things out and useful things like what percentage to specify for a font size of so many pixels. </p>\n\n<p>This gets you scaling of the positioning but scaling of the entire site, including font sizes, when the browser window resizes is a bit trickier. I'm thinking that you are going to have to write some sort of browser plugin for this which means that your solution will be non portable. If you are on an intranet this isn't too bad as you can control the browser on each client but if you are wanting a site that is available on the internet then you may need to rethink your UI.</p>\n" }, { "answer_id": 90654, "author": "Justin Bozonier", "author_id": 9401, "author_profile": "https://Stackoverflow.com/users/9401", "pm_score": 3, "selected": false, "text": "<p>It really depends on the web page you are implementing. As a general rule you're going to want 100% CSS. When sizing elements that will contain text remember to gravitate towards text oriented sizes such as em, ex, and not px.</p>\n\n<p>Floats are dangerous if you're new to CSS. I'm not new and they are still somewhat baffling to me. Avoid them where possible. Normally, you just need to modify the display property of the div or element you're working on anyway.</p>\n\n<p>If you do all of this and scour the web where you have additional difficulties you'll not only have pages that resize when the browser does so, but also pages that can be zoomed in and out by resizing text. Basically, do it right and the design is unbreakable. I've seen it done on complex layouts but it is a lot of work, as much effort as programming the web page in certain instances.</p>\n\n<p>I'm not sure who you're doing this site for (fun, profit, both) but I'd recommend you think long and hard about how you balance out the CSS purity with a few hacks here and there to help increase your efficiency. Does your web site have a business need to be 100% accessible? No? Then screw it. Do what you need to do to make your money first, then go hog wild with your passion and do anything extra you have time for.</p>\n" }, { "answer_id": 90696, "author": "Florian", "author_id": 12336, "author_profile": "https://Stackoverflow.com/users/12336", "pm_score": 1, "selected": false, "text": "<p>After trying a solution by the book I got stuck with incompatibility's in either Firefox or IE. So I did some tinkering and came up with this CSS. As you can see, the margins are half of the desired size and negative.</p>\n\n<pre><code>&lt;head&gt;&lt;title&gt;Centered&lt;/title&gt;\n&lt;style type=\"text/css\"&gt;\nbody { \n background-position: center center;\n border: thin solid #000000;\n height: 300px;\n width: 600px;\n position: absolute;\n left: 50%;\n top: 50%;\n margin-top: -150px;\n margin-right: auto;\n margin-bottom: auto;\n margin-left: -300px;\n }\n&lt;/style&gt;&lt;/head&gt; \n</code></pre>\n\n<p>Hope that helps</p>\n" }, { "answer_id": 118965, "author": "stalepretzel", "author_id": 1615, "author_profile": "https://Stackoverflow.com/users/1615", "pm_score": 1, "selected": false, "text": "<p>Use percentages! Say you have a \"main pane\" on which all your page's content lies. You want it to be centered in the window, always, and 80% of the width of the window.</p>\n\n<p>Simply do this:<br />\n #centerpane{\n margin: auto;\n width: 80%;\n }</p>\n\n<p>Tada!</p>\n" }, { "answer_id": 181215, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 1, "selected": false, "text": "<p>Thanks for all of the suggestions! It looks like the ugly stuff i had to do was necessary. The following works (on my machine, anyway) in IE and FireFox. I may make an article out of this for CodeProject.com later ;-)</p>\n\n<p>This javascript goes in the &lt;head&gt; section:</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\nvar tmout = null;\nvar mustReload = false;\n\nfunction Resizing()\n{\n if (tmout != null)\n {\n clearTimeout(tmout);\n }\n tmout = setTimeout(RefreshAll,300);\n}\nfunction Reload()\n{\n document.location.href = document.location.href;\n}\n//IE fires the window's onresize event when the client area \n//expands or contracts, which causes an infinite loop.\n//the way around this is a hidden div set to 100% of \n//height and width, with a guard around the resize event \n//handler to see if the _window_ size really changed\nvar windowHeight;\nvar windowWidth;\nwindow.onresize = null;\nwindow.onresize = function()\n{\n var backdropDiv = document.getElementById(\"divBackdrop\");\n if (windowHeight != backdropDiv.offsetHeight ||\n windowWidth != backdropDiv.offsetWidth)\n {\n //if screen is shrinking, must reload to get correct sizes\n if (windowHeight != backdropDiv.offsetHeight ||\n windowWidth != backdropDiv.offsetWidth)\n {\n mustReload = true;\n }\n else\n {\n mustReload = mustReload || false;\n }\n windowHeight = backdropDiv.offsetHeight;\n windowWidth = backdropDiv.offsetWidth;\n Resizing();\n }\n}\n&lt;/script&gt;\n</code></pre>\n\n<p>the &lt;body&gt; starts off like this:</p>\n\n<pre><code>&lt;body onload=\"RefreshAll();\"&gt;\n &lt;div id=\"divBackdrop\" \n style=\"width:100%; clear:both; height: 100%; margin: 0; \n padding: 0; position:absolute; top:0px; left:0px; \n visibility:hidden; z-index:0;\"&gt;\n &lt;/div&gt;\n</code></pre>\n\n<p>the DIVs float left for the layout. I had to set the height and width to percentages just shy of the full amount (e.g., 99.99%, 59.99%, 39.99%) to keep the floats from wrapping, probably due to the borders on the DIVs.</p>\n\n<p>Finally, after the content section, another javascript block to manage the refreshing:</p>\n\n<pre><code>var isWorking = false;\nvar currentEntity = &lt;%=currentEntityId %&gt;;\n\n//try to detect a bad back-button usage;\n//if the current entity id does not match the querystring \n//parameter entityid=###\nif (location.search != null &amp;&amp; location.search.indexOf(\"&amp;entityid=\") &gt; 0)\n{\n var urlId = location.search.substring(\n location.search.indexOf(\"&amp;entityid=\")+10);\n if (urlId.indexOf(\"&amp;\") &gt; 0)\n {\n urlId = urlId.substring(0,urlId.indexOf(\"&amp;\"));\n }\n if (currentEntity != urlId)\n {\n mustReload = true;\n }\n}\n//a friendly please wait... hidden div\nvar pleaseWaitDiv = document.getElementById(\"divPleaseWait\");\n//an example content div being refreshed via AJAX PRO\nvar contentDiv = document.getElementById(\"contentDiv\");\n\n//synchronous refresh of content\nfunction RefreshAll()\n{\n if (isWorking) { return; } //no infinite recursion please!\n\n isWorking = true;\n pleaseWaitDiv.style.visibility = \"visible\";\n\n if (mustReload)\n {\n Reload();\n }\n else\n {\n contentDiv.innerHTML = NAMESPACE.REFRESH_METHOD(\n (currentEntity, contentDiv.offsetWidth, \n contentDiv.offsetHeight).value;\n }\n\n pleaseWaitDiv.style.visibility = \"hidden\";\n isWorking = false;\n if (tmout != null)\n {\n clearTimeout(tmout);\n }\n}\n\nvar tmout2 = null;\nvar refreshInterval = 60000;\n\n//periodic synchronous refresh of all content\nfunction Refreshing()\n{\n RefreshAll();\n if (tmout2 != null)\n {\n clearTimeout(tmout2);\n tmout2 = setTimeout(Refreshing,refreshInterval);\n }\n}\n\n//start periodic refresh of content\ntmout2 = setTimeout(Refreshing,refreshInterval);\n\n//clean up\nwindow.onunload = function() \n{\n isWorking = true;\n if (tmout != null)\n {\n clearTimeout(tmout);\n tmout = null;\n }\n if (tmout2 != null)\n {\n clearTimeout(tmout2);\n tmout2 = null;\n }\n</code></pre>\n\n<p>ugly, but it works - which i guess it what really matters ;-)</p>\n" }, { "answer_id": 286358, "author": "Andy Ford", "author_id": 17252, "author_profile": "https://Stackoverflow.com/users/17252", "pm_score": 1, "selected": false, "text": "<p>use ems. <a href=\"http://jontangerine.com/\" rel=\"nofollow noreferrer\">jontangerine.com</a> and <a href=\"http://simplebits.com/\" rel=\"nofollow noreferrer\">simplebits.com</a> are both amazing examples. Further reading - <a href=\"http://jontangerine.com/log/2007/09/the-incredible-em-and-elastic-layouts-with-css\" rel=\"nofollow noreferrer\">The Incredible Em &amp; Elastic Layouts with CSS by Jon Tan</a></p>\n" }, { "answer_id": 2160019, "author": "Sphvn", "author_id": 261564, "author_profile": "https://Stackoverflow.com/users/261564", "pm_score": 0, "selected": false, "text": "<p>&lt; body onresize=\"resizeWindow()\" onload=\"resizeWindow()\" >\nPAGE\n&lt; /body > </p>\n\n<p></p>\n\n<pre><code> /**** Page Rescaling Function ****/\n\n function resizeWindow() \n {\n var windowHeight = getWindowHeight();\n var windowWidth = getWindowWidth();\n\n document.getElementById(\"content\").style.height = (windowHeight - 4) + \"px\";\n }\n\n function getWindowHeight() \n {\n var windowHeight=0;\n if (typeof(window.innerHeight)=='number') \n {\n windowHeight = window.innerHeight;\n }\n else {\n if (document.documentElement &amp;&amp; document.documentElement.clientHeight) \n {\n windowHeight = document.documentElement.clientHeight;\n }\n else \n {\n if (document.body &amp;&amp; document.body.clientHeight) \n {\n windowHeight = document.body.clientHeight;\n }\n }\n }\n return windowHeight;\n }\n</code></pre>\n\n<p>The solution I'm currently working on needs a few changes as to width otherwise height works fine as of so far ^^</p>\n\n<p>-Ozaki</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90595", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9345/" ]
How to implement a web page that scales when the browser window is resized? I can lay out the elements of the page using either a table or CSS float sections, but i want the display to rescale when the browser window is resized i have a working solution using AJAX PRO and DIVs with overflow:auto and an onwindowresize hook, but it is cumbersome. Is there a better way? * thanks everyone for the answers so far, i intend to try them all (or at least most of them) and then choose the best solution as the answer to this thread * using CSS and percentages seems to work best, which is what I did in the original solution; using a visibility:hidden div set to 100% by 100% gives a way to measure the client area of the window [difficult in IE otherwise], and an onwindowresize javascript function lets the AJAXPRO methods kick in when the window is resized to redraw the layout-cell contents at the new resolution EDIT: my apologies for not being completely clear; i needed a 'liquid layout' where the major elements ('panes') would scale as the browser window was resized. I found that i had to use an AJAX call to re-display the 'pane' contents after resizing, and keep overflow:auto turned on to avoid scrolling
instead of using in css say "width: 200px", use stuff like "width: 50%" This makes it use 50% of whatever it's in, so in the case of: ``` <body> <div style="width:50%"> <!--some stuff--> </div> </body> ``` The div will now always take up half the window horizontaly.
90,657
<p>I'm trying to find a way to fake the result of a method called from within another method.</p> <p>I have a "LoadData" method which calls a separate helper to get some data and then it will transform it (I'm interested in testing the transformed result).</p> <p>So I have code like this:</p> <pre><code>public class MyClass(){ public void LoadData(){ SomeProperty = Helper.GetSomeData(); } public object SomeProperty {get;set;} } </code></pre> <p>I want to have a known result from the Helper.GetSomeData() method. Can I use a mocking framework (I've got fairly limited experience with Rhino Mocks but am open to anything) to force an expected result? If so, how?</p> <p>*Edit - yeah as expected I couldn't achieve the hack I wanted, I'll have to work out a better way to set up the data.</p>
[ { "answer_id": 90670, "author": "Kevin Pang", "author_id": 1574, "author_profile": "https://Stackoverflow.com/users/1574", "pm_score": 0, "selected": false, "text": "<p>Yes, a mocking framework is exactly what you're looking for. You can record / arrange how you want certain mocked out / stubbed classes to return.</p>\n\n<p>Rhino Mocks, Typemock, and Moq are all good options for doing this.</p>\n\n<p><a href=\"http://weblogs.asp.net/stephenwalther/archive/2008/03/22/tdd-introduction-to-rhino-mocks.aspx\" rel=\"nofollow noreferrer\">Steven Walther's post</a> on using Rhino Mocks helped me a lot when I first started playing with Rhino Mocks.</p>\n" }, { "answer_id": 90672, "author": "Dario Solera", "author_id": 16026, "author_profile": "https://Stackoverflow.com/users/16026", "pm_score": 3, "selected": true, "text": "<p>As far as I know, you should create an interface or a base abstract class for the Helper object. With Rhino Mocks you can then return the value you want.</p>\n\n<p>Alternatively, you can add an overload for LoadData that accepts as parameters the data that you normally retrieve from the Helper object. This might even be easier.</p>\n" }, { "answer_id": 90687, "author": "Marcio Aguiar", "author_id": 4213, "author_profile": "https://Stackoverflow.com/users/4213", "pm_score": 3, "selected": false, "text": "<p>You have a problem there. I don't know if thats a simplified scenario of your code, but if the Helper class is used that way, then your code is not testable. First, the Helper class is used directly, so you <strong>can't replace it with a mock</strong>. Second, you're calling a static method. I don't know about C#, but in Java you <strong>can't override static methods</strong>.</p>\n\n<p>You'll have to do some refactoring to be able to inject a mock object with a dummy GetSomeData() method.</p>\n\n<p>In this simplified version of your code is difficult to give you a straight answer. You have some options:</p>\n\n<ul>\n<li>Create an interface for the Helper class and provide a way for the client to inject the Helper implementation to the MyClass class. But if Helper is just really a utility class it doesn't make much sense.</li>\n<li>Create a protected method in MyClass called getSomeData and make it only call Helper.LoadSomeData. Then replace the call to Helper.LoadSomeData in LoadData with for getSomeData. Now you can mock the getSomeData method to return the dummy value.</li>\n</ul>\n\n<hr>\n\n<p><strong>Beware of simply creating an interface to Helper class</strong> and inject it via method. This can expose implementation details. Why a client should provide an implementation of a <strong>utility</strong> class to call a simple operation? This will increase the complexity of MyClass clients.</p>\n" }, { "answer_id": 90692, "author": "Fossmo", "author_id": 4093, "author_profile": "https://Stackoverflow.com/users/4093", "pm_score": 0, "selected": false, "text": "<p>I would try something like this:</p>\n\n<pre><code>public class MyClass(){\n public void LoadData(IHelper helper){\n SomeProperty = helper.GetSomeData();\n }\n</code></pre>\n\n<p>This way you can mock up the helper class using for example MOQ.</p>\n" }, { "answer_id": 90737, "author": "Justin Bozonier", "author_id": 9401, "author_profile": "https://Stackoverflow.com/users/9401", "pm_score": 3, "selected": false, "text": "<p>I would recommend converting what you have into something like this:</p>\n\n<pre><code>public class MyClass()\n{\n private IHelper _helper;\n\n public MyClass()\n {\n //Default constructor normal code would use.\n this._helper = new Helper();\n }\n\n public MyClass(IHelper helper)\n {\n if(helper == null)\n {\n throw new NullException(); //I forget the exact name but you get my drift ;)\n }\n this._helper = helper;\n }\n\n public void LoadData()\n {\n SomeProperty = this._helper.GetSomeData();\n }\n public object SomeProperty {get;set;}\n}\n</code></pre>\n\n<p>Now your class supports what is known as dependency injection. This allows you to inject the implementation of the helper class and it ensures that your class need only depend on the interface. When you mock this know you just create a mock that uses the IHelper interface and pass it in to the constructor and your class will use that as though it is the real Helper class.</p>\n\n<p>Now if you're stuck using the Helper class as a static class then I would suggest that you use a proxy/adapter pattern and wrap the static class with another class that supports the IHelper interface (that you will also need to create).</p>\n\n<p>If at some point you want to take this a step further you could completely remove the default Helper implementation from the revised class and use IoC (Inversion of Control) containers. If thiis is new to you though, I would recommend focusing first on the fundamentals of why all of this extra hassle is worth while (it is IMHO).</p>\n\n<p>Your unit tests will look something like this psuedo-code:</p>\n\n<pre><code>public Amazing_Mocking_Test()\n{\n //Mock object setup\n MockObject mockery = new MockObject();\n IHelper myMock = (IHelper)mockery.createMockObject&lt;IHelper&gt;();\n mockery.On(myMock).Expect(\"GetSomeData\").WithNoArguments().Return(Anything);\n\n //The actual test\n MyClass testClass = new MyClass(myMock);\n testClass.LoadData();\n\n //Ensure the mock had all of it's expectations met.\n mockery.VerifyExpectations();\n}\n</code></pre>\n\n<p>Feel free to comment if you have any questions. (By the way I have no clue if this code all works I just typed it in my browser, I'm mainly illustrating the concepts).</p>\n" }, { "answer_id": 98605, "author": "RoyOsherove", "author_id": 18426, "author_profile": "https://Stackoverflow.com/users/18426", "pm_score": 2, "selected": false, "text": "<p>You might want to look into Typemock Isolator, which can \"fake\" method calls without forcing you to refactor your code.\nI am a dev in that company, but the solution is viable if you would want to choose not to change your design (or forced not to change it for testability)\nit's at www.Typemock.com</p>\n\n<p>Roy\nblog: ISerializable.com</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11388/" ]
I'm trying to find a way to fake the result of a method called from within another method. I have a "LoadData" method which calls a separate helper to get some data and then it will transform it (I'm interested in testing the transformed result). So I have code like this: ``` public class MyClass(){ public void LoadData(){ SomeProperty = Helper.GetSomeData(); } public object SomeProperty {get;set;} } ``` I want to have a known result from the Helper.GetSomeData() method. Can I use a mocking framework (I've got fairly limited experience with Rhino Mocks but am open to anything) to force an expected result? If so, how? \*Edit - yeah as expected I couldn't achieve the hack I wanted, I'll have to work out a better way to set up the data.
As far as I know, you should create an interface or a base abstract class for the Helper object. With Rhino Mocks you can then return the value you want. Alternatively, you can add an overload for LoadData that accepts as parameters the data that you normally retrieve from the Helper object. This might even be easier.
90,682
<p>Is it possible to get a thread dump of a Java Web Start application? And if so, how?</p> <p>It would be nice if there were a simple solution, which would enable a non-developer (customer) to create a thread dump. Alternatively, is it possible to create a thread dump programmatically?</p> <p>In the Java Web Start Console I can get a list of threads by pressing 't' but stacktraces are not included.</p> <p>If answers require certain java versions, please say so.</p>
[ { "answer_id": 90711, "author": "Amir Arad", "author_id": 11813, "author_profile": "https://Stackoverflow.com/users/11813", "pm_score": 2, "selected": false, "text": "<p>Try</p>\n\n<pre><code>StackTraceElement[] stack = Thread.currentThread().getStackTrace();\n</code></pre>\n\n<p>Then you can iterate over the collection to show the top x stack elements you're interested in.</p>\n" }, { "answer_id": 90743, "author": "Asgeir S. Nilsen", "author_id": 16023, "author_profile": "https://Stackoverflow.com/users/16023", "pm_score": 2, "selected": false, "text": "<p>Recent JDKs (sadly not JREs) include tools like jstack which does such things. JVMs from version 5 include JMX extensions to get thread dumps, memory statistics, and much more. All java applications, including web start applications, have this functionality available.</p>\n\n<p>You would either need to have the JDK installed or to write a JMX client that does the same thing. Take a look at <a href=\"http://java.sun.com/javase/6/docs/technotes/guides/management/\" rel=\"nofollow noreferrer\">http://java.sun.com/javase/6/docs/technotes/guides/management/</a> to get more information.</p>\n" }, { "answer_id": 90794, "author": "Marcio Aguiar", "author_id": 4213, "author_profile": "https://Stackoverflow.com/users/4213", "pm_score": 0, "selected": false, "text": "<p>Since Java 5 you have the getStackTrace() method of Thread class. For prior versions you can do:</p>\n\n<pre><code>Thread.currentThread().dumpStack();\n</code></pre>\n\n<p>This will print the stack trace to System.out</p>\n" }, { "answer_id": 90796, "author": "ashirley", "author_id": 6950, "author_profile": "https://Stackoverflow.com/users/6950", "pm_score": 2, "selected": false, "text": "<p>Since 1.5 you can use <code>Thread.getAllStackTraces()</code> to get a <code>Map</code> to iterate over.</p>\n\n<p>The ideal output would be that produced from Ctrl-\\ (or Ctrl-Break or similar), but there doesn't seem to be a documented way of producing this. If you are willing to limit yourself to sun's JVM (or use reflection I suppose) you could have a dig around the <code>sun.*</code> packages and see if anything interesting shows up.</p>\n" }, { "answer_id": 91097, "author": "scotty", "author_id": 15925, "author_profile": "https://Stackoverflow.com/users/15925", "pm_score": 4, "selected": true, "text": "<p>In the console, press V rather than T:</p>\n\n<pre><code>t: dump thread list\nv: dump thread stack\n</code></pre>\n\n<p>This works under JDK6. Don't know about others.</p>\n\n<p>Alternative, under JDK5 (and possibly earlier) you can send a full stack trace of all threads to standard out:</p>\n\n<p><em>Under Windows:</em> type ctrl-break in the Java console.</p>\n\n<p><em>Under Unix:</em> <code>kill -3 &lt;java_process_id&gt;</code>\n(e.g. kill -3 5555). This will NOT kill your app.</p>\n\n<p>One other thing: As others say, you can get the stacks programatically via the <code>Thread</code> class but watch out for <code>Thread.getAllStackTraces()</code> prior to JDK6 as there's a memory leak.</p>\n\n<p><a href=\"http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6434648\" rel=\"noreferrer\">http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6434648</a></p>\n\n<p>Regards,</p>\n\n<p>scotty</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90682", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15646/" ]
Is it possible to get a thread dump of a Java Web Start application? And if so, how? It would be nice if there were a simple solution, which would enable a non-developer (customer) to create a thread dump. Alternatively, is it possible to create a thread dump programmatically? In the Java Web Start Console I can get a list of threads by pressing 't' but stacktraces are not included. If answers require certain java versions, please say so.
In the console, press V rather than T: ``` t: dump thread list v: dump thread stack ``` This works under JDK6. Don't know about others. Alternative, under JDK5 (and possibly earlier) you can send a full stack trace of all threads to standard out: *Under Windows:* type ctrl-break in the Java console. *Under Unix:* `kill -3 <java_process_id>` (e.g. kill -3 5555). This will NOT kill your app. One other thing: As others say, you can get the stacks programatically via the `Thread` class but watch out for `Thread.getAllStackTraces()` prior to JDK6 as there's a memory leak. <http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6434648> Regards, scotty
90,693
<p>I have tree control object created using CTreeCtrl MFC class. The tree control needs to support rename. When I left click on any of item in Tree the TVN_SELCHANGED event is called from which I can get the selected item of the tree as below : HTREEITEM h = m_moveListTree.GetSelectedItem(); CString s = m_moveListTree.GetItemText(h);</p> <p>However when I rightclick on any item in tree I do not get any TVN_SELCHANGED event and hence my selected item still remains the same from left click event. This is causing following problem : 1)User leftclicks on item A 2)user right clicks on item B and says rename 3)Since the selected item is still A the rename is applying for item A.</p> <p>Please help in solving problem.</p> <p>-Praveen</p>
[ { "answer_id": 90773, "author": "jussij", "author_id": 14738, "author_profile": "https://Stackoverflow.com/users/14738", "pm_score": 1, "selected": true, "text": "<p>I created my own MFC like home grown C++ GUI library on top of the Win32 API and looking at my code, this is how it handles that situation:</p>\n\n<pre><code>LRESULT xTreeCtrl::onRightClick(NMHDR *)\n{\n xPoint pt;\n\n //-- get the cursor at the time the mesage was posted\n DWORD dwPos = ::GetMessagePos();\n\n pt.x = GET_X_LPARAM(dwPos);\n pt.y = GET_Y_LPARAM (dwPos);\n\n //-- now convert to window co-ordinates\n pt.toWindow(this);\n\n //-- check for a hit\n HTREEITEM hItem = this-&gt;hitTest(pt);\n\n //-- select any item that was hit\n if ((int)hItem != -1) this-&gt;select(hItem);\n\n //-- leave the rest to default processing\n return 0;\n}\n</code></pre>\n\n<p>I suspect if you do something similar in the MFC right click or right button down events that will fix the problem.</p>\n\n<p>NOTE: The onRightClick code above is nothing more than the handler for the <strong>WM_NOTIFY</strong>, <strong>NM_RCLICK</strong> message.</p>\n" }, { "answer_id": 90779, "author": "Steffen", "author_id": 6919, "author_profile": "https://Stackoverflow.com/users/6919", "pm_score": 0, "selected": false, "text": "<p>Not sure how you popup the context menu, but you can use HitTest() to get from a point to a tree item. So you might use this in your right click handler.</p>\n\n<p>Don't forget that the context menu can also be activated by a key on reasonable modern keyboards. Then you probably want to use the selected item as target.</p>\n" }, { "answer_id": 90786, "author": "Roger Lipscombe", "author_id": 8446, "author_profile": "https://Stackoverflow.com/users/8446", "pm_score": 2, "selected": false, "text": "<p>This behaviour is by design -- right-clicking doesn't move the selection.</p>\n\n<p>For what you want, turn on the TVS_EDITLABELS style on the tree view. Then you handle the TVN_BEGINLABELEDIT and TVN_ENDLABELEDIT notifications.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90693", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have tree control object created using CTreeCtrl MFC class. The tree control needs to support rename. When I left click on any of item in Tree the TVN\_SELCHANGED event is called from which I can get the selected item of the tree as below : HTREEITEM h = m\_moveListTree.GetSelectedItem(); CString s = m\_moveListTree.GetItemText(h); However when I rightclick on any item in tree I do not get any TVN\_SELCHANGED event and hence my selected item still remains the same from left click event. This is causing following problem : 1)User leftclicks on item A 2)user right clicks on item B and says rename 3)Since the selected item is still A the rename is applying for item A. Please help in solving problem. -Praveen
I created my own MFC like home grown C++ GUI library on top of the Win32 API and looking at my code, this is how it handles that situation: ``` LRESULT xTreeCtrl::onRightClick(NMHDR *) { xPoint pt; //-- get the cursor at the time the mesage was posted DWORD dwPos = ::GetMessagePos(); pt.x = GET_X_LPARAM(dwPos); pt.y = GET_Y_LPARAM (dwPos); //-- now convert to window co-ordinates pt.toWindow(this); //-- check for a hit HTREEITEM hItem = this->hitTest(pt); //-- select any item that was hit if ((int)hItem != -1) this->select(hItem); //-- leave the rest to default processing return 0; } ``` I suspect if you do something similar in the MFC right click or right button down events that will fix the problem. NOTE: The onRightClick code above is nothing more than the handler for the **WM\_NOTIFY**, **NM\_RCLICK** message.
90,697
<p>How do I create a resource that I can reference and use in various parts of my program easily?</p> <p>My specific problem is that I have a NotifyIcon that I want to change the icon of depending on the state of the program. A common problem, but one I've been struggling with for a long time. </p>
[ { "answer_id": 90699, "author": "Matthew Scharley", "author_id": 15537, "author_profile": "https://Stackoverflow.com/users/15537", "pm_score": 9, "selected": true, "text": "<p>Well, after searching around and cobbling together various points from around StackOverflow (gee, I love this place already), most of the problems were already past this stage. I did manage to work out an answer to my problem though.</p>\n\n<p><strong>How to create a resource:</strong></p>\n\n<p>In my case, I want to create an icon. It's a similar process, no matter what type of data you want to add as a resource though.</p>\n\n<ul>\n<li>Right click the project you want to add a resource to. Do this in the Solution Explorer. Select the \"Properties\" option from the list.</li>\n<li>Click the \"Resources\" tab.</li>\n<li>The first button along the top of the bar will let you select the type of resource you want to add. It should start on string. We want to add an icon, so click on it and select \"Icons\" from the list of options.</li>\n<li>Next, move to the second button, \"Add Resource\". You can either add a new resource, or if you already have an icon already made, you can add that too. Follow the prompts for whichever option you choose.</li>\n<li>At this point, you can double click the newly added resource to edit it. Note, resources also show up in the Solution Explorer, and double clicking there is just as effective.</li>\n</ul>\n\n<p><strong>How to use a resource:</strong></p>\n\n<p>Great, so we have our new resource and we're itching to have those lovely changing icons... How do we do that? Well, lucky us, C# makes this exceedingly easy.</p>\n\n<p>There is a static class called <code>Properties.Resources</code> that gives you access to all your resources, so my code ended up being as simple as:</p>\n\n<pre><code>paused = !paused;\nif (paused)\n notifyIcon.Icon = Properties.Resources.RedIcon;\nelse\n notifyIcon.Icon = Properties.Resources.GreenIcon;\n</code></pre>\n\n<p>Done! Finished! Everything is simple when you know how, isn't it?</p>\n" }, { "answer_id": 90735, "author": "Chuck Conway", "author_id": 17360, "author_profile": "https://Stackoverflow.com/users/17360", "pm_score": 3, "selected": false, "text": "<p>The above method works well.</p>\n<p>Another method (I am assuming web here) is to create your page. Add controls to the page. Then while in design mode go to: <strong>Tools &gt; Generate Local Resource</strong>. A resource file will automatically appear in the solution with all the controls in the page mapped in the resource file.</p>\n<p>To create resources for other languages, append the 4 character language to the end of the file name, before the extension (<em>Account.aspx.en-US.resx, Account.aspx.es-ES.resx</em>...etc).</p>\n<p>To retrieve specific entries in the code-behind, simply call this method: <code>GetLocalResourceObject([resource entry key/name])</code>.</p>\n" }, { "answer_id": 6349063, "author": "Quinxy von Besiex", "author_id": 636189, "author_profile": "https://Stackoverflow.com/users/636189", "pm_score": 3, "selected": false, "text": "<p>The above didn't actually work for me as I had expected with Visual Studio 2010. It wouldn't let me access Properties.Resources, said it was inaccessible due to permission issues. I ultimately had to change the Persistence settings in the properties of the resource and then I found how to access it via the Resources.Designer.cs file, where it had an automatic getter that let me access the icon, via MyNamespace.Properties.Resources.NameFromAddingTheResource. That returns an object of type Icon, ready to just use.</p>\n" }, { "answer_id": 67958544, "author": "Wojciech", "author_id": 4348120, "author_profile": "https://Stackoverflow.com/users/4348120", "pm_score": 2, "selected": false, "text": "<p>Code posted by Matthew Scharley has a memory leak:</p>\n<pre><code>paused = !paused;\nif (paused)\n notifyIcon.Icon = Properties.Resources.RedIcon;\nelse\n notifyIcon.Icon = Properties.Resources.GreenIcon;\n</code></pre>\n<p>You should <code>Dispose()</code> notifyIcon.Icon before replacing it, because <code>Properties.Resources.SOME_ICON</code> creates a new <code>Icon</code> each time it is used.\nThis can be observed in the log, with this code:</p>\n<pre><code>Console.WriteLine(Properties.Resources.RedIcon.GetHashCode());\nConsole.WriteLine(Properties.Resources.RedIcon.GetHashCode());\nConsole.WriteLine(Properties.Resources.RedIcon.GetHashCode());\n</code></pre>\n<p>You will see 3 different Hash Codes in the log. This means these are different Objects.</p>\n<p>So, the simple fix will be:</p>\n<pre><code>paused = !paused;\nnotifyIcon.Icon?.Dispose();\nnotifyIcon.Icon = paused \n ? Properties.Resources.RedIcon;\n : Properties.Resources.GreenIcon;\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15537/" ]
How do I create a resource that I can reference and use in various parts of my program easily? My specific problem is that I have a NotifyIcon that I want to change the icon of depending on the state of the program. A common problem, but one I've been struggling with for a long time.
Well, after searching around and cobbling together various points from around StackOverflow (gee, I love this place already), most of the problems were already past this stage. I did manage to work out an answer to my problem though. **How to create a resource:** In my case, I want to create an icon. It's a similar process, no matter what type of data you want to add as a resource though. * Right click the project you want to add a resource to. Do this in the Solution Explorer. Select the "Properties" option from the list. * Click the "Resources" tab. * The first button along the top of the bar will let you select the type of resource you want to add. It should start on string. We want to add an icon, so click on it and select "Icons" from the list of options. * Next, move to the second button, "Add Resource". You can either add a new resource, or if you already have an icon already made, you can add that too. Follow the prompts for whichever option you choose. * At this point, you can double click the newly added resource to edit it. Note, resources also show up in the Solution Explorer, and double clicking there is just as effective. **How to use a resource:** Great, so we have our new resource and we're itching to have those lovely changing icons... How do we do that? Well, lucky us, C# makes this exceedingly easy. There is a static class called `Properties.Resources` that gives you access to all your resources, so my code ended up being as simple as: ``` paused = !paused; if (paused) notifyIcon.Icon = Properties.Resources.RedIcon; else notifyIcon.Icon = Properties.Resources.GreenIcon; ``` Done! Finished! Everything is simple when you know how, isn't it?
90,751
<p>Do C#/.NET floating point operations differ in precision between debug mode and release mode?</p>
[ { "answer_id": 90783, "author": "Dark Shikari", "author_id": 11206, "author_profile": "https://Stackoverflow.com/users/11206", "pm_score": 2, "selected": false, "text": "<p>In fact, they may differ if debug mode uses the x87 FPU and release mode uses SSE for float-ops.</p>\n" }, { "answer_id": 90815, "author": "Dark Shikari", "author_id": 11206, "author_profile": "https://Stackoverflow.com/users/11206", "pm_score": 1, "selected": false, "text": "<p>In response to Frank Krueger's request above (in comments) for a demonstration of a difference:</p>\n\n<p>Compile this code in gcc with no optimizations and -mfpmath=387 (I have no reason to think it wouldn't work on other compilers, but I haven't tried it.)\nThen compile it with no optimizations and -msse -mfpmath=sse.</p>\n\n<p>The output will differ.</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\nint main()\n{\n float e = 0.000000001;\n float f[3] = {33810340466158.90625,276553805316035.1875,10413022032824338432.0};\n f[0] = pow(f[0],2-e); f[1] = pow(f[1],2+e); f[2] = pow(f[2],-2-e);\n printf(\"%s\\n\",f);\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 90835, "author": "stusmith", "author_id": 6604, "author_profile": "https://Stackoverflow.com/users/6604", "pm_score": 6, "selected": true, "text": "<p>They can indeed be different. According to the CLR ECMA specification:</p>\n\n<blockquote>\n <p>Storage locations for floating-point\n numbers (statics, array elements, and\n fields of classes) are of fixed size.\n The supported storage sizes are\n float32 and float64. Everywhere else\n (on the evaluation stack, as\n arguments, as return types, and as\n local variables) floating-point\n numbers are represented using an\n internal floating-point type. In each\n such instance, the nominal type of the\n variable or expression is either R4 or\n R8, but its value can be represented\n internally with additional range\n and/or precision. The size of the\n internal floating-point representation\n is implementation-dependent, can vary,\n and shall have precision at least as\n great as that of the variable or\n expression being represented. An\n implicit widening conversion to the\n internal representation from float32\n or float64 is performed when those\n types are loaded from storage. The\n internal representation is typically\n the native size for the hardware, or\n as required for efficient\n implementation of an operation.</p>\n</blockquote>\n\n<p>What this basically means is that the following comparison may or may not be equal:</p>\n\n<pre><code>class Foo\n{\n double _v = ...;\n\n void Bar()\n {\n double v = _v;\n\n if( v == _v )\n {\n // Code may or may not execute here.\n // _v is 64-bit.\n // v could be either 64-bit (debug) or 80-bit (release) or something else (future?).\n }\n }\n}\n</code></pre>\n\n<p>Take-home message: never check floating values for equality.</p>\n" }, { "answer_id": 91027, "author": "Skizz", "author_id": 1898, "author_profile": "https://Stackoverflow.com/users/1898", "pm_score": 4, "selected": false, "text": "<p>This is an interesting question, so I did a bit of experimentation. I used this code:</p>\n\n<pre><code>static void Main (string [] args)\n{\n float\n a = float.MaxValue / 3.0f,\n b = a * a;\n\n if (a * a &lt; b)\n {\n Console.WriteLine (\"Less\");\n }\n else\n {\n Console.WriteLine (\"GreaterEqual\");\n }\n}\n</code></pre>\n\n<p>using DevStudio 2005 and .Net 2. I compiled as both debug and release and examined the output of the compiler:</p>\n\n<pre><code>Release Debug\n\n static void Main (string [] args) static void Main (string [] args)\n { {\n 00000000 push ebp \n 00000001 mov ebp,esp \n 00000003 push edi \n 00000004 push esi \n 00000005 push ebx \n 00000006 sub esp,3Ch \n 00000009 xor eax,eax \n 0000000b mov dword ptr [ebp-10h],eax \n 0000000e xor eax,eax \n 00000010 mov dword ptr [ebp-1Ch],eax \n 00000013 mov dword ptr [ebp-3Ch],ecx \n 00000016 cmp dword ptr ds:[00A2853Ch],0 \n 0000001d je 00000024 \n 0000001f call 793B716F \n 00000024 fldz \n 00000026 fstp dword ptr [ebp-40h] \n 00000029 fldz \n 0000002b fstp dword ptr [ebp-44h] \n 0000002e xor esi,esi \n 00000030 nop \n float float\n a = float.MaxValue / 3.0f, a = float.MaxValue / 3.0f,\n00000000 sub esp,0Ch 00000031 mov dword ptr [ebp-40h],7EAAAAAAh\n00000003 mov dword ptr [esp],ecx \n00000006 cmp dword ptr ds:[00A2853Ch],0 \n0000000d je 00000014 \n0000000f call 793B716F \n00000014 fldz \n00000016 fstp dword ptr [esp+4] \n0000001a fldz \n0000001c fstp dword ptr [esp+8] \n00000020 mov dword ptr [esp+4],7EAAAAAAh \n b = a * a; b = a * a;\n00000028 fld dword ptr [esp+4] 00000038 fld dword ptr [ebp-40h] \n0000002c fmul st,st(0) 0000003b fmul st,st(0) \n0000002e fstp dword ptr [esp+8] 0000003d fstp dword ptr [ebp-44h] \n\n if (a * a &lt; b) if (a * a &lt; b)\n00000032 fld dword ptr [esp+4] 00000040 fld dword ptr [ebp-40h] \n00000036 fmul st,st(0) 00000043 fmul st,st(0) \n00000038 fld dword ptr [esp+8] 00000045 fld dword ptr [ebp-44h] \n0000003c fcomip st,st(1) 00000048 fcomip st,st(1) \n0000003e fstp st(0) 0000004a fstp st(0) \n00000040 jp 00000054 0000004c jp 00000052 \n00000042 jbe 00000054 0000004e ja 00000056 \n 00000050 jmp 00000052 \n 00000052 xor eax,eax \n 00000054 jmp 0000005B \n 00000056 mov eax,1 \n 0000005b test eax,eax \n 0000005d sete al \n 00000060 movzx eax,al \n 00000063 mov esi,eax \n 00000065 test esi,esi \n 00000067 jne 0000007A \n { {\n Console.WriteLine (\"Less\"); 00000069 nop \n00000044 mov ecx,dword ptr ds:[0239307Ch] Console.WriteLine (\"Less\");\n0000004a call 78678B7C 0000006a mov ecx,dword ptr ds:[0239307Ch] \n0000004f nop 00000070 call 78678B7C \n00000050 add esp,0Ch 00000075 nop \n00000053 ret }\n } 00000076 nop \n else 00000077 nop \n { 00000078 jmp 00000088 \n Console.WriteLine (\"GreaterEqual\"); else\n00000054 mov ecx,dword ptr ds:[02393080h] {\n0000005a call 78678B7C 0000007a nop \n } Console.WriteLine (\"GreaterEqual\");\n } 0000007b mov ecx,dword ptr ds:[02393080h] \n 00000081 call 78678B7C \n 00000086 nop \n }\n</code></pre>\n\n<p>What the above shows is that the floating point code is the same for both debug and release, the compiler is choosing consistency over optimisation. Although the program produces the wrong result (a * a is not less than b) it is the same regardless of the debug/release mode.</p>\n\n<p>Now, the Intel IA32 FPU has eight floating point registers, you would think that the compiler would use the registers to store values when optimising rather than writing to memory, thus improving the performance, something along the lines of:</p>\n\n<pre><code>fld dword ptr [a] ; precomputed value stored in ram == float.MaxValue / 3.0f\nfmul st,st(0) ; b = a * a\n; no store to ram, keep b in FPU\nfld dword ptr [a]\nfmul st,st(0)\nfcomi st,st(0) ; a*a compared to b\n</code></pre>\n\n<p>but this would execute differently to the debug version (in this case, display the correct result). However, changing the behaviour of the program depending on the build options is a very bad thing.</p>\n\n<p>FPU code is one area where hand crafting the code can significantly out-perform the compiler, but you do need to get your head around the way the FPU works.</p>\n" }, { "answer_id": 55383018, "author": "fuglede", "author_id": 5085211, "author_profile": "https://Stackoverflow.com/users/5085211", "pm_score": 2, "selected": false, "text": "<p>Here's a simple example where results not only differ between debug and release mode, but the way by which they do so depend on whether one uses x86 or x84 as a platform:</p>\n\n<pre><code>Single f1 = 0.00000000002f;\nSingle f2 = 1 / f1;\nDouble d = f2;\nConsole.WriteLine(d);\n</code></pre>\n\n<p>This writes the following results:</p>\n\n<pre><code> Debug Release\nx86 49999998976 50000000199,7901\nx64 49999998976 49999998976\n</code></pre>\n\n<p>A quick look at the disassembly (Debug -> Windows -> Disassembly in Visual Studio) gives some hints about what's going on here. For the x86 case:</p>\n\n<pre><code>Debug Release\nmov dword ptr [ebp-40h],2DAFEBFFh | mov dword ptr [ebp-4],2DAFEBFFh \nfld dword ptr [ebp-40h] | fld dword ptr [ebp-4] \nfld1 | fld1\nfdivrp st(1),st | fdivrp st(1),st\nfstp dword ptr [ebp-44h] |\nfld dword ptr [ebp-44h] |\nfstp qword ptr [ebp-4Ch] |\nfld qword ptr [ebp-4Ch] |\nsub esp,8 | sub esp,8 \nfstp qword ptr [esp] | fstp qword ptr [esp]\ncall 6B9783BC | call 6B9783BC\n</code></pre>\n\n<p>In particular, we see that a bunch of seemingly redundant \"store the value from the floating point register in memory, then immediately load it back from memory into the floating point register\" have been optimized away in release mode. However, the two instructions</p>\n\n<pre><code>fstp dword ptr [ebp-44h] \nfld dword ptr [ebp-44h]\n</code></pre>\n\n<p>are enough to change the value in the x87 register from +5.0000000199790138e+0010 to +4.9999998976000000e+0010 as one may verify by stepping through the disassembly and investigating the values of the relevant registers (Debug -> Windows -> Registers, then right click and check \"Floating point\").</p>\n\n<p>The story for x64 is wildly different. We still see the same optimization removing a few instructions, but this time around, everything relies on SSE with its 128-bit registers and dedicated instruction set:</p>\n\n<pre><code>Debug Release\nvmovss xmm0,dword ptr [7FF7D0E104F8h] | vmovss xmm0,dword ptr [7FF7D0E304C8h] \nvmovss dword ptr [rbp+34h],xmm0 | vmovss dword ptr [rbp-4],xmm0 \nvmovss xmm0,dword ptr [7FF7D0E104FCh] | vmovss xmm0,dword ptr [7FF7D0E304CCh]\nvdivss xmm0,xmm0,dword ptr [rbp+34h] | vdivss xmm0,xmm0,dword ptr [rbp-4]\nvmovss dword ptr [rbp+30h],xmm0 |\nvcvtss2sd xmm0,xmm0,dword ptr [rbp+30h] | vcvtss2sd xmm0,xmm0,xmm0 \nvmovsd qword ptr [rbp+28h],xmm0 |\nvmovsd xmm0,qword ptr [rbp+28h] |\ncall 00007FF81C9343F0 | call 00007FF81C9343F0 \n</code></pre>\n\n<p>Here, because the SSE unit avoids using higher precision than single precision internally (while the x87 unit does), we end up with the \"single precision-ish\" result of the x86 case regardless of optimizations. Indeed, one finds (after enabling the SSE registers in the Visual Studio Registers overview) that after <code>vdivss</code>, XMM0 contains 0000000000000000-00000000513A43B7 which is exactly the 49999998976 from before.</p>\n\n<p>Both of the discrepancies bit me in practice. Besides illustrating that one should never compare equality of floating points, the example also shows that there's still room for assembly debugging in a high-level language such as C#, the moment floating points show up.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90751", "https://Stackoverflow.com", "https://Stackoverflow.com/users/288629/" ]
Do C#/.NET floating point operations differ in precision between debug mode and release mode?
They can indeed be different. According to the CLR ECMA specification: > > Storage locations for floating-point > numbers (statics, array elements, and > fields of classes) are of fixed size. > The supported storage sizes are > float32 and float64. Everywhere else > (on the evaluation stack, as > arguments, as return types, and as > local variables) floating-point > numbers are represented using an > internal floating-point type. In each > such instance, the nominal type of the > variable or expression is either R4 or > R8, but its value can be represented > internally with additional range > and/or precision. The size of the > internal floating-point representation > is implementation-dependent, can vary, > and shall have precision at least as > great as that of the variable or > expression being represented. An > implicit widening conversion to the > internal representation from float32 > or float64 is performed when those > types are loaded from storage. The > internal representation is typically > the native size for the hardware, or > as required for efficient > implementation of an operation. > > > What this basically means is that the following comparison may or may not be equal: ``` class Foo { double _v = ...; void Bar() { double v = _v; if( v == _v ) { // Code may or may not execute here. // _v is 64-bit. // v could be either 64-bit (debug) or 80-bit (release) or something else (future?). } } } ``` Take-home message: never check floating values for equality.
90,755
<p>How do I get a list of the active IP-addresses, MAC-addresses and <a href="http://en.wikipedia.org/wiki/NetBIOS" rel="nofollow noreferrer">NetBIOS</a> names on the LAN?</p> <p>I'd like to get NetBIOS name, IP and <a href="http://en.wikipedia.org/wiki/MAC_address" rel="nofollow noreferrer">MAC addresses</a> for every host on the LAN, preferably not having to walk to every single PC and take note of the stuff myself.</p> <p>How to do that with <a href="http://en.wikipedia.org/wiki/Windows_Script_Host" rel="nofollow noreferrer">Windows Script Host</a>/PowerShell/whatever?</p>
[ { "answer_id": 90806, "author": "Tubs", "author_id": 11924, "author_profile": "https://Stackoverflow.com/users/11924", "pm_score": 2, "selected": false, "text": "<p>If you're using DHCP then the server will give you a list of all that information.</p>\n\n<p>This website has a good tutorial on using powershell to get networking information <a href=\"http://www.powershellpro.com/powershell-tutorial-introduction/powershell-scripting-with-wmi/\" rel=\"nofollow noreferrer\">http://www.powershellpro.com/powershell-tutorial-introduction/powershell-scripting-with-wmi/</a> </p>\n\n<p>If you neet to get quick list of computer names you can use \"net view\". Also have a look at nbmac although I'm unsure of it's working status under XP. Another option could be to use nbtstat -a (once you've used net view to list workstations)</p>\n" }, { "answer_id": 90854, "author": "mana", "author_id": 12016, "author_profile": "https://Stackoverflow.com/users/12016", "pm_score": 4, "selected": true, "text": "<p>As Daren Thomas said, use nmap.</p>\n\n<pre><code> nmap -sP 192.168.1.1/24\n</code></pre>\n\n<p>to scan the network 192.168.1.*</p>\n\n<pre><code> nmap -O 192.168.1.1/24\n</code></pre>\n\n<p>to get the operating system of the user. For more information, read the manpage</p>\n\n<pre><code> man nmap\n</code></pre>\n\n<p>regards</p>\n" }, { "answer_id": 90875, "author": "Matthew Schinckel", "author_id": 188, "author_profile": "https://Stackoverflow.com/users/188", "pm_score": 3, "selected": false, "text": "<pre><code>arp -a\n</code></pre>\n\n<p>That gets everything the current machine knows about on the network.</p>\n\n<p>(I'm putting this up there as a second option, since nmap isn't universally installed).</p>\n" }, { "answer_id": 94462, "author": "Shay Levy", "author_id": 9833, "author_profile": "https://Stackoverflow.com/users/9833", "pm_score": 1, "selected": false, "text": "<p>In PowerShell you can do something like:</p>\n\n<p>$computers = \"server1\",\"server2\",\"server3\"</p>\n\n<p>Get-WmiObject Win32_NetworkAdapterConfiguration -computer $computers -filter \"IPEnabled ='true'\" | select __Server,IPAddress,MACAddress</p>\n" }, { "answer_id": 5135520, "author": "mjsr", "author_id": 1169720, "author_profile": "https://Stackoverflow.com/users/1169720", "pm_score": 1, "selected": false, "text": "<p>In PowerShell:</p>\n\n<pre><code>function Explore-Net($subnet, [int[]]$range){\n $range | % { test-connection \"$subnet.$_\" -count 1 -erroraction silentlycontinue} | select -Property address | % {[net.dns]::gethostbyaddress($_.address)}\n}\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>Explore-Net 192.168.2 @(3..10)\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90755", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6069/" ]
How do I get a list of the active IP-addresses, MAC-addresses and [NetBIOS](http://en.wikipedia.org/wiki/NetBIOS) names on the LAN? I'd like to get NetBIOS name, IP and [MAC addresses](http://en.wikipedia.org/wiki/MAC_address) for every host on the LAN, preferably not having to walk to every single PC and take note of the stuff myself. How to do that with [Windows Script Host](http://en.wikipedia.org/wiki/Windows_Script_Host)/PowerShell/whatever?
As Daren Thomas said, use nmap. ``` nmap -sP 192.168.1.1/24 ``` to scan the network 192.168.1.\* ``` nmap -O 192.168.1.1/24 ``` to get the operating system of the user. For more information, read the manpage ``` man nmap ``` regards
90,758
<p>I'm currently using ImageMagick to determine the size of images uploaded to the website. By calling ImageMagick's "identify" on the command line it takes about 0.42 seconds to determine a 1MB JPEG's dimensions along with the fact that it's a JPEG. I find that a bit slow.</p> <p>Using the Imagick PHP library is even slower as it attemps to load the whole 1MB in memory before doing any treatment to the image (in this case, simply determining its size and type).</p> <p>Are there any solutions to speed up this process of determining which file type and which dimensions an arbitrary image file has? I can live with it only supporting JPEG and PNG. It's important to me that the file type is determined by looking at the file's headers and not simply the extension.</p> <p><strong>Edit: The solution can be a command-line tool UNIX called by PHP, much like the way I'm using ImageMagick at the moment</strong></p>
[ { "answer_id": 90768, "author": "J D OConal", "author_id": 17023, "author_profile": "https://Stackoverflow.com/users/17023", "pm_score": 3, "selected": false, "text": "<p>If you're using PHP with GD support, you can try <a href=\"http://www.php.net/manual/en/function.getimagesize.php\" rel=\"nofollow noreferrer\">getimagesize()</a>.</p>\n" }, { "answer_id": 90784, "author": "Kasprzol", "author_id": 5957, "author_profile": "https://Stackoverflow.com/users/5957", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>It's important to me that the file type is determined by looking at the file's headers and not simply the extension.</p>\n</blockquote>\n\n<p>For that you can use 'file' unix command (orsome php function that implements the same functionality).</p>\n\n<p><code>/tmp$ file stackoverflow-logo-250.png</code><br>\n<code>stackoverflow-logo-250.png: PNG image data, 250 x 70, 8-bit colormap, non-interlaced</code></p>\n" }, { "answer_id": 90824, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 2, "selected": false, "text": "<p>Have you tried</p>\n\n<pre><code>identify -ping filename.png\n</code></pre>\n\n<p>?</p>\n" }, { "answer_id": 91017, "author": "William Macdonald", "author_id": 2725, "author_profile": "https://Stackoverflow.com/users/2725", "pm_score": 2, "selected": false, "text": "<p>Actually, to use getimagesize(), you do <strong>NOT</strong> need to have GD compiled in.</p>\n\n<p>You can also use mime_content_type() to get the MIME type.</p>\n" }, { "answer_id": 91034, "author": "Steven Noble", "author_id": 10393, "author_profile": "https://Stackoverflow.com/users/10393", "pm_score": 3, "selected": true, "text": "<p>Sorry I can't add this as a comment to a previous answer but I don't have the rep. Doing some quick and dirty testing I also found that exec(\"identify -ping... is about 20 times faster than without the -ping. But getimagesize() appears to be about 200 times faster still.</p>\n\n<p>So I would say getimagesize() is the faster method. I only tested on jpg and not on png.</p>\n\n<p>the test is just</p>\n\n<pre><code>$files = array('2819547919_db7466149b_o_d.jpg', 'GP1-green2.jpg', 'aegeri-lake-switzerland.JPG');\nforeach($files as $file){\n $size2 = array();\n $size3 = array();\n $time1 = microtime();\n $size = getimagesize($file);\n $time1 = microtime() - $time1;\n print \"$time1 \\n\";\n $time2 = microtime();\n exec(\"identify -ping $file\", $size2);\n $time2 = microtime() - $time2;\n print $time2/$time1 . \"\\n\";\n $time2 = microtime();\n exec(\"identify $file\", $size3);\n $time2 = microtime() - $time2;\n print $time2/$time1 . \"\\n\";\n print_r($size);\n print_r($size2);\n print_r($size3);\n}\n</code></pre>\n" }, { "answer_id": 558243, "author": "jproffer", "author_id": 316801, "author_profile": "https://Stackoverflow.com/users/316801", "pm_score": 1, "selected": false, "text": "<p>exif_imagetype() is faster than getimagesize().</p>\n\n<p>$filename = \"somefile\";<BR>\n$data = exif_imagetype($filename);<BR>\necho \"&lt;PRE&gt;\";<BR>\nprint_r($data);<BR>\necho \"&lt;/PRE&gt;\";<BR><BR></p>\n\n<p>output:\n<PRE>\nArray (\n [FileName] => somefile\n [FileDateTime] => 1234895396\n [FileSize] => 15427\n [FileType] => 2\n [MimeType] => image/jpeg\n [SectionsFound] => \n [COMPUTED] => Array\n (\n [html] => width=\"229\" height=\"300\"\n [Height] => 300\n [Width] => 229\n [IsColor] => 1\n )\n)\n</PRE></p>\n" }, { "answer_id": 15657701, "author": "kralyk", "author_id": 786102, "author_profile": "https://Stackoverflow.com/users/786102", "pm_score": 0, "selected": false, "text": "<p>If you're using PHP I'd suggest using the Imagick library rather than calling <code>exec()</code>. The feature you're looking for is <a href=\"http://www.php.net/manual/en/imagick.pingimage.php\" rel=\"nofollow\">Imagick::pingImage()</a>.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90758", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10024/" ]
I'm currently using ImageMagick to determine the size of images uploaded to the website. By calling ImageMagick's "identify" on the command line it takes about 0.42 seconds to determine a 1MB JPEG's dimensions along with the fact that it's a JPEG. I find that a bit slow. Using the Imagick PHP library is even slower as it attemps to load the whole 1MB in memory before doing any treatment to the image (in this case, simply determining its size and type). Are there any solutions to speed up this process of determining which file type and which dimensions an arbitrary image file has? I can live with it only supporting JPEG and PNG. It's important to me that the file type is determined by looking at the file's headers and not simply the extension. **Edit: The solution can be a command-line tool UNIX called by PHP, much like the way I'm using ImageMagick at the moment**
Sorry I can't add this as a comment to a previous answer but I don't have the rep. Doing some quick and dirty testing I also found that exec("identify -ping... is about 20 times faster than without the -ping. But getimagesize() appears to be about 200 times faster still. So I would say getimagesize() is the faster method. I only tested on jpg and not on png. the test is just ``` $files = array('2819547919_db7466149b_o_d.jpg', 'GP1-green2.jpg', 'aegeri-lake-switzerland.JPG'); foreach($files as $file){ $size2 = array(); $size3 = array(); $time1 = microtime(); $size = getimagesize($file); $time1 = microtime() - $time1; print "$time1 \n"; $time2 = microtime(); exec("identify -ping $file", $size2); $time2 = microtime() - $time2; print $time2/$time1 . "\n"; $time2 = microtime(); exec("identify $file", $size3); $time2 = microtime() - $time2; print $time2/$time1 . "\n"; print_r($size); print_r($size2); print_r($size3); } ```
90,775
<p>I have an exe file generated with py2exe. In the setup.py I specify an icon to be embedded in the exe:</p> <pre><code>windows=[{'script': 'my_script.py','icon_resources': [(0, 'my_icon.ico')], ... </code></pre> <p>I tried loading the icon using:</p> <pre><code>hinst = win32api.GetModuleHandle(None) hicon = win32gui.LoadImage(hinst, 0, win32con.IMAGE_ICON, 0, 0, win32con.LR_DEFAULTSIZE) </code></pre> <p>But this produces an (very unspecific) error:<br> <strong>pywintypes.error: (0, 'LoadImage', 'No error message is available')</strong><br> <br> If I try specifying 0 as a string</p> <pre><code>hicon = win32gui.LoadImage(hinst, '0', win32con.IMAGE_ICON, 0, 0, win32con.LR_DEFAULTSIZE) </code></pre> <p>then I get the error:<br> <strong>pywintypes.error: (1813, 'LoadImage', 'The specified resource type cannot be found in the image file.')</strong><br> <br>So, what's the correct method/syntax to load the icon?<br> <em>Also please notice that I don't use any GUI toolkit - just the Windows API via PyWin32.</em></p>
[ { "answer_id": 91245, "author": "efotinis", "author_id": 12320, "author_profile": "https://Stackoverflow.com/users/12320", "pm_score": 0, "selected": false, "text": "<p>You should set the icon ID to something other than 0:</p>\n\n<pre><code>'icon_resources': [(42, 'my_icon.ico')]\n</code></pre>\n\n<p>Windows resource IDs must be between 1 and 32767.</p>\n" }, { "answer_id": 91670, "author": "elifiner", "author_id": 15109, "author_profile": "https://Stackoverflow.com/users/15109", "pm_score": 1, "selected": false, "text": "<p>If you're using wxPython, you can use the following simple code:</p>\n\n<pre><code>wx.Icon(sys.argv[0], wx.BITMAP_TYPE_ICO)\n</code></pre>\n\n<p>I usually have code that checks whether it's running from an EXE or not, and acts accordingly:</p>\n\n<pre><code>def get_app_icon():\n if hasattr(sys, \"frozen\") and getattr(sys, \"frozen\") == \"windows_exe\":\n return wx.Icon(sys.argv[0], wx.BITMAP_TYPE_ICO)\n else:\n return wx.Icon(\"gfx/myapp.ico\", wx.BITMAP_TYPE_ICO)\n</code></pre>\n" }, { "answer_id": 92710, "author": "efotinis", "author_id": 12320, "author_profile": "https://Stackoverflow.com/users/12320", "pm_score": 1, "selected": false, "text": "<p>Well, well... I installed py2exe and I think it's a bug. In py2exe_util.c they should init <code>rt_icon_id</code> to 1 instead of 0. The way it is now, it's impossible to load the first format of the first icon using LoadIcon/LoadImage.</p>\n\n<p>I'll notify the developers about this if it's not already a known issue.</p>\n\n<p>A workaround, in the meantime, would be to include the same icon twice in your setup.py:</p>\n\n<pre><code>'icon_resources': [(1, 'my_icon.ico'), (2, 'my_icon.ico')]\n</code></pre>\n\n<p>You can load the second one, while Windows will use the first one as the shell icon. Remember to use non-zero IDs though. :)</p>\n" }, { "answer_id": 110777, "author": "Andreas Thomas", "author_id": 1531, "author_profile": "https://Stackoverflow.com/users/1531", "pm_score": 4, "selected": true, "text": "<p>@efotinis: You're right. </p>\n\n<p>Here is a workaround until py2exe gets fixed and you don't want to include the same icon twice:</p>\n\n<pre><code>hicon = win32gui.CreateIconFromResource(win32api.LoadResource(None, win32con.RT_ICON, 1), True)\n</code></pre>\n\n<p>Be aware that <strong>1</strong> is not the ID you gave the icon in setup.py (which is the icon group ID), but the resource ID <em>automatically</em> assigned by py2exe to each icon in each icon group. At least that's how I understand it.</p>\n\n<p>If you want to create an icon with a specified size (as CreateIconFromResource uses the system default icon size), you need to use CreateIconFromResourceEx, which isn't available via PyWin32:</p>\n\n<pre><code>icon_res = win32api.LoadResource(None, win32con.RT_ICON, 1)\nhicon = ctypes.windll.user32.CreateIconFromResourceEx(icon_res, len(icon_res), True,\n 0x00030000, 16, 16, win32con.LR_DEFAULTCOLOR)\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90775", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1531/" ]
I have an exe file generated with py2exe. In the setup.py I specify an icon to be embedded in the exe: ``` windows=[{'script': 'my_script.py','icon_resources': [(0, 'my_icon.ico')], ... ``` I tried loading the icon using: ``` hinst = win32api.GetModuleHandle(None) hicon = win32gui.LoadImage(hinst, 0, win32con.IMAGE_ICON, 0, 0, win32con.LR_DEFAULTSIZE) ``` But this produces an (very unspecific) error: **pywintypes.error: (0, 'LoadImage', 'No error message is available')** If I try specifying 0 as a string ``` hicon = win32gui.LoadImage(hinst, '0', win32con.IMAGE_ICON, 0, 0, win32con.LR_DEFAULTSIZE) ``` then I get the error: **pywintypes.error: (1813, 'LoadImage', 'The specified resource type cannot be found in the image file.')** So, what's the correct method/syntax to load the icon? *Also please notice that I don't use any GUI toolkit - just the Windows API via PyWin32.*
@efotinis: You're right. Here is a workaround until py2exe gets fixed and you don't want to include the same icon twice: ``` hicon = win32gui.CreateIconFromResource(win32api.LoadResource(None, win32con.RT_ICON, 1), True) ``` Be aware that **1** is not the ID you gave the icon in setup.py (which is the icon group ID), but the resource ID *automatically* assigned by py2exe to each icon in each icon group. At least that's how I understand it. If you want to create an icon with a specified size (as CreateIconFromResource uses the system default icon size), you need to use CreateIconFromResourceEx, which isn't available via PyWin32: ``` icon_res = win32api.LoadResource(None, win32con.RT_ICON, 1) hicon = ctypes.windll.user32.CreateIconFromResourceEx(icon_res, len(icon_res), True, 0x00030000, 16, 16, win32con.LR_DEFAULTCOLOR) ```
90,885
<p>I want to make an entity that has an autogenerated primary key, but also a unique compound key made up of two other fields. How do I do this in JPA?<br> I want to do this because the primary key should be used as foreign key in another table and making it compound would not be good.</p> <p>In the following snippet, I need the command and model to be unique. pk is of course the primary key.</p> <pre><code>@Entity @Table(name = "dm_action_plan") public class ActionPlan { @Id private int pk; @Column(name = "command", nullable = false) private String command; @Column(name = "model", nullable = false) String model; } </code></pre>
[ { "answer_id": 90960, "author": "Michel", "author_id": 7198, "author_profile": "https://Stackoverflow.com/users/7198", "pm_score": 5, "selected": true, "text": "<p>You can use <a href=\"http://java.sun.com/javaee/5/docs/api/javax/persistence/UniqueConstraint.html\" rel=\"nofollow noreferrer\"><code>@UniqueConstraint</code></a> something like this :</p>\n\n<pre><code>@Entity\n@Table(name = \"dm_action_plan\",\n uniqueConstraints={ @UniqueConstraint(columnNames= \"command\",\"model\") } )\npublic class ActionPlan {\n @Id\n private int pk;\n\n @Column(name = \"command\", nullable = false)\n private String command;\n\n @Column(name = \"model\", nullable = false)\n String model;\n}\n</code></pre>\n\n<p>This will allow your JPA implementation to generate the DDL for the unique constraint.</p>\n" }, { "answer_id": 90968, "author": "Nicolas", "author_id": 1730, "author_profile": "https://Stackoverflow.com/users/1730", "pm_score": 0, "selected": false, "text": "<p>Use @GeneratedValue to indicate that the key will be generated and @UniqueConstraint to express unicity</p>\n\n<pre><code>@Entity\n@Table(name = \"dm_action_plan\"\n uniqueConstraint = @UniqueConstraint({\"command\", \"model\"})\n)\npublic class ActionPlan {\n @Id\n @GeneratedValue\n private int pk;\n @Column(name = \"command\", nullable = false)\n private String command;\n @Column(name = \"model\", nullable = false)\n String model;\n}\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90885", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16152/" ]
I want to make an entity that has an autogenerated primary key, but also a unique compound key made up of two other fields. How do I do this in JPA? I want to do this because the primary key should be used as foreign key in another table and making it compound would not be good. In the following snippet, I need the command and model to be unique. pk is of course the primary key. ``` @Entity @Table(name = "dm_action_plan") public class ActionPlan { @Id private int pk; @Column(name = "command", nullable = false) private String command; @Column(name = "model", nullable = false) String model; } ```
You can use [`@UniqueConstraint`](http://java.sun.com/javaee/5/docs/api/javax/persistence/UniqueConstraint.html) something like this : ``` @Entity @Table(name = "dm_action_plan", uniqueConstraints={ @UniqueConstraint(columnNames= "command","model") } ) public class ActionPlan { @Id private int pk; @Column(name = "command", nullable = false) private String command; @Column(name = "model", nullable = false) String model; } ``` This will allow your JPA implementation to generate the DDL for the unique constraint.
90,899
<p>How can I get all items from a specific calendar (for a specific date). Lets say for instance that I have a calendar with a recurring item every Monday evening. When I request all items like this:</p> <pre><code>CalendarItems = CalendarFolder.Items; CalendarItems.IncludeRecurrences = true; </code></pre> <p>I only get 1 item...</p> <p>Is there an easy way to get <strong>all</strong> items (main item + derived items) from a calendar? In my specific situation it can be possible to set a date limit but it would be cool just to get all items (my recurring items are time limited themselves).</p> <p><strong>I'm using the Microsoft Outlook 12 Object library (Microsoft.Office.Interop.Outlook)</strong>.</p>
[ { "answer_id": 91652, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 5, "selected": true, "text": "<p>I believe that you must Restrict or Find in order to get recurring appointments, otherwise Outlook won't expand them. Also, you must Sort by Start <em>before</em> setting IncludeRecurrences.</p>\n" }, { "answer_id": 92184, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "<p>I've studied the docs and this is my result:\nI've put a time limit of one month hard-coded, but this is just an example.</p>\n\n<pre><code>public void GetAllCalendarItems()\n{\n Microsoft.Office.Interop.Outlook.Application oApp = null;\n Microsoft.Office.Interop.Outlook.NameSpace mapiNamespace = null;\n Microsoft.Office.Interop.Outlook.MAPIFolder CalendarFolder = null;\n Microsoft.Office.Interop.Outlook.Items outlookCalendarItems = null;\n\n oApp = new Microsoft.Office.Interop.Outlook.Application();\n mapiNamespace = oApp.GetNamespace(\"MAPI\"); ;\n CalendarFolder = mapiNamespace.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderCalendar);\n outlookCalendarItems = CalendarFolder.Items;\n outlookCalendarItems.IncludeRecurrences = true;\n\n foreach (Microsoft.Office.Interop.Outlook.AppointmentItem item in outlookCalendarItems)\n {\n if (item.IsRecurring)\n {\n Microsoft.Office.Interop.Outlook.RecurrencePattern rp = item.GetRecurrencePattern();\n DateTime first = new DateTime(2008, 8, 31, item.Start.Hour, item.Start.Minute, 0);\n DateTime last = new DateTime(2008, 10, 1);\n Microsoft.Office.Interop.Outlook.AppointmentItem recur = null;\n\n\n\n for (DateTime cur = first; cur &lt;= last; cur = cur.AddDays(1))\n {\n try\n {\n recur = rp.GetOccurrence(cur);\n MessageBox.Show(recur.Subject + \" -&gt; \" + cur.ToLongDateString());\n }\n catch\n { }\n }\n }\n else\n {\n MessageBox.Show(item.Subject + \" -&gt; \" + item.Start.ToLongDateString());\n }\n }\n\n}\n</code></pre>\n" }, { "answer_id": 2869463, "author": "uygar", "author_id": 345515, "author_profile": "https://Stackoverflow.com/users/345515", "pm_score": -1, "selected": false, "text": "<pre><code>calendarFolder = \n mapiNamespace.GetDefaultFolder(\n Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderCalendar);\n</code></pre>\n" }, { "answer_id": 7106351, "author": "sdyutjan", "author_id": 900453, "author_profile": "https://Stackoverflow.com/users/900453", "pm_score": 2, "selected": false, "text": "<p>If you need want to access the shared folder from your friend, then you can set your friend as the recipient. Requirement: his calendar must be shared first. </p>\n\n<pre><code>// Set recepient\nOutlook.Recipient oRecip = (Outlook.Recipient)oNS.CreateRecipient(\"[email protected]\");\n\n// Get calendar folder \nOutlook.MAPIFolder oCalendar = oNS.GetSharedDefaultFolder(oRecip, Outlook.OlDefaultFolders.olFolderCalendar);\n</code></pre>\n" }, { "answer_id": 8366973, "author": "Eliot", "author_id": 1078856, "author_profile": "https://Stackoverflow.com/users/1078856", "pm_score": 3, "selected": false, "text": "<p>I wrote similar code, but then found the export functionality:</p>\n\n<pre><code>Application outlook;\nNameSpace OutlookNS;\n\noutlook = new ApplicationClass();\nOutlookNS = outlook.GetNamespace(\"MAPI\");\n\nMAPIFolder f = OutlookNS.GetDefaultFolder(OlDefaultFolders.olFolderCalendar);\n\nCalendarSharing cs = f.GetCalendarExporter();\ncs.CalendarDetail = OlCalendarDetail.olFullDetails;\ncs.StartDate = new DateTime(2011, 11, 1);\ncs.EndDate = new DateTime(2011, 12, 31);\ncs.SaveAsICal(\"c:\\\\temp\\\\cal.ics\");\n</code></pre>\n" }, { "answer_id": 15669633, "author": "Vladimir Sitnikov", "author_id": 1261287, "author_profile": "https://Stackoverflow.com/users/1261287", "pm_score": 2, "selected": false, "text": "<p>There is no need to expand recurring items manually. Just ensure you sort the items <em>before</em> using IncludeRecurrences.</p>\n\n<p>Here is VBA example:</p>\n\n<pre><code>tdystart = VBA.Format(#8/1/2012#, \"Short Date\")\ntdyend = VBA.Format(#8/31/2012#, \"Short Date\")\n\nDim folder As MAPIFolder\nSet appointments = folder.Items\n\nappointments.Sort \"[Start]\" ' &lt;-- !!! Sort is a MUST\nappointments.IncludeRecurrences = True ' &lt;-- This will expand reccurent items\n\nSet app = appointments.Find(\"[Start] &gt;= \"\"\" &amp; tdystart &amp; \"\"\" and [Start] &lt;= \"\"\" &amp; tdyend &amp; \"\"\"\")\n\nWhile TypeName(app) &lt;&gt; \"Nothing\"\n MsgBox app.Start &amp; \" \" &amp; app.Subject\n Set app = appointments.FindNext\nWend\n</code></pre>\n" }, { "answer_id": 19149688, "author": "Roy Ashbrook", "author_id": 2074040, "author_profile": "https://Stackoverflow.com/users/2074040", "pm_score": 3, "selected": false, "text": "<p>LinqPad snipped that works for me:</p>\n\n<pre><code>//using Microsoft.Office.Interop.Outlook\nApplication a = new Application();\nItems i = a.Session.GetDefaultFolder(OlDefaultFolders.olFolderCalendar).Items;\ni.IncludeRecurrences = true;\ni.Sort(\"[Start]\");\ni = i.Restrict(\n \"[Start] &gt;= '10/1/2013 12:00 AM' AND [End] &lt; '10/3/2013 12:00 AM'\");\n\n\nvar r =\n from ai in i.Cast&lt;AppointmentItem&gt;()\n select new {\n ai.Categories,\n ai.Start,\n ai.Duration\n };\nr.Dump();\n</code></pre>\n" }, { "answer_id": 21669956, "author": "RameezAli", "author_id": 3098077, "author_profile": "https://Stackoverflow.com/users/3098077", "pm_score": 2, "selected": false, "text": "<pre><code>public void GetAllCalendarItems()\n {\n DataTable sample = new DataTable(); //Sample Data\n sample.Columns.Add(\"Subject\", typeof(string));\n sample.Columns.Add(\"Location\", typeof(string));\n sample.Columns.Add(\"StartTime\", typeof(DateTime));\n sample.Columns.Add(\"EndTime\", typeof(DateTime));\n sample.Columns.Add(\"StartDate\", typeof(DateTime));\n sample.Columns.Add(\"EndDate\", typeof(DateTime));\n sample.Columns.Add(\"AllDayEvent\", typeof(bool));\n sample.Columns.Add(\"Body\", typeof(string));\n\n\n listViewContacts.Items.Clear();\n oApp = new Outlook.Application();\n oNS = oApp.GetNamespace(\"MAPI\");\n oCalenderFolder = oNS.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderCalendar);\n outlookCalendarItems = oCalenderFolder.Items;\n outlookCalendarItems.IncludeRecurrences = true;\n // DataTable sample = new DataTable();\n foreach (Microsoft.Office.Interop.Outlook.AppointmentItem item in outlookCalendarItems)\n {\n DataRow row = sample.NewRow();\n row[\"Subject\"] = item.Subject;\n row[\"Location\"] = item.Location;\n row[\"StartTime\"] = item.Start.TimeOfDay.ToString();\n row[\"EndTime\"] = item.End.TimeOfDay.ToString();\n row[\"StartDate\"] = item.Start.Date;\n row[\"EndDate\"] = item.End.Date;\n row[\"AllDayEvent\"] = item.AllDayEvent;\n row[\"Body\"] = item.Body;\n sample.Rows.Add(row);\n }\n sample.AcceptChanges();\n foreach (DataRow dr in sample.Rows)\n {\n ListViewItem lvi = new ListViewItem(dr[\"Subject\"].ToString());\n\n lvi.SubItems.Add(dr[\"Location\"].ToString());\n lvi.SubItems.Add(dr[\"StartTime\"].ToString());\n lvi.SubItems.Add(dr[\"EndTime\"].ToString());\n lvi.SubItems.Add(dr[\"StartDate\"].ToString());\n lvi.SubItems.Add(dr[\"EndDate\"].ToString());\n lvi.SubItems.Add(dr[\"AllDayEvent\"].ToString());\n lvi.SubItems.Add(dr[\"Body\"].ToString());\n\n\n\n this.listViewContacts.Items.Add(lvi);\n }\n oApp = null;\n oNS = null;\n\n }\n</code></pre>\n" }, { "answer_id": 28295179, "author": "Dobry", "author_id": 1045115, "author_profile": "https://Stackoverflow.com/users/1045115", "pm_score": 0, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code> public List&lt;AdxCalendarItem&gt; GetAllCalendarItems()\n {\n Outlook.Application OutlookApp = new Outlook.Application();\n List&lt;AdxCalendarItem&gt; result = new List&lt;AdxCalendarItem&gt;();\n Outlook._NameSpace session = OutlookApp.Session;\n if (session != null)\n try\n {\n object stores = session.GetType().InvokeMember(\"Stores\", BindingFlags.GetProperty, null, session, null);\n if (stores != null)\n try\n {\n int count = (int)stores.GetType().InvokeMember(\"Count\", BindingFlags.GetProperty, null, stores, null);\n for (int i = 1; i &lt;= count; i++)\n {\n object store = stores.GetType().InvokeMember(\"Item\", BindingFlags.GetProperty, null, stores, new object[] { i });\n if (store != null)\n try\n {\n Outlook.MAPIFolder calendar = null;\n try\n {\n calendar = (Outlook.MAPIFolder)store.GetType().InvokeMember(\"GetDefaultFolder\", BindingFlags.GetProperty, null, store, new object[] { Outlook.OlDefaultFolders.olFolderCalendar });\n }\n catch\n {\n continue;\n }\n if (calendar != null)\n try\n {\n Outlook.Folders folders = calendar.Folders;\n try\n {\n Outlook.MAPIFolder subfolder = null;\n for (int j = 1; j &lt; folders.Count + 1; j++)\n {\n subfolder = folders[j];\n try\n {\n // add subfolder items\n result.AddRange(GetAppointmentItems(subfolder));\n }\n finally\n { if (subfolder != null) Marshal.ReleaseComObject(subfolder); }\n }\n }\n finally\n { if (folders != null) Marshal.ReleaseComObject(folders); }\n // add root items\n result.AddRange(GetAppointmentItems(calendar));\n }\n finally { Marshal.ReleaseComObject(calendar); }\n }\n finally { Marshal.ReleaseComObject(store); }\n }\n }\n finally { Marshal.ReleaseComObject(stores); }\n }\n finally { Marshal.ReleaseComObject(session); }\n return result;\n }\n\n List&lt;AdxCalendarItem&gt; GetAppointmentItems(Outlook.MAPIFolder calendarFolder)\n {\n List&lt;AdxCalendarItem&gt; result = new List&lt;AdxCalendarItem&gt;();\n Outlook.Items calendarItems = calendarFolder.Items;\n try\n {\n calendarItems.IncludeRecurrences = true;\n Outlook.AppointmentItem appointment = null;\n for (int j = 1; j &lt; calendarItems.Count + 1; j++)\n {\n appointment = calendarItems[j] as Outlook.AppointmentItem;\n try\n {\n AdxCalendarItem item = new AdxCalendarItem(\n calendarFolder.Name,\n appointment.Subject,\n appointment.Location,\n appointment.Start,\n appointment.End,\n appointment.Start.Date,\n appointment.End.Date,\n appointment.AllDayEvent,\n appointment.Body);\n result.Add(item);\n }\n finally\n {\n { Marshal.ReleaseComObject(appointment); }\n }\n }\n }\n finally { Marshal.ReleaseComObject(calendarItems); }\n return result;\n }\n}\n\npublic class AdxCalendarItem\n{\n public string CalendarName;\n public string Subject;\n public string Location;\n public DateTime StartTime;\n public DateTime EndTime;\n public DateTime StartDate;\n public DateTime EndDate;\n public bool AllDayEvent;\n public string Body;\n\n public AdxCalendarItem(string CalendarName, string Subject, string Location, DateTime StartTime, DateTime EndTime,\n DateTime StartDate, DateTime EndDate, bool AllDayEvent, string Body)\n {\n this.CalendarName = CalendarName;\n this.Subject = Subject;\n this.Location = Location;\n this.StartTime = StartTime;\n this.EndTime = EndTime;\n this.StartDate = StartDate;\n this.EndDate = EndDate;\n this.AllDayEvent = AllDayEvent;\n this.Body = Body;\n\n }\n\n}\n</code></pre>\n" }, { "answer_id": 53943350, "author": "TC Anıl Aydınalp", "author_id": 9359745, "author_profile": "https://Stackoverflow.com/users/9359745", "pm_score": 0, "selected": false, "text": "<pre><code> Microsoft.Office.Interop.Outlook.Application oApp = null;\n Microsoft.Office.Interop.Outlook.NameSpace mapiNamespace = null;\n Microsoft.Office.Interop.Outlook.MAPIFolder CalendarFolder = null;\n Microsoft.Office.Interop.Outlook.Items outlookCalendarItems = null;\n\n oApp = new Microsoft.Office.Interop.Outlook.Application();\n mapiNamespace = oApp.GetNamespace(\"MAPI\"); ;\n CalendarFolder = mapiNamespace.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderCalendar);\n outlookCalendarItems = CalendarFolder.Items;\n outlookCalendarItems.IncludeRecurrences = true;\n\n foreach (Microsoft.Office.Interop.Outlook.AppointmentItem item in outlookCalendarItems)\n {\n if (item.IsRecurring)\n {\n Microsoft.Office.Interop.Outlook.RecurrencePattern rp = item.GetRecurrencePattern();\n\n // get all date \n DateTime first = new DateTime( item.Start.Hour, item.Start.Minute, 0);\n DateTime last = new DateTime();\n Microsoft.Office.Interop.Outlook.AppointmentItem recur = null;\n\n\n\n for (DateTime cur = first; cur &lt;= last; cur = cur.AddDays(1))\n {\n try\n {\n recur = rp.GetOccurrence(cur);\n MessageBox.Show(recur.Subject + \" -&gt; \" + cur.ToLongDateString());\n }\n catch\n { }\n }\n }\n else\n {\n MessageBox.Show(item.Subject + \" -&gt; \" + item.Start.ToLongDateString());\n }\n }\n\n}\n</code></pre>\n\n<blockquote>\n <p>it is working I try it but you need to add reference about \n Microsoft outlook</p>\n</blockquote>\n" }, { "answer_id": 57530946, "author": "anhoppe", "author_id": 1178267, "author_profile": "https://Stackoverflow.com/users/1178267", "pm_score": 1, "selected": false, "text": "<p>I found this article very useful: <a href=\"https://learn.microsoft.com/en-us/office/client-developer/outlook/pia/how-to-search-and-obtain-appointments-in-a-time-range\" rel=\"nofollow noreferrer\">https://learn.microsoft.com/en-us/office/client-developer/outlook/pia/how-to-search-and-obtain-appointments-in-a-time-range</a></p>\n\n<p>It demonstrates how to get calendar entries in a specified time range. It worked for me. Here is the source code from the article for your convenience :)</p>\n\n<pre><code>using Outlook = Microsoft.Office.Interop.Outlook;\n\nprivate void DemoAppointmentsInRange()\n{\n Outlook.Folder calFolder = Application.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderCalendar)\n as Outlook.Folder;\n DateTime start = DateTime.Now;\n DateTime end = start.AddDays(5);\n Outlook.Items rangeAppts = GetAppointmentsInRange(calFolder, start, end);\n if (rangeAppts != null)\n {\n foreach (Outlook.AppointmentItem appt in rangeAppts)\n {\n Debug.WriteLine(\"Subject: \" + appt.Subject \n + \" Start: \" + appt.Start.ToString(\"g\"));\n }\n }\n}\n\n/// &lt;summary&gt;\n/// Get recurring appointments in date range.\n/// &lt;/summary&gt;\n/// &lt;param name=\"folder\"&gt;&lt;/param&gt;\n/// &lt;param name=\"startTime\"&gt;&lt;/param&gt;\n/// &lt;param name=\"endTime\"&gt;&lt;/param&gt;\n/// &lt;returns&gt;Outlook.Items&lt;/returns&gt;\nprivate Outlook.Items GetAppointmentsInRange(\n Outlook.Folder folder, DateTime startTime, DateTime endTime)\n{\n string filter = \"[Start] &gt;= '\"\n + startTime.ToString(\"g\")\n + \"' AND [End] &lt;= '\"\n + endTime.ToString(\"g\") + \"'\";\n Debug.WriteLine(filter);\n try\n {\n Outlook.Items calItems = folder.Items;\n calItems.IncludeRecurrences = true;\n calItems.Sort(\"[Start]\", Type.Missing);\n Outlook.Items restrictItems = calItems.Restrict(filter);\n if (restrictItems.Count &gt; 0)\n {\n return restrictItems;\n }\n else\n {\n return null;\n }\n }\n catch { return null; }\n }\n</code></pre>\n" }, { "answer_id": 73280470, "author": "Binxalot", "author_id": 1086549, "author_profile": "https://Stackoverflow.com/users/1086549", "pm_score": 0, "selected": false, "text": "<p>Here's a combination of a few answers to get entries from the past 30 days. Will output to console but you can take the console log output and save to a file or whatever you want from there. Thanks to everyone for posting their code here, was very helpful!</p>\n<pre><code>using Microsoft.Office.Interop.Outlook;\n\nvoid GetAllCalendarItems()\n{\n\nMicrosoft.Office.Interop.Outlook.Application oApp = null;\nMicrosoft.Office.Interop.Outlook.NameSpace mapiNamespace = null;\nMicrosoft.Office.Interop.Outlook.MAPIFolder CalendarFolder = null;\nMicrosoft.Office.Interop.Outlook.Items outlookCalendarItems = null;\n\noApp = new Microsoft.Office.Interop.Outlook.Application();\nmapiNamespace = oApp.GetNamespace(&quot;MAPI&quot;); ;\nCalendarFolder = mapiNamespace.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderCalendar);\noutlookCalendarItems = CalendarFolder.Items;\noutlookCalendarItems.IncludeRecurrences = false;\n\nConsole.WriteLine(&quot;Showing Calendar Items From the last 30 days&quot;);\n\n//Set your dates here...\nDateTime startTime = DateTime.Now.AddDays(-31);\nDateTime endTime = DateTime.Now;\n\nstring filter = &quot;[Start] &gt;= '&quot;\n + startTime.ToString(&quot;g&quot;)\n + &quot;' AND [End] &lt;= '&quot;\n + endTime.ToString(&quot;g&quot;) + &quot;'&quot;;\n\ntry\n{\n\n outlookCalendarItems.Sort(&quot;[Start]&quot;, Type.Missing);\n\n\n foreach (Microsoft.Office.Interop.Outlook.AppointmentItem item in outlookCalendarItems.Restrict(filter))\n {\n\n Console.WriteLine(item.Subject + &quot; -&gt; &quot; + item.Start.ToLongDateString());\n\n }\n\n\n}\ncatch { }\n\n\nConsole.WriteLine(&quot;Finished&quot;);\n}\n\n\nGetAllCalendarItems();\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90899", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
How can I get all items from a specific calendar (for a specific date). Lets say for instance that I have a calendar with a recurring item every Monday evening. When I request all items like this: ``` CalendarItems = CalendarFolder.Items; CalendarItems.IncludeRecurrences = true; ``` I only get 1 item... Is there an easy way to get **all** items (main item + derived items) from a calendar? In my specific situation it can be possible to set a date limit but it would be cool just to get all items (my recurring items are time limited themselves). **I'm using the Microsoft Outlook 12 Object library (Microsoft.Office.Interop.Outlook)**.
I believe that you must Restrict or Find in order to get recurring appointments, otherwise Outlook won't expand them. Also, you must Sort by Start *before* setting IncludeRecurrences.
90,940
<p>I'm writing the memory manager for an application, as part of a team of twenty-odd coders. We're running out of memory quota and we need to be able to see what's going on, since we only appear to be using about 700Mb. I need to be able to report where it's all going - fragmentation etc. Any ideas?</p>
[ { "answer_id": 91054, "author": "Suma", "author_id": 16673, "author_profile": "https://Stackoverflow.com/users/16673", "pm_score": 3, "selected": true, "text": "<p>You can use existing memory debugging tools for this, I found Memory Validator <a href=\"http://www.vmvalidator.com/cpp/memory/index.html\" rel=\"nofollow noreferrer\" title=\"Memory Validator\">1</a> quite useful, it is able to track both API level (heap, new...) and OS level (Virtual Memory) allocations and show virtual memory maps.</p>\n\n<p>The other option which I also found very usefull is to be able to dump a map of the whole virtual space based on VirtualQuery function. My code for this looks like this:</p>\n\n<pre><code>void PrintVMMap()\n{\n size_t start = 0;\n // TODO: make portable - not compatible with /3GB, 64b OS or 64b app\n size_t end = 1U&lt;&lt;31; // map 32b user space only - kernel space not accessible\n SYSTEM_INFO si;\n GetSystemInfo(&amp;si);\n size_t pageSize = si.dwPageSize;\n size_t longestFreeApp = 0;\n\n int index=0;\n for (size_t addr = start; addr&lt;end; )\n {\n MEMORY_BASIC_INFORMATION buffer;\n SIZE_T retSize = VirtualQuery((void *)addr,&amp;buffer,sizeof(buffer));\n if (retSize==sizeof(buffer) &amp;&amp; buffer.RegionSize&gt;0)\n {\n // dump information about this region\n printf(.... some buffer information here ....);\n // track longest feee region - usefull fragmentation indicator\n if (buffer.State&amp;MEM_FREE)\n {\n if (buffer.RegionSize&gt;longestFreeApp) longestFreeApp = buffer.RegionSize;\n }\n addr += buffer.RegionSize;\n index+= buffer.RegionSize/pageSize;\n }\n else\n {\n // always proceed\n addr += pageSize;\n index++;\n }\n }\n printf(\"Longest free VM region: %d\",longestFreeApp);\n}\n</code></pre>\n" }, { "answer_id": 93015, "author": "Mike Dimmick", "author_id": 6970, "author_profile": "https://Stackoverflow.com/users/6970", "pm_score": 1, "selected": false, "text": "<p>You can also find out information about the heaps in a process with Heap32ListFirst/Heap32ListNext, and about loaded modules with Module32First/Module32Next, from the Tool Help API.</p>\n\n<p>'Tool Help' originated on Windows 9x. The original process information API on Windows NT was PSAPI, which offers functions which partially (but not completely) overlap with Tool Help.</p>\n" }, { "answer_id": 100696, "author": "hatcat", "author_id": 11483, "author_profile": "https://Stackoverflow.com/users/11483", "pm_score": 0, "selected": false, "text": "<p>Our (huge) application (a Win32 game) started throwing \"Not enough quota\" exceptions recently, and I was charged with finding out where all the memory was going. It is not a trivial job - this question and <a href=\"https://stackoverflow.com/questions/84234/is-there-a-single-resource-which-explains-windows-memory-thoroughly\">this one</a> were my first attempts at finding out. Heap behaviour is unexpected, and accurately tracking how much quota you've used and how much is available has so far proved impossible. In fact, it's not particularly useful information anyway - \"quota\" and \"somewhere to put things\" are subtly and annoyingly different concepts. The accepted answer is as good as it gets, although enumerating heaps and modules is also handy. I used <a href=\"http://www.microsoft.com/downloads/details.aspx?familyid=28bd5941-c458-46f1-b24d-f60151d875a3&amp;displaylang=en\" rel=\"nofollow noreferrer\">DebugDiag</a> from MS to view the true horror of the situation, and understand how hard it is to actually thoroughly track everything.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90940", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11483/" ]
I'm writing the memory manager for an application, as part of a team of twenty-odd coders. We're running out of memory quota and we need to be able to see what's going on, since we only appear to be using about 700Mb. I need to be able to report where it's all going - fragmentation etc. Any ideas?
You can use existing memory debugging tools for this, I found Memory Validator [1](http://www.vmvalidator.com/cpp/memory/index.html "Memory Validator") quite useful, it is able to track both API level (heap, new...) and OS level (Virtual Memory) allocations and show virtual memory maps. The other option which I also found very usefull is to be able to dump a map of the whole virtual space based on VirtualQuery function. My code for this looks like this: ``` void PrintVMMap() { size_t start = 0; // TODO: make portable - not compatible with /3GB, 64b OS or 64b app size_t end = 1U<<31; // map 32b user space only - kernel space not accessible SYSTEM_INFO si; GetSystemInfo(&si); size_t pageSize = si.dwPageSize; size_t longestFreeApp = 0; int index=0; for (size_t addr = start; addr<end; ) { MEMORY_BASIC_INFORMATION buffer; SIZE_T retSize = VirtualQuery((void *)addr,&buffer,sizeof(buffer)); if (retSize==sizeof(buffer) && buffer.RegionSize>0) { // dump information about this region printf(.... some buffer information here ....); // track longest feee region - usefull fragmentation indicator if (buffer.State&MEM_FREE) { if (buffer.RegionSize>longestFreeApp) longestFreeApp = buffer.RegionSize; } addr += buffer.RegionSize; index+= buffer.RegionSize/pageSize; } else { // always proceed addr += pageSize; index++; } } printf("Longest free VM region: %d",longestFreeApp); } ```
90,949
<p>There is no documentation on cakephp.org and I am unable to find one on google. Please link me some documentation or supply one!</p>
[ { "answer_id": 100658, "author": "David Heggie", "author_id": 4309, "author_profile": "https://Stackoverflow.com/users/4309", "pm_score": 5, "selected": true, "text": "<p>The translate behavior is another of CakePHP's very useful but poorly documented features. I've implemented it a couple of times with reasonable success in multi-lingual websites along the following lines.</p>\n\n<p>Firstly, the translate behavior will only internationalize the database content of your site. If you've any more static content, you'll want to look at Cake's <code>__('string')</code> wrapper function and <code>gettext</code> (there's some useful information about this <a href=\"https://stackoverflow.com/questions/39562/how-do-you-build-a-multi-language-web-site#41379\">here</a>)</p>\n\n<p>Assuming there's Contents that we want to translate with the following db table:</p>\n\n<pre><code>CREATE TABLE `contents` (\n `id` int(11) unsigned NOT NULL auto_increment,\n `title` varchar(255) default NULL,\n `body` text,\n PRIMARY KEY (`id`),\n) ENGINE=InnoDB DEFAULT CHARSET=utf8;\n</code></pre>\n\n<p>The content.php model then has:</p>\n\n<pre><code>var $actsAs = array('Translate' =&gt; array('title' =&gt; 'titleTranslation',\n 'body' =&gt; 'bodyTranslation'\n ));\n</code></pre>\n\n<p>in its definition. You then need to add the i18n table to the database thusly:</p>\n\n<pre><code>CREATE TABLE `i18n` (\n `id` int(10) NOT NULL auto_increment,\n `locale` varchar(6) NOT NULL,\n `model` varchar(255) NOT NULL,\n `foreign_key` int(10) NOT NULL,\n `field` varchar(255) NOT NULL,\n `content` mediumtext,\n PRIMARY KEY (`id`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8;\n</code></pre>\n\n<p>Then when you're saving the data to the database in your controller, set the locale to the language you want (this example would be for Polish):</p>\n\n<pre><code>$this-&gt;Content-&gt;locale = 'pol';\n$result = $this-&gt;Content-&gt;save($this-&gt;data);\n</code></pre>\n\n<p>This will create entries in the i18n table for the title and body fields for the pol locale. Finds will find based on the current locale set in the user's browser, returning an array like:</p>\n\n<pre><code>[Content]\n [id]\n [titleTranslation]\n [bodyTranslation]\n</code></pre>\n\n<p>We use the excellent <a href=\"http://bakery.cakephp.org/articles/view/p28n-the-top-to-bottom-persistent-internationalization-tutorial\" rel=\"nofollow noreferrer\">p28n component</a> to implement a language switching solution that works pretty well with the gettext and translate behaviours.</p>\n\n<p>It's not a perfect system - as it creates HABTM relationships on the fly, it can cause some issues with other relationships you may have created manually, but if you're careful, it can work well.</p>\n" }, { "answer_id": 22088437, "author": "Sp0T", "author_id": 3007408, "author_profile": "https://Stackoverflow.com/users/3007408", "pm_score": 0, "selected": false, "text": "<p>For anyone searching the same thing, cakephp updated their documentation. For Translate Behavior go <a href=\"http://book.cakephp.org/2.0/en/core-libraries/behaviors/translate.html\" rel=\"nofollow\">here..</a></p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90949", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4013/" ]
There is no documentation on cakephp.org and I am unable to find one on google. Please link me some documentation or supply one!
The translate behavior is another of CakePHP's very useful but poorly documented features. I've implemented it a couple of times with reasonable success in multi-lingual websites along the following lines. Firstly, the translate behavior will only internationalize the database content of your site. If you've any more static content, you'll want to look at Cake's `__('string')` wrapper function and `gettext` (there's some useful information about this [here](https://stackoverflow.com/questions/39562/how-do-you-build-a-multi-language-web-site#41379)) Assuming there's Contents that we want to translate with the following db table: ``` CREATE TABLE `contents` ( `id` int(11) unsigned NOT NULL auto_increment, `title` varchar(255) default NULL, `body` text, PRIMARY KEY (`id`), ) ENGINE=InnoDB DEFAULT CHARSET=utf8; ``` The content.php model then has: ``` var $actsAs = array('Translate' => array('title' => 'titleTranslation', 'body' => 'bodyTranslation' )); ``` in its definition. You then need to add the i18n table to the database thusly: ``` CREATE TABLE `i18n` ( `id` int(10) NOT NULL auto_increment, `locale` varchar(6) NOT NULL, `model` varchar(255) NOT NULL, `foreign_key` int(10) NOT NULL, `field` varchar(255) NOT NULL, `content` mediumtext, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; ``` Then when you're saving the data to the database in your controller, set the locale to the language you want (this example would be for Polish): ``` $this->Content->locale = 'pol'; $result = $this->Content->save($this->data); ``` This will create entries in the i18n table for the title and body fields for the pol locale. Finds will find based on the current locale set in the user's browser, returning an array like: ``` [Content] [id] [titleTranslation] [bodyTranslation] ``` We use the excellent [p28n component](http://bakery.cakephp.org/articles/view/p28n-the-top-to-bottom-persistent-internationalization-tutorial) to implement a language switching solution that works pretty well with the gettext and translate behaviours. It's not a perfect system - as it creates HABTM relationships on the fly, it can cause some issues with other relationships you may have created manually, but if you're careful, it can work well.
90,971
<p>Let's say I have a class:</p> <pre><code>class Foo { public string Bar { get { ... } } public string this[int index] { get { ... } } } </code></pre> <p>I can bind to these two properties using "{Binding Path=Bar}" and "{Binding Path=[x]}". Fine.</p> <p>Now let's say I want to implement INotifyPropertyChanged:</p> <pre><code>class Foo : INotifyPropertyChanged { public string Bar { get { ... } set { ... if( PropertyChanged != null ) { PropertyChanged( this, new PropertyChangedEventArgs( "Bar" ) ); } } } public string this[int index] { get { ... } set { ... if( PropertyChanged != null ) { PropertyChanged( this, new PropertyChangedEventArgs( "????" ) ); } } } public event PropertyChangedEventHandler PropertyChanged; } </code></pre> <p>What goes in the part marked ????? (I've tried string.Format("[{0}]", index) and it doesn't work). Is this a bug in WPF, is there an alternative syntax, or is it simply that INotifyPropertyChanged isn't as powerful as normal binding?</p>
[ { "answer_id": 91020, "author": "Cameron MacFarland", "author_id": 3820, "author_profile": "https://Stackoverflow.com/users/3820", "pm_score": 2, "selected": false, "text": "<p>Don't know for sure if this'll work, but reflector shows that the get and set methods for an indexed property are called get_Item and set_Item. Perhaps you could try Item and see if that works.</p>\n" }, { "answer_id": 91083, "author": "stusmith", "author_id": 6604, "author_profile": "https://Stackoverflow.com/users/6604", "pm_score": 5, "selected": true, "text": "<p>Thanks to Cameron's suggestion, I've found the correct syntax, which is:</p>\n\n<pre><code>Item[]\n</code></pre>\n\n<p>Which updates everything (all index values) bound to that indexed property.</p>\n" }, { "answer_id": 798762, "author": "jEROD", "author_id": 97207, "author_profile": "https://Stackoverflow.com/users/97207", "pm_score": 3, "selected": false, "text": "<pre><code>PropertyChanged( this, new PropertyChangedEventArgs( \"Item[]\" ) )\n</code></pre>\n\n<p>for all indexes and</p>\n\n<pre><code>PropertyChanged( this, new PropertyChangedEventArgs( \"Item[\" + index + \"]\" ) )\n</code></pre>\n\n<p>for a single item</p>\n\n<p>greetings, jerod</p>\n" }, { "answer_id": 10500334, "author": "Adi Lester", "author_id": 389966, "author_profile": "https://Stackoverflow.com/users/389966", "pm_score": 3, "selected": false, "text": "<p>Avoiding strings in your code, you can use the constant <code>Binding.IndexerName</code>, which is actually <code>\"Item[]\"</code></p>\n\n<pre><code>new PropertyChangedEventArgs(Binding.IndexerName)\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6604/" ]
Let's say I have a class: ``` class Foo { public string Bar { get { ... } } public string this[int index] { get { ... } } } ``` I can bind to these two properties using "{Binding Path=Bar}" and "{Binding Path=[x]}". Fine. Now let's say I want to implement INotifyPropertyChanged: ``` class Foo : INotifyPropertyChanged { public string Bar { get { ... } set { ... if( PropertyChanged != null ) { PropertyChanged( this, new PropertyChangedEventArgs( "Bar" ) ); } } } public string this[int index] { get { ... } set { ... if( PropertyChanged != null ) { PropertyChanged( this, new PropertyChangedEventArgs( "????" ) ); } } } public event PropertyChangedEventHandler PropertyChanged; } ``` What goes in the part marked ????? (I've tried string.Format("[{0}]", index) and it doesn't work). Is this a bug in WPF, is there an alternative syntax, or is it simply that INotifyPropertyChanged isn't as powerful as normal binding?
Thanks to Cameron's suggestion, I've found the correct syntax, which is: ``` Item[] ``` Which updates everything (all index values) bound to that indexed property.
90,977
<p>Emacs Lisp has <code>replace-string</code> but has no <code>replace-char</code>. I want to replace "typographic" curly quotes (Emacs code for this character is hexadecimal 53979) with regular ASCII quotes, and I can do so with:</p> <pre><code>(replace-string (make-string 1 ?\x53979) "'") </code></pre> <p>I think it would be better with <code>replace-char</code>. </p> <p>What is the best way to do this?</p>
[ { "answer_id": 91043, "author": "0124816", "author_id": 11521, "author_profile": "https://Stackoverflow.com/users/11521", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>which would certainly be better with replace-char. Any way to improve my code?</p>\n</blockquote>\n\n<p>Is it actually slow to the point where it matters? My elisp is usually ridiculously inefficient and I never notice. (I only use it for editor tools though, YMMV if you're building the next MS live search with it.)</p>\n\n<p>Also, reading the docs:</p>\n\n<pre><code>This function is usually the wrong thing to use in a Lisp program.\nWhat you probably want is a loop like this:\n (while (search-forward \"’\" nil t)\n (replace-match \"'\" nil t))\n</code></pre>\n\n<p>This answer is probably GPL licensed now.</p>\n" }, { "answer_id": 97261, "author": "cjm", "author_id": 8355, "author_profile": "https://Stackoverflow.com/users/8355", "pm_score": 4, "selected": true, "text": "<p>Why not just use</p>\n\n<pre><code>(replace-string \"\\x53979\" \"'\")\n</code></pre>\n\n<p>or</p>\n\n<pre><code>(while (search-forward \"\\x53979\" nil t)\n (replace-match \"'\" nil t))\n</code></pre>\n\n<p>as recommended in the documentation for replace-string?</p>\n" }, { "answer_id": 1052892, "author": "Yoo", "author_id": 37664, "author_profile": "https://Stackoverflow.com/users/37664", "pm_score": 2, "selected": false, "text": "<p>What about this</p>\n\n<pre><code>(defun my-replace-smart-quotes (beg end)\n \"replaces ’ (the curly typographical quote, unicode hexa 2019) to ' (ordinary ascii quote).\"\n (interactive \"r\")\n (save-excursion\n (format-replace-strings '((\"\\x2019\" . \"'\")) nil beg end)))\n</code></pre>\n\n<p>Once you have that in your dotemacs, you can paste elisp example codes (from blogs and etc) to your scratch buffer and then immediately press C-M-\\ (to indent it properly) and then M-x my-replace-smart-quotes (to fix smart quotes) and finally C-x C-e (to run it).</p>\n\n<p>I find that the curly quote is always hexa 2019, are you sure it's 53979 in your case? You can check characters in buffer with C-u C-x =.</p>\n\n<p>I think you can write \"’\" in place of \"\\x2019\" in the definition of my-replace-smart-quotes and be fine. It's just to be on the safe side.</p>\n" }, { "answer_id": 44957530, "author": "notetiene", "author_id": 7879170, "author_profile": "https://Stackoverflow.com/users/7879170", "pm_score": 3, "selected": false, "text": "<p>This is the way I replace characters in elisp:</p>\n\n<pre><code>(subst-char-in-string ?' ?’ \"John's\")\n</code></pre>\n\n<p>gives:</p>\n\n<pre><code>\"John’s\"\n</code></pre>\n\n<p>Note that this function doesn't accept characters as string. The first and second argument must be a literal character (either using the <code>?</code> notation or <code>string-to-char</code>).</p>\n\n<p>Also note that this function can be destructive if the optional <code>inplace</code> argument is non-nil.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90977", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15625/" ]
Emacs Lisp has `replace-string` but has no `replace-char`. I want to replace "typographic" curly quotes (Emacs code for this character is hexadecimal 53979) with regular ASCII quotes, and I can do so with: ``` (replace-string (make-string 1 ?\x53979) "'") ``` I think it would be better with `replace-char`. What is the best way to do this?
Why not just use ``` (replace-string "\x53979" "'") ``` or ``` (while (search-forward "\x53979" nil t) (replace-match "'" nil t)) ``` as recommended in the documentation for replace-string?
90,982
<p>I'm looking for a good, clean way to go around the fact that PHP5 still doesn't support multiple inheritance. Here's the class hierarchy:</p> <p>Message<br> -- TextMessage<br> -------- InvitationTextMessage<br> -- EmailMessage<br> -------- InvitationEmailMessage </p> <p>The two types of Invitation* classes have a lot in common; i'd love to have a common parent class, Invitation, that they both would inherit from. Unfortunately, they also have a lot in common with their current ancestors... TextMessage and EmailMessage. Classical desire for multiple inheritance here. </p> <p>What's the most light-weight approach to solve the issue? </p> <p>Thanks!</p>
[ { "answer_id": 90991, "author": "danio", "author_id": 12663, "author_profile": "https://Stackoverflow.com/users/12663", "pm_score": 2, "selected": false, "text": "<p>It sounds like the <a href=\"http://en.wikipedia.org/wiki/Decorator_pattern\" rel=\"nofollow noreferrer\">decorator pattern</a> may be suitable, but hard to tell without more details.</p>\n" }, { "answer_id": 90992, "author": "joelhardi", "author_id": 11438, "author_profile": "https://Stackoverflow.com/users/11438", "pm_score": 3, "selected": false, "text": "<p>The Symfony framework has a <a href=\"https://symfony.com/legacy/doc/gentle-introduction/1_4/en/17-Extending-Symfony\" rel=\"nofollow noreferrer\">mixin plugin for this</a>, you might want to check it out -- even just for ideas, if not to use it.</p>\n\n<p>The \"design pattern\" answer is to abstract the shared functionality into a separate component, and compose at runtime. Think about a way to abstract out the Invitation functionality out as a class that gets associated with your Message classes in some way other than inheritance.</p>\n" }, { "answer_id": 91003, "author": "DeeCee", "author_id": 5895, "author_profile": "https://Stackoverflow.com/users/5895", "pm_score": 0, "selected": false, "text": "<p>Same problem like Java. Try using interfaces with abstract functions for solving that problem</p>\n" }, { "answer_id": 91004, "author": "Matthias Kestenholz", "author_id": 317346, "author_profile": "https://Stackoverflow.com/users/317346", "pm_score": 4, "selected": false, "text": "<p>Maybe you can replace an 'is-a' relation with a 'has-a' relation? An Invitation might have a Message, but it does not necessarily need to 'is-a' message. An Invitation f.e. might be confirmed, which does not go well together with the Message model.</p>\n\n<p>Search for 'composition vs. inheritance' if you need to know more about that.</p>\n" }, { "answer_id": 91012, "author": "Cheekysoft", "author_id": 1820, "author_profile": "https://Stackoverflow.com/users/1820", "pm_score": 0, "selected": false, "text": "<p>PHP does support interfaces. This could be a good bet, depending on your use-cases.</p>\n" }, { "answer_id": 91303, "author": "Michał Niedźwiedzki", "author_id": 2169, "author_profile": "https://Stackoverflow.com/users/2169", "pm_score": 8, "selected": true, "text": "<p>Alex, most of the times you need multiple inheritance is a signal your object structure is somewhat incorrect. In situation you outlined I see you have class responsibility simply too broad. If Message is part of application business model, it should not take care about rendering output. Instead, you could split responsibility and use MessageDispatcher that sends the Message passed using text or html backend. I don't know your code, but let me simulate it this way:</p>\n<pre><code>$m = new Message();\n$m-&gt;type = 'text/html';\n$m-&gt;from = 'John Doe &lt;[email protected]&gt;';\n$m-&gt;to = 'Random Hacker &lt;[email protected]&gt;';\n$m-&gt;subject = 'Invitation email';\n$m-&gt;importBody('invitation.html');\n\n$d = new MessageDispatcher();\n$d-&gt;dispatch($m);\n</code></pre>\n<p>This way you can add some specialisation to Message class:</p>\n<pre><code>$htmlIM = new InvitationHTMLMessage(); // html type, subject and body configuration in constructor\n$textIM = new InvitationTextMessage(); // text type, subject and body configuration in constructor\n\n$d = new MessageDispatcher();\n$d-&gt;dispatch($htmlIM);\n$d-&gt;dispatch($textIM);\n</code></pre>\n<p>Note that MessageDispatcher would make a decision whether to send as HTML or plain text depending on <code>type</code> property in Message object passed.</p>\n<pre><code>// in MessageDispatcher class\npublic function dispatch(Message $m) {\n if ($m-&gt;type == 'text/plain') {\n $this-&gt;sendAsText($m);\n } elseif ($m-&gt;type == 'text/html') {\n $this-&gt;sendAsHTML($m);\n } else {\n throw new Exception(&quot;MIME type {$m-&gt;type} not supported&quot;);\n }\n}\n</code></pre>\n<p>To sum it up, responsibility is split between two classes. Message configuration is done in InvitationHTMLMessage/InvitationTextMessage class, and sending algorithm is delegated to dispatcher. This is called Strategy Pattern, you can read more on it <a href=\"https://web.archive.org/web/20190613203216/https://www.dofactory.com/net/strategy-design-pattern\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 92896, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>I have a couple of questions to ask to clarify what you are doing:</p>\n\n<p>1) Does your message object <em>just</em> contain a message e.g. body, recipient, schedule time?\n2) What do you intend to do with your Invitation object? Does it need to be treated specially compared to an EmailMessage?\n3) If so WHAT is so special about it?\n4) If that is then the case, why do the message types need handling differently for an invitation?\n5) What if you want to send a welcome message or an OK message? Are they new objects too?</p>\n\n<p>It does sound like you are trying combine too much functionality into a set of objects that should only be concerned with holding a message contents - and not how it should be handled. To me, you see, there is no difference between an invitation or a standard message. If the invitation requires special handling, then that means application logic and not a message type.</p>\n\n<p>For example: a system I built had a shared base message object that was extended into SMS, Email, and other message types. However: these were not extended further - an invitation message was simply pre-defined text to be sent via a message of type Email. A specific Invitation application would be concerned with validation and other requirements for an invite. After all, all you want to do is send message X to recipient Y which should be a discrete system in its own right.</p>\n" }, { "answer_id": 3975764, "author": "Ralph Ritoch", "author_id": 481399, "author_profile": "https://Stackoverflow.com/users/481399", "pm_score": 2, "selected": false, "text": "<p>This is both a question and a solution....</p>\n\n<p>What about the magical _<em>call(),</em>_get(), __set() methods? I have not yet tested this solution but what if you make a multiInherit class. A protected variable in a child class could contain an array of classes to inherit. The constructor in the multi-interface class could create instances of each of the classes that are being inherited and link them to a private property, say _ext. The __call() method could use the method_exists() function on each of the classes in the _ext array to locate the correct method to call. __get() and __set could be used to locate internal properties, or if your an expert with references you could make the properties of the child class and the inherited classes be references to the same data. The multiple inheritance of your object would be transparent to code using those objects. Also, internal objects could access the inherited objects directly if needed as long as the _ext array is indexed by class name. I have envisioned creating this super-class and have not yet implemented it as I feel that if it works than it could lead to developing some vary bad programming habits.</p>\n" }, { "answer_id": 9817919, "author": "Simon East", "author_id": 195835, "author_profile": "https://Stackoverflow.com/users/195835", "pm_score": 3, "selected": false, "text": "<p>If I can quote Phil in <a href=\"https://stackoverflow.com/questions/7762883/does-anyone-know-how-can-i-extends-2-classes-in-the-class-in-php\">this thread</a>...</p>\n\n<blockquote>\n <p>PHP, like Java, does not support multiple inheritance.</p>\n \n <p>Coming in PHP 5.4 will be <a href=\"https://secure.php.net/manual/en/language.oop5.traits.php\" rel=\"nofollow noreferrer\"><strong>traits</strong></a> which attempt to provide a solution\n to this problem.</p>\n \n <p>In the meantime, you would be best to re-think your class design. You\n can implement multiple interfaces if you're after an extended API to\n your classes.</p>\n</blockquote>\n\n<p>And Chris....</p>\n\n<blockquote>\n <p>PHP doesn't really support multiple inheritance, but there are some\n (somewhat messy) ways to implement it. Check out this URL for some\n examples:</p>\n \n <p><a href=\"http://www.jasny.net/articles/how-i-php-multiple-inheritance/\" rel=\"nofollow noreferrer\">http://www.jasny.net/articles/how-i-php-multiple-inheritance/</a></p>\n</blockquote>\n\n<p>Thought they both had useful links. Can't wait to try out traits or maybe some mixins...</p>\n" }, { "answer_id": 10727781, "author": "nube", "author_id": 1362094, "author_profile": "https://Stackoverflow.com/users/1362094", "pm_score": -1, "selected": false, "text": "<p>How about an Invitation class right below the Message class?</p>\n\n<p>so the hierarchy goes:</p>\n\n<p>Message<br>\n--- Invitation<br>\n------ TextMessage<br>\n------ EmailMessage </p>\n\n<p>And in Invitation class, add the functionality that was in InvitationTextMessage and InvitationEmailMessage. </p>\n\n<p>I know that Invitation isn't really a type of Message, it's more a functionality of Message. So I'm not sure if this is good OO design or not.</p>\n" }, { "answer_id": 13397169, "author": "MatthewPearson", "author_id": 1689169, "author_profile": "https://Stackoverflow.com/users/1689169", "pm_score": 2, "selected": false, "text": "<p>I'm using traits in PHP 5.4 as the way of solving this.\n<a href=\"http://php.net/manual/en/language.oop5.traits.php\" rel=\"nofollow\">http://php.net/manual/en/language.oop5.traits.php</a></p>\n\n<p>This allows for classic inheritance with extends, but also gives the possible of placing common functionality and properties into a 'trait'. As the manual says:</p>\n\n<blockquote>\n <p>Traits is a mechanism for code reuse in single inheritance languages such as PHP. A Trait is intended to reduce some limitations of single inheritance by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies.</p>\n</blockquote>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16668/" ]
I'm looking for a good, clean way to go around the fact that PHP5 still doesn't support multiple inheritance. Here's the class hierarchy: Message -- TextMessage -------- InvitationTextMessage -- EmailMessage -------- InvitationEmailMessage The two types of Invitation\* classes have a lot in common; i'd love to have a common parent class, Invitation, that they both would inherit from. Unfortunately, they also have a lot in common with their current ancestors... TextMessage and EmailMessage. Classical desire for multiple inheritance here. What's the most light-weight approach to solve the issue? Thanks!
Alex, most of the times you need multiple inheritance is a signal your object structure is somewhat incorrect. In situation you outlined I see you have class responsibility simply too broad. If Message is part of application business model, it should not take care about rendering output. Instead, you could split responsibility and use MessageDispatcher that sends the Message passed using text or html backend. I don't know your code, but let me simulate it this way: ``` $m = new Message(); $m->type = 'text/html'; $m->from = 'John Doe <[email protected]>'; $m->to = 'Random Hacker <[email protected]>'; $m->subject = 'Invitation email'; $m->importBody('invitation.html'); $d = new MessageDispatcher(); $d->dispatch($m); ``` This way you can add some specialisation to Message class: ``` $htmlIM = new InvitationHTMLMessage(); // html type, subject and body configuration in constructor $textIM = new InvitationTextMessage(); // text type, subject and body configuration in constructor $d = new MessageDispatcher(); $d->dispatch($htmlIM); $d->dispatch($textIM); ``` Note that MessageDispatcher would make a decision whether to send as HTML or plain text depending on `type` property in Message object passed. ``` // in MessageDispatcher class public function dispatch(Message $m) { if ($m->type == 'text/plain') { $this->sendAsText($m); } elseif ($m->type == 'text/html') { $this->sendAsHTML($m); } else { throw new Exception("MIME type {$m->type} not supported"); } } ``` To sum it up, responsibility is split between two classes. Message configuration is done in InvitationHTMLMessage/InvitationTextMessage class, and sending algorithm is delegated to dispatcher. This is called Strategy Pattern, you can read more on it [here](https://web.archive.org/web/20190613203216/https://www.dofactory.com/net/strategy-design-pattern).
90,988
<p>Using eclipse 3.3.2 with MyEclipse installed. For some reason if a file isn't called build.xml then it isnt' recognised as an ant file. The file association for *.xml includes ant and says "locked by 'Ant Buildfile' content type.</p> <p>The run-as menu is broken. Even if the editor association works run-as doesn't.</p> <p>The ant buildfiles in question are correctly formatted. They work fine if you call them build.xml or if you use them anywhere else. Eclipse just won't recognise and thus wont allow you to run them.</p>
[ { "answer_id": 91324, "author": "Ashley Mercer", "author_id": 13065, "author_profile": "https://Stackoverflow.com/users/13065", "pm_score": 0, "selected": false, "text": "<p>If you open the \"File Associations\" page (Window -> Preferences -> General -> Editors -> File Associations) you should see a list of all file types which Eclipse recognises. Scroll down to the \"*.xml\" entry, highlight \"Ant Editor\" in the \"Associated Editors\" pane and hit the \"Default\" button on the right-hand side. Eclipse should now open any XML files with the ant editor.</p>\n" }, { "answer_id": 91557, "author": "McDowell", "author_id": 304, "author_profile": "https://Stackoverflow.com/users/304", "pm_score": 2, "selected": false, "text": "<p>The environment inspects the file contents to determine if it is an Ant file (if it isn't called \"build.xml\"). Add the following to the XML file:</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;\n\n&lt;project name=\"myproject\" default=\"t1\"&gt;\n &lt;target name=\"t1\"&gt;&lt;/target&gt;\n&lt;/project&gt;\n</code></pre>\n\n<p>You should now see the \"Ant Editor\" in the \"Open With >\" menu when you right-click on the file.</p>\n" }, { "answer_id": 417444, "author": "Brian Fisher", "author_id": 43816, "author_profile": "https://Stackoverflow.com/users/43816", "pm_score": 1, "selected": false, "text": "<p>I was having a similar problem and found that the Ant Tools weren't included in the Eclipse binary I downloaded. You can try installing the Eclipse Java Development Tools. These can be found under Java Development > Eclipse Java Development Tools in Help > Software Updates > Available Software.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Using eclipse 3.3.2 with MyEclipse installed. For some reason if a file isn't called build.xml then it isnt' recognised as an ant file. The file association for \*.xml includes ant and says "locked by 'Ant Buildfile' content type. The run-as menu is broken. Even if the editor association works run-as doesn't. The ant buildfiles in question are correctly formatted. They work fine if you call them build.xml or if you use them anywhere else. Eclipse just won't recognise and thus wont allow you to run them.
The environment inspects the file contents to determine if it is an Ant file (if it isn't called "build.xml"). Add the following to the XML file: ``` <?xml version="1.0" encoding="UTF-8"?> <project name="myproject" default="t1"> <target name="t1"></target> </project> ``` You should now see the "Ant Editor" in the "Open With >" menu when you right-click on the file.
90,996
<p>I have an IList that contains items ( parent first ), they need to be added to a Diagram Document in the reverse order so that the parent is added last, drawn on top so that it is the first thing to be selected by the user.</p> <p>What's the best way to do it? Something better/more elegant than what I am doing currently which I post below..</p>
[ { "answer_id": 90998, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": 0, "selected": false, "text": "<p>NewItems is my List here... This is a bit clunky though. </p>\n\n<pre><code>for(int iLooper = obEvtArgs.NewItems.Count-1; iLooper &gt;= 0; iLooper--)\n {\n GoViewBoy.Document.Add(CreateNodeFor(obEvtArgs.NewItems[iLooper] as IMySpecificObject, obNextPos));\n }\n</code></pre>\n" }, { "answer_id": 91044, "author": "Davy Landman", "author_id": 11098, "author_profile": "https://Stackoverflow.com/users/11098", "pm_score": 4, "selected": true, "text": "<p>If you have .NET 3.5 you could use LINQ's Reverse?</p>\n\n<pre><code>foreach(var item in obEvtArgs.NewItems.Reverse())\n{\n ...\n}\n</code></pre>\n\n<p>(Assuming you're talking about the generic IList)</p>\n" }, { "answer_id": 146294, "author": "Emperor XLII", "author_id": 2495, "author_profile": "https://Stackoverflow.com/users/2495", "pm_score": 2, "selected": false, "text": "<p>Based on the comments to <a href=\"https://stackoverflow.com/questions/90996?sort=votes#91044\">Davy's answer</a>, and <a href=\"https://stackoverflow.com/questions/90996?sort=votes#90998\">Gishu's original answer</a>, you could cast your weakly-typed <code>System.Collections.IList</code> to a generic collection using the <code>System.Linq.Enumerable.Cast</code> extension method:</p>\n\n<pre><code>var reversedCollection = obEvtArgs.NewItems\n .Cast&lt;IMySpecificObject&gt;( )\n .Reverse( );\n</code></pre>\n\n<p>This removes the noise of both the reverse <code>for</code> loop, and the <code>as</code> cast to get a strongly-typed object from the original collection.</p>\n" }, { "answer_id": 17299868, "author": "Rok Strniša", "author_id": 974531, "author_profile": "https://Stackoverflow.com/users/974531", "pm_score": 0, "selected": false, "text": "<p>You don't need LINQ:</p>\n\n<pre class=\"lang-csharp prettyprint-override\"><code>var reversed = new List&lt;T&gt;(original); // assuming original has type IList&lt;T&gt;\nreversed.Reverse();\nforeach (T e in reversed) {\n ...\n}\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90996", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1695/" ]
I have an IList that contains items ( parent first ), they need to be added to a Diagram Document in the reverse order so that the parent is added last, drawn on top so that it is the first thing to be selected by the user. What's the best way to do it? Something better/more elegant than what I am doing currently which I post below..
If you have .NET 3.5 you could use LINQ's Reverse? ``` foreach(var item in obEvtArgs.NewItems.Reverse()) { ... } ``` (Assuming you're talking about the generic IList)
91,108
<p>How do I get my C# program to sleep (pause execution) for 50 milliseconds?</p>
[ { "answer_id": 91119, "author": "Isak Savo", "author_id": 8521, "author_profile": "https://Stackoverflow.com/users/8521", "pm_score": 10, "selected": true, "text": "<pre><code>System.Threading.Thread.Sleep(50);\n</code></pre>\n\n<p>Remember though, that doing this in the main GUI thread will block your GUI from updating (it will feel \"sluggish\")</p>\n\n<p>Just remove the <code>;</code> to make it work for VB.net as well.</p>\n" }, { "answer_id": 91120, "author": "Alexander Prokofyev", "author_id": 11256, "author_profile": "https://Stackoverflow.com/users/11256", "pm_score": 5, "selected": false, "text": "<p>Use this code</p>\n\n<pre><code>using System.Threading;\n// ...\nThread.Sleep(50);\n</code></pre>\n" }, { "answer_id": 91441, "author": "SelvirK", "author_id": 17465, "author_profile": "https://Stackoverflow.com/users/17465", "pm_score": 4, "selected": false, "text": "<pre><code>Thread.Sleep(50);\n</code></pre>\n\n<p>The thread will not be scheduled for execution by the operating system for the amount of time specified. This method changes the state of the thread to include WaitSleepJoin.</p>\n\n<p>This method does not perform standard COM and SendMessage pumping. \nIf you need to sleep on a thread that has STAThreadAttribute, but you want to perform standard COM and SendMessage pumping, consider using one of the overloads of the Join method that specifies a timeout interval. </p>\n\n<pre><code>Thread.Join\n</code></pre>\n" }, { "answer_id": 92512, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 6, "selected": false, "text": "<p>You can't specify an <em>exact</em> sleep time in Windows. You need a real-time OS for that. The best you can do is specify a <em>minimum</em> sleep time. Then it's up to the scheduler to wake up your thread after that. And <strong>never</strong> call <code>.Sleep()</code> on the GUI thread.</p>\n" }, { "answer_id": 5743843, "author": "Marcel Toth", "author_id": 702199, "author_profile": "https://Stackoverflow.com/users/702199", "pm_score": 7, "selected": false, "text": "<p>There are basically 3 choices for waiting in (almost) any programming language:</p>\n\n<ol>\n<li><strong>Loose waiting</strong>\n<ul>\n<li>Executing thread blocks for given time (= does not consume processing power)</li>\n<li>No processing is possible on blocked/waiting thread</li>\n<li>Not so precise</li>\n</ul></li>\n<li><strong>Tight waiting</strong> (also called tight loop)\n<ul>\n<li>processor is VERY busy for the entire waiting interval (in fact, it usually consumes 100% of one core's processing time)</li>\n<li>Some actions can be performed while waiting</li>\n<li>Very precise</li>\n</ul></li>\n<li><strong>Combination</strong> of previous 2\n<ul>\n<li>It usually combines processing efficiency of 1. and preciseness + ability to do something of 2.</li>\n</ul></li>\n</ol>\n\n<hr>\n\n<p><strong>for 1. - Loose waiting in C#:</strong></p>\n\n<pre><code>Thread.Sleep(numberOfMilliseconds);\n</code></pre>\n\n<p>However, windows thread scheduler causes acccuracy of <code>Sleep()</code> to be around 15ms (so Sleep can easily wait for 20ms, even if scheduled to wait just for 1ms).</p>\n\n<p><strong>for 2. - Tight waiting in C# is:</strong></p>\n\n<pre><code>Stopwatch stopwatch = Stopwatch.StartNew();\nwhile (true)\n{\n //some other processing to do possible\n if (stopwatch.ElapsedMilliseconds &gt;= millisecondsToWait)\n {\n break;\n }\n}\n</code></pre>\n\n<p>We could also use <code>DateTime.Now</code> or other means of time measurement, but <code>Stopwatch</code> is much faster (and this would really become visible in tight loop).</p>\n\n<p><strong>for 3. - Combination:</strong></p>\n\n<pre><code>Stopwatch stopwatch = Stopwatch.StartNew();\nwhile (true)\n{\n //some other processing to do STILL POSSIBLE\n if (stopwatch.ElapsedMilliseconds &gt;= millisecondsToWait)\n {\n break;\n }\n Thread.Sleep(1); //so processor can rest for a while\n}\n</code></pre>\n\n<p>This code regularly blocks thread for 1ms (or slightly more, depending on OS thread scheduling), so processor is not busy for that time of blocking and code does not consume 100% of processor's power. Other processing can still be performed in-between blocking (such as: updating of UI, handling of events or doing interaction/communication stuff).</p>\n" }, { "answer_id": 13684964, "author": "Toni Petrina", "author_id": 671469, "author_profile": "https://Stackoverflow.com/users/671469", "pm_score": 6, "selected": false, "text": "<p>Since now you have async/await feature, the best way to sleep for 50ms is by using Task.Delay:</p>\n\n<pre><code>async void foo()\n{\n // something\n await Task.Delay(50);\n}\n</code></pre>\n\n<p>Or if you are targeting .NET 4 (with Async CTP 3 for VS2010 or Microsoft.Bcl.Async), you must use:</p>\n\n<pre><code>async void foo()\n{\n // something\n await TaskEx.Delay(50);\n}\n</code></pre>\n\n<p>This way you won't block UI thread.</p>\n" }, { "answer_id": 15650225, "author": "Colonel Panic", "author_id": 284795, "author_profile": "https://Stackoverflow.com/users/284795", "pm_score": 3, "selected": false, "text": "<p>For readability:</p>\n\n<pre><code>using System.Threading;\nThread.Sleep(TimeSpan.FromMilliseconds(50));\n</code></pre>\n" }, { "answer_id": 40311525, "author": "Akumaburn", "author_id": 4104551, "author_profile": "https://Stackoverflow.com/users/4104551", "pm_score": -1, "selected": false, "text": "<p>Best of both worlds:</p>\n\n<pre><code>using System.Runtime.InteropServices;\n\n [DllImport(\"winmm.dll\", EntryPoint = \"timeBeginPeriod\", SetLastError = true)]\n private static extern uint TimeBeginPeriod(uint uMilliseconds);\n\n [DllImport(\"winmm.dll\", EntryPoint = \"timeEndPeriod\", SetLastError = true)]\n private static extern uint TimeEndPeriod(uint uMilliseconds);\n /**\n * Extremely accurate sleep is needed here to maintain performance so system resolution time is increased\n */\n private void accurateSleep(int milliseconds)\n {\n //Increase timer resolution from 20 miliseconds to 1 milisecond\n TimeBeginPeriod(1);\n Stopwatch stopwatch = new Stopwatch();//Makes use of QueryPerformanceCounter WIN32 API\n stopwatch.Start();\n\n while (stopwatch.ElapsedMilliseconds &lt; milliseconds)\n {\n //So we don't burn cpu cycles\n if ((milliseconds - stopwatch.ElapsedMilliseconds) &gt; 20)\n {\n Thread.Sleep(5);\n }\n else\n {\n Thread.Sleep(1);\n }\n }\n\n stopwatch.Stop();\n //Set it back to normal.\n TimeEndPeriod(1);\n }\n</code></pre>\n" }, { "answer_id": 57364499, "author": "timmebee", "author_id": 11772622, "author_profile": "https://Stackoverflow.com/users/11772622", "pm_score": 2, "selected": false, "text": "<p>Starting with .NET Framework 4.5, you can use:</p>\n\n<pre><code>using System.Threading.Tasks;\n\nTask.Delay(50).Wait(); // wait 50ms\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91108", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1816/" ]
How do I get my C# program to sleep (pause execution) for 50 milliseconds?
``` System.Threading.Thread.Sleep(50); ``` Remember though, that doing this in the main GUI thread will block your GUI from updating (it will feel "sluggish") Just remove the `;` to make it work for VB.net as well.
91,110
<p>How to match a single quote in sed if the expression is enclosed in single quotes:</p> <pre><code>sed -e '...' </code></pre> <p>For example need to match this text:</p> <pre><code>'foo' </code></pre>
[ { "answer_id": 91176, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 7, "selected": true, "text": "\n\n<p>You can either use:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>\"texta'textb\" (APOSTROPHE inside QUOTATION MARKs)\n</code></pre>\n\n<p>or</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>'texta'\\''textb' (APOSTROPHE text APOSTROPHE, then REVERSE SOLIDUS, APOSTROPHE, then APOSTROPHE more text APOSTROPHE)\n</code></pre>\n\n<p>I used unicode character names. REVERSE SOLIDUS is more commonly known as backslash.</p>\n\n<p>In the latter case, you close your apostrophe, then shell-quote your apostrophe with a backslash, then open another apostrophe for the rest of the text.</p>\n" }, { "answer_id": 206963, "author": "TimB", "author_id": 4193, "author_profile": "https://Stackoverflow.com/users/4193", "pm_score": 6, "selected": false, "text": "<p>As noted in the comments to the question, it's not really about sed, but how to include a quote in a quoted string in a shell (e.g. bash).</p>\n\n<p>To clarify a previous answer, you need to escape the quote with a backslash, but you can't do that within a single-quoted expression. From the bash man page:</p>\n\n<blockquote>\n <p>Enclosing characters in single quotes\n preserves the literal value of each\n character within the quotes. A single\n quote may not occur between single\n quotes, even when preceded by a\n backslash.</p>\n</blockquote>\n\n<p>Therefore, you need to terminate the quoted expression, insert the escaped quote, and start a new quoted expression. The shell's quote removal does not add any extra spaces, so in effect you get string concatenation.</p>\n\n<p>So, to answer the original question of how to single quote the expression 'foo', you would do something like this:</p>\n\n<pre><code>sed -e '...'\\''foo'\\''...'\n</code></pre>\n\n<p>(where '...' is the rest of the sed expression).</p>\n\n<p>Overall, for the sake of readability, you'd be much better off changing the surrounding quotes to double quotes if at all possible:</p>\n\n<pre><code>sed -e \"...'foo'...\"\n</code></pre>\n\n<p>[As an example of the potential maintenance nightmare of the first (single quote) approach, note how StackOverflow's syntax highlighting colours the quotes, backslashes and other text -- it's definitely not correct.]</p>\n" }, { "answer_id": 63193353, "author": "dragon788", "author_id": 3794873, "author_profile": "https://Stackoverflow.com/users/3794873", "pm_score": -1, "selected": false, "text": "<p>You can also use <code>[']</code> to match a literal single quote without needing to do any shell quoting tricks.</p>\n<pre><code>myvar=&quot;stupid computers can't reason about life&quot;\necho &quot;$myvar&quot; | sed -e &quot;s/[']t//&quot;\n</code></pre>\nOutputs:\n<pre><code>stupid computers can reason about life\n</code></pre>\n" }, { "answer_id": 65133170, "author": "Rachel", "author_id": 7938150, "author_profile": "https://Stackoverflow.com/users/7938150", "pm_score": 1, "selected": false, "text": "<p>For sed, a very simple solution is to change the single quotation format to a double quote.</p>\n<p>For a given variable that contains single quotes</p>\n<pre><code>var=&quot;I'm a string with a single quote&quot;\n</code></pre>\n<p>If double quotes are used for sed, this will match the single quote.</p>\n<pre><code>echo $var | sed &quot;s/'//g&quot;\nIm a string with a single quote\n</code></pre>\n<p>Rather than single quotes, which will hang</p>\n<pre><code>echo $var | sed 's/'//g'\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91110", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1692070/" ]
How to match a single quote in sed if the expression is enclosed in single quotes: ``` sed -e '...' ``` For example need to match this text: ``` 'foo' ```
You can either use: ```none "texta'textb" (APOSTROPHE inside QUOTATION MARKs) ``` or ```none 'texta'\''textb' (APOSTROPHE text APOSTROPHE, then REVERSE SOLIDUS, APOSTROPHE, then APOSTROPHE more text APOSTROPHE) ``` I used unicode character names. REVERSE SOLIDUS is more commonly known as backslash. In the latter case, you close your apostrophe, then shell-quote your apostrophe with a backslash, then open another apostrophe for the rest of the text.
91,116
<p>I'm using this formula to calculate the distance between entries in my (My)SQL database which have latitude and longitude fields in decimal format:</p> <pre><code>6371 * ACOS(SIN(RADIANS( %lat1% )) * SIN(RADIANS( %lat2% )) + COS(RADIANS( %lat1% )) * COS(RADIANS( %lat2% )) * COS(RADIANS( %lon2% ) - RADIANS( %lon1% ))) </code></pre> <p>Substituting %lat1% and %lat2% appropriately it can be used in the WHERE clause to find entries within a certain radius of another entry, using it in the ORDER BY clause together with LIMIT will find the nearest x entries etc.</p> <p>I'm writing this mostly as a note for myself, but improvements are always welcome. :)</p> <p>Note: As mentioned by Valerion below, this calculates in kilometers. Substitute 6371 by an <a href="http://en.wikipedia.org/wiki/Earth_radius" rel="nofollow noreferrer">appropriate alternative number</a> to use meters, miles etc.</p>
[ { "answer_id": 91144, "author": "Adam Hopkinson", "author_id": 12280, "author_profile": "https://Stackoverflow.com/users/12280", "pm_score": 2, "selected": false, "text": "<p>Am i right in thinking this is the Haversine formula?</p>\n" }, { "answer_id": 91481, "author": "Valerion", "author_id": 16156, "author_profile": "https://Stackoverflow.com/users/16156", "pm_score": 1, "selected": false, "text": "<p>I use the exact same method on a vehicle-tracking application and have done for years. It works perfectly well. A quick check of some old code shows that I multiply the result by 6378137 which if memory serves converts to meters, but I haven't touched it for a very long time.</p>\n\n<p>I believe SQL 2008 has a new spatial datatype that I imagine allows these kinds of comparisons without knowing this formula, and also allows spatial indexes which might be interesting, but I've not looked into it.</p>\n" }, { "answer_id": 123413, "author": "David", "author_id": 21328, "author_profile": "https://Stackoverflow.com/users/21328", "pm_score": 3, "selected": false, "text": "<p>For databases (such as SQLite) that don't support trigonometric functions you can use the Pythagorean theorem.</p>\n<p>This is a faster method, even if your database does support trigonometric functions, with the following caveats:</p>\n<ul>\n<li>you need to store coords in x,y grid instead of (or as well as) lat,lng;</li>\n<li>the calculation assumes 'flat earth', but this is fine for relatively local searches.</li>\n</ul>\n<p>Here's an example from a Rails project I'm working on (the important bit is the SQL in the middle):</p>\n<pre><code>class User &lt; ActiveRecord::Base\n ...\n # has integer x &amp; y coordinates\n ...\n\n # Returns array of {:user =&gt; &lt;User&gt;, :distance =&gt; &lt;distance&gt;}, sorted by distance (in metres).\n # Distance is rounded to nearest integer.\n # point is a Geo::LatLng.\n # radius is in metres.\n # limit specifies the maximum number of records to return (default 100).\n def self.find_within_radius(point, radius, limit = 100)\n\n sql = &lt;&lt;-SQL\n select id, lat, lng, (#{point.x} - x) * (#{point.x} - x) + (#{point.y} - y) * (#{point.y} - y) d \n from users where #{(radius ** 2)} &gt;= d \n order by d limit #{limit}\n SQL\n \n users = User.find_by_sql(sql)\n users.each {|user| user.d = Math.sqrt(user.d.to_f).round}\n return users\n end\n</code></pre>\n" }, { "answer_id": 11621817, "author": "2pha", "author_id": 1547127, "author_profile": "https://Stackoverflow.com/users/1547127", "pm_score": 1, "selected": false, "text": "<p>I have been using this, forget where I got it though.</p>\n\n<pre><code>SELECT n, SQRT(POW((69.1 * (n.field_geofield_lat - :lat)) , 2 ) + POW((53 * (n.field_geofield_lon - :lon)), 2)) AS distance FROM field_revision_field_geofield n ORDER BY distance ASC\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91116", "https://Stackoverflow.com", "https://Stackoverflow.com/users/476/" ]
I'm using this formula to calculate the distance between entries in my (My)SQL database which have latitude and longitude fields in decimal format: ``` 6371 * ACOS(SIN(RADIANS( %lat1% )) * SIN(RADIANS( %lat2% )) + COS(RADIANS( %lat1% )) * COS(RADIANS( %lat2% )) * COS(RADIANS( %lon2% ) - RADIANS( %lon1% ))) ``` Substituting %lat1% and %lat2% appropriately it can be used in the WHERE clause to find entries within a certain radius of another entry, using it in the ORDER BY clause together with LIMIT will find the nearest x entries etc. I'm writing this mostly as a note for myself, but improvements are always welcome. :) Note: As mentioned by Valerion below, this calculates in kilometers. Substitute 6371 by an [appropriate alternative number](http://en.wikipedia.org/wiki/Earth_radius) to use meters, miles etc.
For databases (such as SQLite) that don't support trigonometric functions you can use the Pythagorean theorem. This is a faster method, even if your database does support trigonometric functions, with the following caveats: * you need to store coords in x,y grid instead of (or as well as) lat,lng; * the calculation assumes 'flat earth', but this is fine for relatively local searches. Here's an example from a Rails project I'm working on (the important bit is the SQL in the middle): ``` class User < ActiveRecord::Base ... # has integer x & y coordinates ... # Returns array of {:user => <User>, :distance => <distance>}, sorted by distance (in metres). # Distance is rounded to nearest integer. # point is a Geo::LatLng. # radius is in metres. # limit specifies the maximum number of records to return (default 100). def self.find_within_radius(point, radius, limit = 100) sql = <<-SQL select id, lat, lng, (#{point.x} - x) * (#{point.x} - x) + (#{point.y} - y) * (#{point.y} - y) d from users where #{(radius ** 2)} >= d order by d limit #{limit} SQL users = User.find_by_sql(sql) users.each {|user| user.d = Math.sqrt(user.d.to_f).round} return users end ```
91,124
<p>Suppose I have a string 'nvarchar(50)', which is for example the T-SQL string segment used in creating a table of that type. How do I best convert that to an enum representation of System.Data.DbType?</p> <p>Could it handle the many different possible ways of writing the type in T-SQL, such as:</p> <pre><code>[nvarchar](50) nvarchar 50 </code></pre> <p>@Jorge Table: Yes, that's handy, but isn't there a prebaked converter? Otherwise good answer.</p>
[ { "answer_id": 91139, "author": "m_pGladiator", "author_id": 446104, "author_profile": "https://Stackoverflow.com/users/446104", "pm_score": 2, "selected": false, "text": "<p>In addition to yours I will put:</p>\n\n<ul>\n<li>Unit Test Strategy</li>\n<li>Integration Test Strategy</li>\n<li>Defined Process</li>\n<li>Release (delivery) strategy (like milestones, working packages and so on)</li>\n<li>Source control branching strategy</li>\n</ul>\n" }, { "answer_id": 91154, "author": "Vertigo", "author_id": 5468, "author_profile": "https://Stackoverflow.com/users/5468", "pm_score": 2, "selected": false, "text": "<ul>\n<li>revision control system (eg. subversion, cvs, git)</li>\n</ul>\n" }, { "answer_id": 91155, "author": "JXG", "author_id": 15456, "author_profile": "https://Stackoverflow.com/users/15456", "pm_score": 3, "selected": false, "text": "<p>As a preliminary answer, check out the Joel test:\n<a href=\"http://www.joelonsoftware.com/articles/fog0000000043.html\" rel=\"noreferrer\">http://www.joelonsoftware.com/articles/fog0000000043.html</a></p>\n\n<p>Just an appetizer:</p>\n\n<blockquote>\n <ol>\n <li>Do you use source control?</li>\n <li>Can you make a build in one step?</li>\n <li>Do you make daily builds?</li>\n <li>Do you have a bug database?</li>\n <li>Do you fix bugs before writing new code?</li>\n <li>Do you have an up-to-date schedule?</li>\n <li>Do you have a spec?</li>\n <li>Do programmers have quiet working conditions?</li>\n <li>Do you use the best tools money can buy?</li>\n <li>Do you have testers?</li>\n <li>Do new candidates write code during their interview?</li>\n <li>Do you do hallway usability testing? </li>\n </ol>\n</blockquote>\n" }, { "answer_id": 91161, "author": "Jakub Kotrla", "author_id": 16943, "author_profile": "https://Stackoverflow.com/users/16943", "pm_score": 1, "selected": false, "text": "<ul>\n<li>What about documentation - how (comments in code, high-level specs), when, amount, who</li>\n<li>How you will test - unit/acceptance/user testing</li>\n<li>code versioning, some SVN/Git (or is it included in trac?)</li>\n<li>team roles and responsibilities - need to be done in ocntext of your project</li>\n</ul>\n" }, { "answer_id": 91165, "author": "Ilya Kochetov", "author_id": 15329, "author_profile": "https://Stackoverflow.com/users/15329", "pm_score": 0, "selected": false, "text": "<p>Knowledge management is crucial. As you already plan to use wiki (like Trac or <a href=\"http://www.redmine.org/\" rel=\"nofollow noreferrer\">Redmine</a>) you could use it for KM as well.</p>\n" }, { "answer_id": 91185, "author": "Ilya Kochetov", "author_id": 15329, "author_profile": "https://Stackoverflow.com/users/15329", "pm_score": 0, "selected": false, "text": "<p>Functional testing is a mandatory part of any project. Unit testing is great and it works well for Agile projects but the functional testing is still necessary. You need at least a basic Test Plan. If you plan to have multiple projects or sub-projects a Test Strategy document or Wiki page would be good.\nTest Cases, Acceptance Test Cases etc could be driven by your User Stories or their equivalents but they still have to exist in some form.</p>\n" }, { "answer_id": 93537, "author": "liangzan", "author_id": 11927, "author_profile": "https://Stackoverflow.com/users/11927", "pm_score": 0, "selected": false, "text": "<p>I would throw a file sharing server into the mix too. I thought version control was so basic, that I didn't even bother to put it there in the list. But its a good point version control.</p>\n" }, { "answer_id": 176503, "author": "Ben", "author_id": 9155, "author_profile": "https://Stackoverflow.com/users/9155", "pm_score": 0, "selected": false, "text": "<p>Configuration Management Plan. You need to have a documented approach to your development workstreams, how you will be merging between then, etc. </p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5790/" ]
Suppose I have a string 'nvarchar(50)', which is for example the T-SQL string segment used in creating a table of that type. How do I best convert that to an enum representation of System.Data.DbType? Could it handle the many different possible ways of writing the type in T-SQL, such as: ``` [nvarchar](50) nvarchar 50 ``` @Jorge Table: Yes, that's handy, but isn't there a prebaked converter? Otherwise good answer.
As a preliminary answer, check out the Joel test: <http://www.joelonsoftware.com/articles/fog0000000043.html> Just an appetizer: > > 1. Do you use source control? > 2. Can you make a build in one step? > 3. Do you make daily builds? > 4. Do you have a bug database? > 5. Do you fix bugs before writing new code? > 6. Do you have an up-to-date schedule? > 7. Do you have a spec? > 8. Do programmers have quiet working conditions? > 9. Do you use the best tools money can buy? > 10. Do you have testers? > 11. Do new candidates write code during their interview? > 12. Do you do hallway usability testing? > > >
91,127
<p>I want to verify a drag &amp; drop operation is allowed. A valid item can come from another one of our "controls", or internally from within the custom treeview. Currently I have this:</p> <pre><code>bool CanDrop(DragEventArgs e) { bool allow = false; Point point = tree.PointToClient(new Point(e.X, e.Y)); TreeNode target = tree.GetNodeAt(point); if (target != null) { if (CanWrite(target)) //user permissions { if (e.Data.GetData(typeof(DataInfoObject)) != null) //from internal application { DataInfoObject info = (DataInfoObject)e.Data.GetData(typeof(DataInfoObject)); DragDataCollection data = info.GetData(typeof(DragDataCollection)) as DragDataCollection; if (data != null) { allow = true; } } else if (tree.SelectedNode.Tag.GetType() != typeof(TreeRow)) //node belongs to this &amp; not a root node { if (TargetExistsInNode(tree.SelectedNode, target) == false) { if (e.Effect == DragDropEffects.Copy) { allow = true; } else if (e.Effect == DragDropEffects.Move) { allow = true; } } } } } return allow; } </code></pre> <p>I've moved all the checking code to this method to try to improve things, but to me this is still horrible!</p> <p>So much logic, and so much of it to do things that I'd expect the treeview would do itself (eg. "TargetExistsInNode" checks whether the dragged node is being dragged to one of its children).</p> <p>What is the best way to validate input to a control?</p>
[ { "answer_id": 91995, "author": "Hallgrim", "author_id": 15454, "author_profile": "https://Stackoverflow.com/users/15454", "pm_score": 3, "selected": true, "text": "<p>I use the TreeNode.Tag property to store small \"controller\" objects that makes up the logic. E.g.:</p>\n\n<pre><code>class TreeNodeController {\n Entity data; \n\n virtual bool IsReadOnly { get; }\n virtual bool CanDrop(TreeNodeController source, DragDropEffects effect);\n virtual bool CanDrop(DataInfoObject info, DragDropEffects effect);\n virtual bool CanRename();\n}\n\nclass ParentNodeController : TreeNodeController {\n override bool IsReadOnly { get { return data.IsReadOnly; } } \n override bool CanDrop(TreeNodeController source, DragDropEffect effect) {\n return !IsReadOnly &amp;&amp; !data.IsChildOf(source.data) &amp;&amp; effect == DragDropEffect.Move;\n }\n virtual bool CanDrop(DataInfoObject info, DragDropEffects effect) {\n return info.DragDataCollection != null;\n }\n override bool CanRename() { \n return !data.IsReadOnly &amp;&amp; data.HasName;\n }\n}\n\nclass LeafNodeController : TreeNodeController {\n override bool CanDrop(TreeNodeController source, DragDropEffect effect) {\n return false;\n }\n}\n</code></pre>\n\n<p>Then my CanDrop would be something like:</p>\n\n<pre><code>bool CanDrop(DragDropEventArgs args) {\n Point point = tree.PointToClient(new Point(e.X, e.Y));\n TreeNode target = tree.GetNodeAt(point);\n TreeNodeController targetController = target.Tag as TreeNodeController;\n\n DataInfoObject info = args.GetData(typeof(DataInfoObject)) as DataInfoObject;\n TreeNodeController sourceController = args.GetData(typeof(TreeNodeController)) as TreeNodeController;\n\n if (info != null) return targetController.CanDrop(info, e.Effect);\n if (sourceController != null) return targetController.CanDrop(sourceController, e.Effect);\n return false;\n}\n</code></pre>\n\n<p>Now for each class of objects that I add to the tree I can specialize the behaviour by choosing which TreeNodeController to put in the Tag object.</p>\n" }, { "answer_id": 126146, "author": "Nigel Hawkins", "author_id": 1389021, "author_profile": "https://Stackoverflow.com/users/1389021", "pm_score": 1, "selected": false, "text": "<p>Not strictly answering your question, but I've spotted a bug in your code.\n<code>DragDropEffects</code> has the flags attribute set so you could get <code>e.Effect</code> to be a bitwise combination of copy and move. In which case your code would incorrectly return false.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91127", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15608/" ]
I want to verify a drag & drop operation is allowed. A valid item can come from another one of our "controls", or internally from within the custom treeview. Currently I have this: ``` bool CanDrop(DragEventArgs e) { bool allow = false; Point point = tree.PointToClient(new Point(e.X, e.Y)); TreeNode target = tree.GetNodeAt(point); if (target != null) { if (CanWrite(target)) //user permissions { if (e.Data.GetData(typeof(DataInfoObject)) != null) //from internal application { DataInfoObject info = (DataInfoObject)e.Data.GetData(typeof(DataInfoObject)); DragDataCollection data = info.GetData(typeof(DragDataCollection)) as DragDataCollection; if (data != null) { allow = true; } } else if (tree.SelectedNode.Tag.GetType() != typeof(TreeRow)) //node belongs to this & not a root node { if (TargetExistsInNode(tree.SelectedNode, target) == false) { if (e.Effect == DragDropEffects.Copy) { allow = true; } else if (e.Effect == DragDropEffects.Move) { allow = true; } } } } } return allow; } ``` I've moved all the checking code to this method to try to improve things, but to me this is still horrible! So much logic, and so much of it to do things that I'd expect the treeview would do itself (eg. "TargetExistsInNode" checks whether the dragged node is being dragged to one of its children). What is the best way to validate input to a control?
I use the TreeNode.Tag property to store small "controller" objects that makes up the logic. E.g.: ``` class TreeNodeController { Entity data; virtual bool IsReadOnly { get; } virtual bool CanDrop(TreeNodeController source, DragDropEffects effect); virtual bool CanDrop(DataInfoObject info, DragDropEffects effect); virtual bool CanRename(); } class ParentNodeController : TreeNodeController { override bool IsReadOnly { get { return data.IsReadOnly; } } override bool CanDrop(TreeNodeController source, DragDropEffect effect) { return !IsReadOnly && !data.IsChildOf(source.data) && effect == DragDropEffect.Move; } virtual bool CanDrop(DataInfoObject info, DragDropEffects effect) { return info.DragDataCollection != null; } override bool CanRename() { return !data.IsReadOnly && data.HasName; } } class LeafNodeController : TreeNodeController { override bool CanDrop(TreeNodeController source, DragDropEffect effect) { return false; } } ``` Then my CanDrop would be something like: ``` bool CanDrop(DragDropEventArgs args) { Point point = tree.PointToClient(new Point(e.X, e.Y)); TreeNode target = tree.GetNodeAt(point); TreeNodeController targetController = target.Tag as TreeNodeController; DataInfoObject info = args.GetData(typeof(DataInfoObject)) as DataInfoObject; TreeNodeController sourceController = args.GetData(typeof(TreeNodeController)) as TreeNodeController; if (info != null) return targetController.CanDrop(info, e.Effect); if (sourceController != null) return targetController.CanDrop(sourceController, e.Effect); return false; } ``` Now for each class of objects that I add to the tree I can specialize the behaviour by choosing which TreeNodeController to put in the Tag object.
91,160
<p>How do I best convert a System.Data.DbType enumeration value to the corresponding (or at least one of the possible corresponding) System.Type values?</p> <p>For example:</p> <pre><code>DbType.StringFixedLength -&gt; System.String DbType.String -&gt; System.String DbType.Int32 -&gt; System.Int32 </code></pre> <p>I've only seen very "dirty" solutions but nothing really clean.</p> <p>(yes, it's a follow up to a different question of mine, but it made more sense as two seperate questions)</p>
[ { "answer_id": 91177, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 4, "selected": true, "text": "<p>AFAIK there is no built-in converter in .NET for converting a SqlDbType to a System.Type. But knowing the mapping you can easily roll your own converter ranging from a simple dictionary to more advanced (XML based for extensability) solutions.</p>\n\n<p>The mapping can be found here:\n<a href=\"http://www.carlprothman.net/Default.aspx?tabid=97\" rel=\"nofollow noreferrer\">http://www.carlprothman.net/Default.aspx?tabid=97</a></p>\n" }, { "answer_id": 18621961, "author": "Jon Banta", "author_id": 2748177, "author_profile": "https://Stackoverflow.com/users/2748177", "pm_score": 2, "selected": false, "text": "<p>System.Data.SqlClient objects use the MetaType component to translate DbType and SqlDbType to .NET CLR Types. Using reflection, you could leverage this ability if needed:</p>\n\n<pre><code>var dbType = DbType.Currency;\n\nType metaClrType = Type.GetType(\n \"System.Data.SqlClient.MetaType, System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\",\n true,\n true\n );\n\nobject metaType = metaClrType.InvokeMember(\n \"GetMetaTypeFromDbType\",\n BindingFlags.InvokeMethod | BindingFlags.Static | BindingFlags.NonPublic,\n null,\n null,\n new object[] { dbType }\n);\n\nvar classType = (Type)metaClrType.InvokeMember(\n \"ClassType\",\n BindingFlags.GetField | BindingFlags.Instance | BindingFlags.NonPublic,\n null,\n metaType,\n null\n);\n\nstring cSharpDataType = classType.FullName;\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91160", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5790/" ]
How do I best convert a System.Data.DbType enumeration value to the corresponding (or at least one of the possible corresponding) System.Type values? For example: ``` DbType.StringFixedLength -> System.String DbType.String -> System.String DbType.Int32 -> System.Int32 ``` I've only seen very "dirty" solutions but nothing really clean. (yes, it's a follow up to a different question of mine, but it made more sense as two seperate questions)
AFAIK there is no built-in converter in .NET for converting a SqlDbType to a System.Type. But knowing the mapping you can easily roll your own converter ranging from a simple dictionary to more advanced (XML based for extensability) solutions. The mapping can be found here: <http://www.carlprothman.net/Default.aspx?tabid=97>
91,169
<p>So I log into a Solaris box, try to start Apache, and find that there is already a process listening on port 80, and it's not Apache. Our boxes don't have lsof installed, so I can't query with that. I guess I could do:</p> <pre><code>pfiles `ls /proc` | less </code></pre> <p>and look for "port: 80", but if anyone has a better solution, I'm all ears! Even better if I can look for the listening process without being root. I'm open to both shell and C solutions; I wouldn't mind having a little custom executable to carry with me for the next time this comes up.</p> <p>Updated: I'm talking about generic installs of solaris for which I am not the administrator (although I do have superuser access), so installing things from the freeware disk isn't an option. Obviously neither are using Linux-specific extensions to fuser, netstat, or other tools. So far running pfiles on <strong>all</strong> processes seems to be the best solution, unfortunately. If that remains the case, I'll probably post an answer with some slightly more efficient code that the clip above.</p>
[ { "answer_id": 91188, "author": "Christoffer", "author_id": 15514, "author_profile": "https://Stackoverflow.com/users/15514", "pm_score": -1, "selected": false, "text": "<p>If you have access to <code>netstat</code>, that can do precisely that. </p>\n" }, { "answer_id": 91194, "author": "paan", "author_id": 2976, "author_profile": "https://Stackoverflow.com/users/2976", "pm_score": 0, "selected": false, "text": "<p>Most probly sun's administrative server..\nIt's usually bundled along with sun's directory and a few other webmin-ish stuff that is in the default installation</p>\n" }, { "answer_id": 118215, "author": "wnoise", "author_id": 15464, "author_profile": "https://Stackoverflow.com/users/15464", "pm_score": 1, "selected": false, "text": "<p>You might not want to, but your best bet is to grab the sunfreeware CD and install lsof.</p>\n\n<p>Other than that, yes you can grovel around in /proc with a shell script.</p>\n" }, { "answer_id": 182852, "author": "Greg Laws", "author_id": 25858, "author_profile": "https://Stackoverflow.com/users/25858", "pm_score": 0, "selected": false, "text": "<p>This is sort of an indirect approach, but you could see if a website loads on your web browser of choice from whatever is running on port 80. Or you could telnet to port 80 and see if you get a response that gives you a clue as to what is running on that port and you can go shut it down. Since port 80 is the default port for http traffic chances are there is some sort of http server running there by default, but there's no guarantee.</p>\n" }, { "answer_id": 825155, "author": "mavroprovato", "author_id": 89435, "author_profile": "https://Stackoverflow.com/users/89435", "pm_score": 5, "selected": false, "text": "<p>I found this script somewhere. I don't remember where, but it works for me:</p>\n\n<pre><code>#!/bin/ksh\n\nline='---------------------------------------------'\npids=$(/usr/bin/ps -ef | sed 1d | awk '{print $2}')\n\nif [ $# -eq 0 ]; then\n read ans?\"Enter port you would like to know pid for: \"\nelse\n ans=$1\nfi\n\nfor f in $pids\ndo\n /usr/proc/bin/pfiles $f 2&gt;/dev/null | /usr/xpg4/bin/grep -q \"port: $ans\"\n if [ $? -eq 0 ]; then\n echo $line\n echo \"Port: $ans is being used by PID:\\c\"\n /usr/bin/ps -ef -o pid -o args | egrep -v \"grep|pfiles\" | grep $f\n fi\ndone\nexit 0\n</code></pre>\n\n<p>Edit: Here is the original source:\n<a href=\"http://blogs.oracle.com/JoachimAndres/entry/solaris_which_process_is_bound1\" rel=\"noreferrer\">[Solaris] Which process is bound to a given port ?</a></p>\n" }, { "answer_id": 9703830, "author": "ceving", "author_id": 402322, "author_profile": "https://Stackoverflow.com/users/402322", "pm_score": 2, "selected": false, "text": "<p>Mavroprovato's answer reports more than only the listening ports. Listening ports are sockets without a peer. The following Perl program reports only the listening ports. It works for me on SunOS 5.10.</p>\n\n<pre><code>#! /usr/bin/env perl\n##\n## Search the processes which are listening on the given port.\n##\n## For SunOS 5.10.\n##\n\nuse strict;\nuse warnings;\n\ndie \"Port missing\" unless $#ARGV &gt;= 0;\nmy $port = int($ARGV[0]);\ndie \"Invalid port\" unless $port &gt; 0;\n\nmy @pids;\nmap { push @pids, $_ if $_ &gt; 0; } map { int($_) } `ls /proc`;\n\nforeach my $pid (@pids) {\n open (PF, \"pfiles $pid 2&gt;/dev/null |\") \n || warn \"Can not read pfiles $pid\";\n $_ = &lt;PF&gt;;\n my $fd;\n my $type;\n my $sockname;\n my $peername;\n my $report = sub {\n if (defined $fd) {\n if (defined $sockname &amp;&amp; ! defined $peername) {\n print \"$pid $type $sockname\\n\"; } } };\n while (&lt;PF&gt;) {\n if (/^\\s*(\\d+):.*$/) {\n &amp;$report();\n $fd = int ($1);\n undef $type;\n undef $sockname;\n undef $peername; }\n elsif (/(SOCK_DGRAM|SOCK_STREAM)/) { $type = $1; }\n elsif (/sockname: AF_INET[6]? (.*) port: $port/) {\n $sockname = $1; }\n elsif (/peername: AF_INET/) { $peername = 1; } }\n &amp;$report();\n close (PF); }\n</code></pre>\n" }, { "answer_id": 16201498, "author": "Mauricio Morales", "author_id": 1830021, "author_profile": "https://Stackoverflow.com/users/1830021", "pm_score": 3, "selected": false, "text": "<p>Here's a one-liner:</p></p>\n\n<pre><code>ps -ef| awk '{print $2}'| xargs -I '{}' sh -c 'echo examining process {}; pfiles {}| grep 80'\n</code></pre>\n\n<p>'echo examining process PID' will be printed before each search, so once you see an output referencing port 80, you'll know which process is holding the handle.</p>\nAlternatively use:</p></p>\n\n<pre><code>ps -ef| grep $USER|awk '{print $2}'| xargs -I '{}' sh -c 'echo examining process {}; pfiles {}| grep 80'\n</code></pre>\n\n<p>Since 'pfiles' might not like that you're trying to access other user's processes, unless you're root of course.</p>\n" }, { "answer_id": 18597375, "author": "RomAndNonES", "author_id": 2743777, "author_profile": "https://Stackoverflow.com/users/2743777", "pm_score": 1, "selected": false, "text": "<p>I think the first answer is the best\nI wrote my own shell script developing this idea :</p>\n\n<pre><code>#!/bin/sh\nif [ $# -ne 1 ]\nthen\n echo \"Sintaxis:\\n\\t\"\n echo \" $0 {port to search in process }\"\n exit\nelse\n MYPORT=$1\n for i in `ls /proc`\n do\n\n pfiles $i | grep port | grep \"port: $MYPORT\" &gt; /dev/null\n if [ $? -eq 0 ]\n then\n echo \" Port $MYPORT founded in $i proccess !!!\\n\\n\"\n echo \"Details\\n\\t\"\n pfiles $i | grep port | grep \"port: $MYPORT\"\n echo \"\\n\\t\"\n echo \"Process detail: \\n\\t\"\n ps -ef | grep $i | grep -v grep\n fi\n done\nfi\n</code></pre>\n" }, { "answer_id": 19218132, "author": "Malcolm Boekhoff", "author_id": 1388639, "author_profile": "https://Stackoverflow.com/users/1388639", "pm_score": 2, "selected": false, "text": "<pre><code>#!/usr/bin/bash\n# This is a little script based on the \"pfiles\" solution that prints the PID and PORT.\n\npfiles `ls /proc` 2&gt;/dev/null | awk \"/^[^ \\\\t]/{smatch=\\$0;next}/port:[ \\\\t]*${1}/{print smatch, \\$0}{next}\"\n</code></pre>\n" }, { "answer_id": 24312175, "author": "JohnGH", "author_id": 224625, "author_profile": "https://Stackoverflow.com/users/224625", "pm_score": 2, "selected": false, "text": "<p>netstat on Solaris will not tell you this, nor will older versions of lsof, but if you download and build/install a newer version of lsof, this can tell you that.</p>\n\n<pre><code>$ lsof -v\nlsof version information:\n revision: 4.85\n latest revision: ftp://lsof.itap.purdue.edu/pub/tools/unix/lsof/\n latest FAQ: ftp://lsof.itap.purdue.edu/pub/tools/unix/lsof/FAQ\n latest man page: ftp://lsof.itap.purdue.edu/pub/tools/unix/lsof/lsof_man\n configuration info: 64 bit kernel\n constructed: Fri Mar 7 10:32:54 GMT 2014\n constructed by and on: user@hostname\n compiler: gcc\n compiler version: 3.4.3 (csl-sol210-3_4-branch+sol_rpath)\n 8&lt;- - - - ***SNIP*** - - -\n</code></pre>\n\n<p>With this you can use the -i option:</p>\n\n<pre><code>$ lsof -i:22\nCOMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME\nsshd 521 root 3u IPv6 0xffffffff89c67580 0t0 TCP *:ssh (LISTEN)\nsshd 5090 root 3u IPv6 0xffffffffa8668580 0t322598 TCP host.domain.com:ssh-&gt;21.43.65.87:52364 (ESTABLISHED)\nsshd 5091 johngh 4u IPv6 0xffffffffa8668580 0t322598 TCP host.domain.com:ssh-&gt;21.43.65.87:52364 (ESTABLISHED)\n</code></pre>\n\n<p>Which shows you exactly what you're asking for.</p>\n\n<p>I had a problem yesterday with a crashed Jetty (Java) process, which only left 2 files in its /proc/[PID] directory (psinfo &amp; usage).</p>\n\n<p>pfiles failed to find the process (because the date it needed was not there)</p>\n\n<p>lsof found it for me.</p>\n" }, { "answer_id": 24488977, "author": "peterh", "author_id": 1504556, "author_profile": "https://Stackoverflow.com/users/1504556", "pm_score": 2, "selected": false, "text": "<p>From Solaris 11.2 onwards you can indeed do this with the <code>netstat</code> command. Have a look <a href=\"https://blogs.oracle.com/casper/entry/solaris_11_2_user_pid\" rel=\"nofollow\">here</a>. The <code>-u</code> switch is what you are looking for. </p>\n\n<p>If you are on a lower version of Solaris then - as others have pointed out - the Solaris way of doing this is some kind of script wrapper around <code>pfiles</code> command. Beware though that <code>pfiles</code> command halts the process for a split second in order to inspect it. For 99.9% of processes this is unimportant. Unfortunately we have a process that will give a core dump if it is hit with a <code>pfiles</code> command so we are a bit cautious about using the command. Your situation may be totally different if you are in the 99.9%, meaning you can safely use the <code>pfiles</code> command.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91169", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
So I log into a Solaris box, try to start Apache, and find that there is already a process listening on port 80, and it's not Apache. Our boxes don't have lsof installed, so I can't query with that. I guess I could do: ``` pfiles `ls /proc` | less ``` and look for "port: 80", but if anyone has a better solution, I'm all ears! Even better if I can look for the listening process without being root. I'm open to both shell and C solutions; I wouldn't mind having a little custom executable to carry with me for the next time this comes up. Updated: I'm talking about generic installs of solaris for which I am not the administrator (although I do have superuser access), so installing things from the freeware disk isn't an option. Obviously neither are using Linux-specific extensions to fuser, netstat, or other tools. So far running pfiles on **all** processes seems to be the best solution, unfortunately. If that remains the case, I'll probably post an answer with some slightly more efficient code that the clip above.
I found this script somewhere. I don't remember where, but it works for me: ``` #!/bin/ksh line='---------------------------------------------' pids=$(/usr/bin/ps -ef | sed 1d | awk '{print $2}') if [ $# -eq 0 ]; then read ans?"Enter port you would like to know pid for: " else ans=$1 fi for f in $pids do /usr/proc/bin/pfiles $f 2>/dev/null | /usr/xpg4/bin/grep -q "port: $ans" if [ $? -eq 0 ]; then echo $line echo "Port: $ans is being used by PID:\c" /usr/bin/ps -ef -o pid -o args | egrep -v "grep|pfiles" | grep $f fi done exit 0 ``` Edit: Here is the original source: [[Solaris] Which process is bound to a given port ?](http://blogs.oracle.com/JoachimAndres/entry/solaris_which_process_is_bound1)
91,223
<p>I'm using Microsoft.XMLHTTP to get some information from another server from an old ASP/VBScript site. But that other server is restarted fairly often, so I want to check that it's up and running before trying to pull information from it (or avoid my page from giving an HTTP 500 by detecting the problem some other way).</p> <p>How can I do this with ASP?</p>
[ { "answer_id": 91334, "author": "Jordi", "author_id": 1893, "author_profile": "https://Stackoverflow.com/users/1893", "pm_score": 2, "selected": false, "text": "<p>You could try making a ping to the server and check the response.\nTake a look at this <a href=\"http://classicasp.aspfaq.com/general/how-do-i-execute-a-ping-command-from-asp-and-retrieve-the-results.html\" rel=\"nofollow noreferrer\">article</a>.</p>\n" }, { "answer_id": 91488, "author": "bastos.sergio", "author_id": 12772, "author_profile": "https://Stackoverflow.com/users/12772", "pm_score": 2, "selected": true, "text": "<p>All you need to do is have the code continue on error, then post to the other server and read the status from the post. Something like this:</p>\n\n<pre><code>PostURL = homelink &amp; \"CustID.aspx?SearchFlag=PO\"\nset xmlhttp = CreateObject(\"MSXML2.ServerXMLHTTP.3.0\")\n</code></pre>\n\n<p><strong>on error resume next</strong></p>\n\n<pre><code>xmlhttp.open \"POST\", PostURL, false\nxmlhttp.send \"\"\n</code></pre>\n\n<p><strong>status = xmlhttp.status</strong></p>\n\n<pre><code>if err.number &lt;&gt; 0 or status &lt;&gt; 200 then\n if status = 404 then\n Response.Write \"ERROR: Page does not exist (404).&lt;BR&gt;&lt;BR&gt;\"\n elseif status &gt;= 401 and status &lt; 402 then\n Response.Write \"ERROR: Access denied (401).&lt;BR&gt;&lt;BR&gt;\"\n elseif status &gt;= 500 and status &lt;= 600 then\n Response.Write \"ERROR: 500 Internal Server Error on remote site.&lt;BR&gt;&lt;BR&gt;\"\n else\n Response.write \"ERROR: Server is down or does not exist.&lt;BR&gt;&lt;BR&gt;\"\n end if\nelse\n 'Response.Write \"Server is up and URL is available.&lt;BR&gt;&lt;BR&gt;\"\n getcustomXML = xmlhttp.responseText\nend if\nset xmlhttp = nothing\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1367/" ]
I'm using Microsoft.XMLHTTP to get some information from another server from an old ASP/VBScript site. But that other server is restarted fairly often, so I want to check that it's up and running before trying to pull information from it (or avoid my page from giving an HTTP 500 by detecting the problem some other way). How can I do this with ASP?
All you need to do is have the code continue on error, then post to the other server and read the status from the post. Something like this: ``` PostURL = homelink & "CustID.aspx?SearchFlag=PO" set xmlhttp = CreateObject("MSXML2.ServerXMLHTTP.3.0") ``` **on error resume next** ``` xmlhttp.open "POST", PostURL, false xmlhttp.send "" ``` **status = xmlhttp.status** ``` if err.number <> 0 or status <> 200 then if status = 404 then Response.Write "ERROR: Page does not exist (404).<BR><BR>" elseif status >= 401 and status < 402 then Response.Write "ERROR: Access denied (401).<BR><BR>" elseif status >= 500 and status <= 600 then Response.Write "ERROR: 500 Internal Server Error on remote site.<BR><BR>" else Response.write "ERROR: Server is down or does not exist.<BR><BR>" end if else 'Response.Write "Server is up and URL is available.<BR><BR>" getcustomXML = xmlhttp.responseText end if set xmlhttp = nothing ```
91,263
<p>Part of the install for an app I am responsible for, compiles some C code libraries. This is done in a console using GNU Make.</p> <p>So, as part of the install, a console window pops open, you see the make file output wiz by as it compiles and links, when finished the console window closes and the installer continues.</p> <p>All good, unless there is a compilation error. Then the make file bugs out and the console window closes before you have a chance to figure out what is happening.</p> <p>So, what I'd like to happen is have the console window pause with a 'press a key to continue' type functionality, if there is an error from the makefile so that the console stays open. Otherwise, just exit as normal and close the console.</p> <p>I can't work out how to do this in a GNU Makefile or from a batch file that could run the Make. </p>
[ { "answer_id": 91273, "author": "Amir Arad", "author_id": 11813, "author_profile": "https://Stackoverflow.com/users/11813", "pm_score": 4, "selected": true, "text": "<p>this should do the trick:</p>\n\n<p></p>\n\n<pre><code>if not ERRORLEVEL 0 pause\n</code></pre>\n\n<p>type <code>help if</code> in DOS for more info on errorlevel usage.</p>\n" }, { "answer_id": 91346, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Have you tried the 'pause' command?</p>\n\n<pre><code>@echo off\necho hello world\npause\n</code></pre>\n\n<ul>\n<li>more info on 'pause' : <a href=\"http://technet.microsoft.com/en-us/library/bb490965.aspx\" rel=\"nofollow noreferrer\">http://technet.microsoft.com/en-us/library/bb490965.aspx</a></li>\n<li>DOS Command Line reference A-Z : <a href=\"http://technet.microsoft.com/en-us/library/bb490890.aspx\" rel=\"nofollow noreferrer\">http://technet.microsoft.com/en-us/library/bb490890.aspx</a></li>\n</ul>\n" }, { "answer_id": 7850322, "author": "Benja", "author_id": 178576, "author_profile": "https://Stackoverflow.com/users/178576", "pm_score": 2, "selected": false, "text": "<p>This is what you're looking for:</p>\n\n<pre><code>if ERRORLEVEL 1 pause\n</code></pre>\n\n<hr>\n\n<p>If you type</p>\n\n<pre><code>HELP IF\n</code></pre>\n\n<p>you get this info: ERRORLEVEL number | \nSpecifies a true condition if the last program run returned an exit code <strong>equal to or greater than</strong> the number specified.</p>\n" }, { "answer_id": 41080486, "author": "bryc", "author_id": 815680, "author_profile": "https://Stackoverflow.com/users/815680", "pm_score": 1, "selected": false, "text": "<p>Using this simple C program to manipulate the exit code:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\nmain(int argc, char *argv[]) {\n if (argc == 2) {\n // return integer of argument 1\n return strtol(argv[1], NULL, 10);\n }\n else {\n return 0;\n }\n}\n</code></pre>\n\n<p>We can test the exit code in a <strong>batch file</strong> like so:</p>\n\n<pre><code>test.exe 0\nIF ERRORLEVEL 0 PAUSE\n</code></pre>\n\n<p><strong>Condition</strong>: <code>0 =&gt; 0 == TRUE</code></p>\n\n<p>When <code>ERRORLEVEL = 0</code>, the pause will occur because the logic is <code>&gt;=</code> or <strong>greater-than-or-equal</strong>. This is important, as it's not immediately clear that the condition is not a <code>==</code> comparison.</p>\n\n<p>Notice that subsituting for <code>1 =&gt; 0</code> will also be true, and thus the pause will occur as well. This is true for any positive number.</p>\n\n<p>We can trigger the opposite effect only by going below <code>0</code>:</p>\n\n<pre><code>test.exe -1\nIF ERRORLEVEL 0 PAUSE\n</code></pre>\n\n<p><strong>Condition</strong>: <code>-1 =&gt; 0 == FALSE</code></p>\n\n<p>Since an <code>ERRORLEVEL</code> of <code>1</code> typically means there is an error, and <code>0</code> no error, we can just increase the minimum in the comparison condition to get what we want like so:</p>\n\n<pre><code>test.exe 0\nIF ERRORLEVEL 1 PAUSE\n</code></pre>\n\n<p><strong>Condition</strong>: <code>-1 =&gt; 1 == FALSE</code></p>\n\n<p><strong>Condition</strong>: <code>0 =&gt; 1 == FALSE</code></p>\n\n<p><strong>Condition</strong>: <code>1 =&gt; 1 == TRUE</code></p>\n\n<p>In this example. the script will pause when <code>ERRORLEVEL</code> is <code>1</code> or higher</p>\n\n<p>Notice that this allows <code>-1</code> exit codes the same as <code>0</code>. What if one only wants <code>0</code> to not pause? We can use a separate syntax:</p>\n\n<pre><code>test.exe 0\nIF NOT %ERRORLEVEL% EQU 0 PAUSE\n</code></pre>\n\n<p><strong>Condition</strong>: <code>-1 != 0 == TRUE</code></p>\n\n<p><strong>Condition</strong>: <code>0 != 0 == FALSE</code></p>\n\n<p><strong>Condition</strong>: <code>1 != 0 == TRUE</code></p>\n\n<p>In this example, the script pauses if <code>%ERRORLEVEL%</code> is not <code>0</code> We can do this by using the EQU operator to first check if <code>%ERRORLEVEL% EQU 0</code>, then the NOT operator to get the opposite effect, equivalent to the <code>!=</code> operator. However, I believe this only works on NT machines, not plain DOS.</p>\n\n<p>References:</p>\n\n<p><a href=\"http://chrisoldwood.blogspot.ca/2013/11/if-errorlevel-1-vs-if-errorlevel-neq-0.html\" rel=\"nofollow noreferrer\">http://chrisoldwood.blogspot.ca/2013/11/if-errorlevel-1-vs-if-errorlevel-neq-0.html</a>\n<a href=\"http://ss64.com/nt/errorlevel.html\" rel=\"nofollow noreferrer\">http://ss64.com/nt/errorlevel.html</a></p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6063/" ]
Part of the install for an app I am responsible for, compiles some C code libraries. This is done in a console using GNU Make. So, as part of the install, a console window pops open, you see the make file output wiz by as it compiles and links, when finished the console window closes and the installer continues. All good, unless there is a compilation error. Then the make file bugs out and the console window closes before you have a chance to figure out what is happening. So, what I'd like to happen is have the console window pause with a 'press a key to continue' type functionality, if there is an error from the makefile so that the console stays open. Otherwise, just exit as normal and close the console. I can't work out how to do this in a GNU Makefile or from a batch file that could run the Make.
this should do the trick: ``` if not ERRORLEVEL 0 pause ``` type `help if` in DOS for more info on errorlevel usage.
91,275
<p>I'm writing a small tool in C# which will need to send and receive data to/from a website using POST and json formatting. I've never done anything like this before in C# (or any language really) so I'm struggling to find some useful information to get me started.</p> <p>I've found some information on the WebRequest class in C# (specifically from <a href="http://msdn.microsoft.com/en-us/library/debx8sh9.aspx" rel="noreferrer">here</a>) but before I start diving into it, I wondered if this was the right tool for the job.</p> <p>I've found plenty of tools to convert data into the json format but not much else, so any information would be really helpful here in case I end up down a dead end.</p>
[ { "answer_id": 91296, "author": "Seb Rose", "author_id": 12405, "author_profile": "https://Stackoverflow.com/users/12405", "pm_score": 0, "selected": false, "text": "<p>I have used WebRequest for interacting with websites. It is the right 'tool'</p>\n\n<p>I can't comment on the JSON aspect of your question.</p>\n" }, { "answer_id": 91300, "author": "redsquare", "author_id": 6440, "author_profile": "https://Stackoverflow.com/users/6440", "pm_score": -1, "selected": false, "text": "<p>in 3.5 there is a built-in jsonserializer. The webrequest is the right class your looking for.</p>\n<p>A few examples:</p>\n<ul>\n<li><a href=\"https://web.archive.org/web/20200925065333/http://geekswithblogs.net/JuanDoNeblo/archive/2007/10/24/json_in_aspnetajax_part2.aspx\" rel=\"nofollow noreferrer\">Link</a></li>\n<li><a href=\"http://dev.aol.com/blog/markdeveloper/ShareFileWithNETFramework\" rel=\"nofollow noreferrer\">http://dev.aol.com/blog/markdeveloper/ShareFileWithNETFramework</a></li>\n<li><a href=\"https://web.archive.org/web/20200919002259/http://geekswithblogs.net/JuanDoNeblo/archive/2007/10.aspx\" rel=\"nofollow noreferrer\">Link</a></li>\n</ul>\n" }, { "answer_id": 91317, "author": "Eric Schoonover", "author_id": 3957, "author_profile": "https://Stackoverflow.com/users/3957", "pm_score": 4, "selected": false, "text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/system.net.webclient(VS.80).aspx\" rel=\"noreferrer\">WebClient</a> is sometimes easier to use than <a href=\"http://msdn.microsoft.com/en-us/library/system.net.webrequest.aspx\" rel=\"noreferrer\">WebRequest</a>. You may want to take a look at it.</p>\n\n<p>For JSON deserialization you are going to want to look at the <a href=\"http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer_members.aspx\" rel=\"noreferrer\">JavaScriptSerializer</a> class.</p>\n\n<p>WebClient example:</p>\n\n<pre><code>using (WebClient client = new WebClient ())\n{\n //manipulate request headers (optional)\n client.Headers.Add (HttpRequestHeader.UserAgent, \"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)\");\n\n //execute request and read response as string to console\n using (StreamReader reader = new StreamReader(client.OpenRead(targetUri)))\n {\n string s = reader.ReadToEnd ();\n Console.WriteLine (s);\n }\n}\n</code></pre>\n\n<p><strong>Marked as wiki in case someone wants to update the code</strong></p>\n" }, { "answer_id": 91322, "author": "mdb", "author_id": 8562, "author_profile": "https://Stackoverflow.com/users/8562", "pm_score": 1, "selected": false, "text": "<p>When it comes to POSTing data to a web site, <a href=\"http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx\" rel=\"nofollow noreferrer\">System.Net.HttpWebRequest</a> (the HTTP-specific implementation of WebRequest) is a perfectly decent solution. It supports SSL, async requests and a bunch of other goodies, and is well-documented on MSDN.</p>\n\n<p>The payload can be anything: data in JSON format or whatever -- as long as you set the ContentType property to something the server expects and understands (most likely application/json, text/json or text/x-json), all will be fine.</p>\n\n<p>One potential issue when using HttpWebRequest from a system service: since it uses the IE proxy and credential information, default behavior may be a bit strange when running as the LOCALSYSTEM user (or basically any account that doesn't log on interactively on a regular basis). Setting the Proxy and Authentication properties to <code>Nothing</code> (or, as you C# folks prefer to call it, <code>null</code>, I guess) should avoid that.</p>\n" }, { "answer_id": 91326, "author": "Wolfwyrd", "author_id": 15570, "author_profile": "https://Stackoverflow.com/users/15570", "pm_score": 6, "selected": true, "text": "<p>WebRequest and more specifically the HttpWebRequest class is a good starting point for what you want to achieve. To create the request you will use the WebRequest.Create and cast the created request to an HttpWebRequest to actually use it. You will then create your post data and send it to the stream like:</p>\n\n<pre><code>HttpWebRequest req = (HttpWebRequest)\nWebRequest.Create(\"http://mysite.com/index.php\");\nreq.Method = \"POST\";\nreq.ContentType = \"application/x-www-form-urlencoded\";\nstring postData = \"var=value1&amp;var2=value2\";\nreq.ContentLength = postData.Length;\n\nStreamWriter stOut = new\nStreamWriter(req.GetRequestStream(),\nSystem.Text.Encoding.ASCII);\nstOut.Write(postData);\nstOut.Close();\n</code></pre>\n\n<p>Similarly you can read the response back by using the GetResponse method which will allow you to read the resultant response stream and do whatever else you need to do. You can find more info on the class at:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx</a></p>\n" }, { "answer_id": 4363315, "author": "Jay", "author_id": 531765, "author_profile": "https://Stackoverflow.com/users/531765", "pm_score": 0, "selected": false, "text": "<p>To convert from instance object to json formatted string and vice-versa, try out Json.NET:\n<a href=\"http://json.codeplex.com/\" rel=\"nofollow\">http://json.codeplex.com/</a></p>\n\n<p>I am currently using it for a project and it's easy to learn and work with and offers some flexibility in terms of serializing and custom type converters. It also supports a LINQ syntax for querying json input.</p>\n" }, { "answer_id": 10821732, "author": "Michael Maddox", "author_id": 12712, "author_profile": "https://Stackoverflow.com/users/12712", "pm_score": 0, "selected": false, "text": "<p>The currently highest rated answer is helpful, but it doesn't send or receive JSON.</p>\n\n<p>Here is an example that uses JSON for both sending and receiving:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/2309954/how-to-post-json-object-in-web-service/10821570#10821570\">How to post json object in web service</a></p>\n\n<p>And here is the StackOverflow question that helped me most to solve this problem:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/10433551/problems-sending-and-receiving-json-between-asp-net-web-service-and-asp-net-web\">Problems sending and receiving JSON between ASP.net web service and ASP.Net web client</a></p>\n\n<p>And here is another related question:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/4982765/json-call-with-c-sharp\">json call with C#</a></p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91275", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm writing a small tool in C# which will need to send and receive data to/from a website using POST and json formatting. I've never done anything like this before in C# (or any language really) so I'm struggling to find some useful information to get me started. I've found some information on the WebRequest class in C# (specifically from [here](http://msdn.microsoft.com/en-us/library/debx8sh9.aspx)) but before I start diving into it, I wondered if this was the right tool for the job. I've found plenty of tools to convert data into the json format but not much else, so any information would be really helpful here in case I end up down a dead end.
WebRequest and more specifically the HttpWebRequest class is a good starting point for what you want to achieve. To create the request you will use the WebRequest.Create and cast the created request to an HttpWebRequest to actually use it. You will then create your post data and send it to the stream like: ``` HttpWebRequest req = (HttpWebRequest) WebRequest.Create("http://mysite.com/index.php"); req.Method = "POST"; req.ContentType = "application/x-www-form-urlencoded"; string postData = "var=value1&var2=value2"; req.ContentLength = postData.Length; StreamWriter stOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII); stOut.Write(postData); stOut.Close(); ``` Similarly you can read the response back by using the GetResponse method which will allow you to read the resultant response stream and do whatever else you need to do. You can find more info on the class at: <http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx>
91,289
<p>I have a migration that runs an SQL script to create a new Postgres schema. When creating a new database in Postgres by default it creates a schema called 'public', which is the main schema we use. The migration to create the new database schema seems to be working fine, however the problem occurs after the migration has run, when rails tries to update the 'schema_info' table that it relies on it says that it does not exist, as if it is looking for it in the new database schema and not the default 'public' schema where the table actually is.</p> <p>Does anybody know how I can tell rails to look at the 'public' schema for this table?</p> <p>Example of SQL being executed: ~</p> <pre><code>CREATE SCHEMA new_schema; COMMENT ON SCHEMA new_schema IS 'this is the new Postgres database schema to sit along side the "public" schema'; -- various tables, triggers and functions created in new_schema </code></pre> <p>Error being thrown: ~</p> <pre><code>RuntimeError: ERROR C42P01 Mrelation "schema_info" does not exist L221 RRangeVarGetRelid: UPDATE schema_info SET version = ?? </code></pre> <p>Thanks for your help</p> <p>Chris Knight</p>
[ { "answer_id": 91449, "author": "Dan Harper", "author_id": 14530, "author_profile": "https://Stackoverflow.com/users/14530", "pm_score": 1, "selected": false, "text": "<p>I'm not sure I understand what you're asking exactly, but, rake will be expecting to update the version of the Rails schema into the schema_info table. Check your database.yml config file, this is where rake will be looking to find the table to update.</p>\n\n<p>Is it a possibility that you are migrating to a new Postgres schema and rake is still pointing to the old one? I'm not sure then that a standard Rails migration is what you need. It might be best to create your own rake task instead.</p>\n\n<p>Edit: If you're referencing two different databases or Postgres schemas, Rails doesn't support this in standard migrations. Rails assumes one database, so migrations from one database to another is usually not possible. When you run \"rake db:migrate\" it actually looks at the RAILS_ENV environment variable to find the correct entry in database.yml. If rake starts the migration looking at the \"development\" environment and database config from database.yml, it will expect to update to this environment at the end of the migration.</p>\n\n<p>So, you'll probably need to do this from outside the Rails stack as you can't reference two databases at the same time within Rails. There are attempts at plugins to allow this, but they're majorly hacky and don't work properly.</p>\n" }, { "answer_id": 91603, "author": "Jean", "author_id": 7898, "author_profile": "https://Stackoverflow.com/users/7898", "pm_score": 4, "selected": true, "text": "<p>Well that depends what your migration looks like, what your database.yml looks like and what exactly you are trying to attempt. Anyway more information is needed change the names if you have to and post an example database.yml and the migration. does the migration change the search_path for the adapter for example ? </p>\n\n<p>But know that in general rails and postgresql schemas don't work well together (yet?). </p>\n\n<p>There are a few places which have problems. Try and build and app that uses only one pg database with 2 non-default schemas one for dev and one for test and tell me about it. (from thefollowing I can already tell you that you will get burned)</p>\n\n<p>Maybe it was fixed since the last time I played with it but when I see <a href=\"http://rails.lighthouseapp.com/projects/8994/tickets/390-postgres-adapter-quotes-table-name-breaks-when-non-default-schema-is-used\" rel=\"noreferrer\">http://rails.lighthouseapp.com/projects/8994/tickets/390-postgres-adapter-quotes-table-name-breaks-when-non-default-schema-is-used</a> or this <a href=\"http://rails.lighthouseapp.com/projects/8994/tickets/918-postgresql-tables-not-generating-correct-schema-list\" rel=\"noreferrer\">http://rails.lighthouseapp.com/projects/8994/tickets/918-postgresql-tables-not-generating-correct-schema-list</a> or this in postgresql_adapter.rb</p>\n\n<pre><code> # Drops a PostgreSQL database\n #\n # Example:\n # drop_database 'matt_development'\n def drop_database(name) #:nodoc:\n execute \"DROP DATABASE IF EXISTS #{name}\"\n end\n</code></pre>\n\n<p>(yes this is wrong if you use the same database with different schemas for both dev and test, this would drop both databases each time you run the unit tests !)</p>\n\n<p>I actually started writing patches. the first one was for the indexes methods in the adapter which didn't care about the search_path ending up with duplicated indexes in some conditions, then I started getting hurt by the rest and ended up abandonning the idea of using schemas: I wanted to get <em>my</em> app done and I didn't have the extra time needed to fix the problems I had using schemas. </p>\n" }, { "answer_id": 18227807, "author": "Sergey Potapov", "author_id": 1013173, "author_profile": "https://Stackoverflow.com/users/1013173", "pm_score": 0, "selected": false, "text": "<p>You can use <a href=\"https://github.com/TMXCredit/pg_power\" rel=\"nofollow\">pg_power</a>. It provides additional DSL for migration to create PostgreSQL schemas and not only.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91289", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11557/" ]
I have a migration that runs an SQL script to create a new Postgres schema. When creating a new database in Postgres by default it creates a schema called 'public', which is the main schema we use. The migration to create the new database schema seems to be working fine, however the problem occurs after the migration has run, when rails tries to update the 'schema\_info' table that it relies on it says that it does not exist, as if it is looking for it in the new database schema and not the default 'public' schema where the table actually is. Does anybody know how I can tell rails to look at the 'public' schema for this table? Example of SQL being executed: ~ ``` CREATE SCHEMA new_schema; COMMENT ON SCHEMA new_schema IS 'this is the new Postgres database schema to sit along side the "public" schema'; -- various tables, triggers and functions created in new_schema ``` Error being thrown: ~ ``` RuntimeError: ERROR C42P01 Mrelation "schema_info" does not exist L221 RRangeVarGetRelid: UPDATE schema_info SET version = ?? ``` Thanks for your help Chris Knight
Well that depends what your migration looks like, what your database.yml looks like and what exactly you are trying to attempt. Anyway more information is needed change the names if you have to and post an example database.yml and the migration. does the migration change the search\_path for the adapter for example ? But know that in general rails and postgresql schemas don't work well together (yet?). There are a few places which have problems. Try and build and app that uses only one pg database with 2 non-default schemas one for dev and one for test and tell me about it. (from thefollowing I can already tell you that you will get burned) Maybe it was fixed since the last time I played with it but when I see <http://rails.lighthouseapp.com/projects/8994/tickets/390-postgres-adapter-quotes-table-name-breaks-when-non-default-schema-is-used> or this <http://rails.lighthouseapp.com/projects/8994/tickets/918-postgresql-tables-not-generating-correct-schema-list> or this in postgresql\_adapter.rb ``` # Drops a PostgreSQL database # # Example: # drop_database 'matt_development' def drop_database(name) #:nodoc: execute "DROP DATABASE IF EXISTS #{name}" end ``` (yes this is wrong if you use the same database with different schemas for both dev and test, this would drop both databases each time you run the unit tests !) I actually started writing patches. the first one was for the indexes methods in the adapter which didn't care about the search\_path ending up with duplicated indexes in some conditions, then I started getting hurt by the rest and ended up abandonning the idea of using schemas: I wanted to get *my* app done and I didn't have the extra time needed to fix the problems I had using schemas.
91,305
<p>Is there a easy way to do this? Or do I have to parse the file and do some search/replacing on my own?</p> <p>The ideal would be something like:</p> <pre><code>var myXML: XML = ???; // ... load xml data into the XML object myXML.someAttribute = newValue; </code></pre>
[ { "answer_id": 91952, "author": "Swaroop C H", "author_id": 4869, "author_profile": "https://Stackoverflow.com/users/4869", "pm_score": 5, "selected": true, "text": "<p>Attributes are accessible in AS3 using the <code>@</code> prefix.</p>\n\n<p>For example:</p>\n\n<pre><code>var myXML:XML = &lt;test name=\"something\"&gt;&lt;/test&gt;;\ntrace(myXML.@name);\nmyXML.@name = \"new\";\ntrace(myXML.@name);\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>something\nnew\n</code></pre>\n" }, { "answer_id": 1292911, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Problem is with some attributes, like @class. Just imagine you want to create HTML source and want to create tag test</p>\n\n<p>So code should be</p>\n\n<p>var myDiv:XML = test\nmyDiv.@class = \"myClass\"; //I want to set it here, because it can vary</p>\n\n<p>but this is not compilable and it throw error (at least in Flex Builder)</p>\n\n<p>in that case you can also use this:</p>\n\n<p>myDiv.@['class'] = \"myClass\";</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Is there a easy way to do this? Or do I have to parse the file and do some search/replacing on my own? The ideal would be something like: ``` var myXML: XML = ???; // ... load xml data into the XML object myXML.someAttribute = newValue; ```
Attributes are accessible in AS3 using the `@` prefix. For example: ``` var myXML:XML = <test name="something"></test>; trace(myXML.@name); myXML.@name = "new"; trace(myXML.@name); ``` Output: ``` something new ```
91,355
<p>Environment: HP laptop with Windows XP SP2</p> <p>I had created some encrypted files using GnuPG (gpg) for Windows. Yesterday, my hard disk failed so I had reimage the hard disk. I have now reinstalled gpg and regenerated my keys using the same passphrase as earlier. But, I am now unable to decrypt the files. I get the following error:</p> <pre> C:\sureshr>gpg -a c:\sureshr\work\passwords.gpg gpg: encrypted with 1024-bit ELG-E key, ID 279AB302, created 2008-07-21 "Suresh Ramaswamy (AAA) BBB" gpg: decryption failed: secret key not available C:\sureshr>gpg --list-keys C:/Documents and Settings/sureshr/Application Data/gnupg\pubring.gpg -------------------------------------------------------------------- pub 1024D/80059241 2008-07-21 uid Suresh Ramaswamy (AAA) BBB sub 1024g/279AB302 2008-07-21 </pre> <p>AAA = gpg comment <br> BBB = my email address</p> <p>I am sure that I am using the correct passphrase. What exactly does this error mean? How do I tell gpg where to find my secret key?</p> <p>Thanks,</p> <p>Suresh</p>
[ { "answer_id": 91371, "author": "David Precious", "author_id": 4040, "author_profile": "https://Stackoverflow.com/users/4040", "pm_score": 3, "selected": false, "text": "<p>Yes, your secret key appears to be missing. Without it, you will not be able to decrypt the files.</p>\n\n<p>Do you have the key backed up somewhere?</p>\n\n<p>Re-creating the keys, whether you use the same passphrase or not, will not work. Each key pair is unique.</p>\n" }, { "answer_id": 91457, "author": "workmad3", "author_id": 16035, "author_profile": "https://Stackoverflow.com/users/16035", "pm_score": 5, "selected": false, "text": "<p>when reimporting your keys from the old keyring, you need to specify the command:</p>\n\n<pre><code>gpg --allow-secret-key-import --import &lt;keyring&gt;\n</code></pre>\n\n<p>otherwise it will only import the public keys, not the private keys.</p>\n" }, { "answer_id": 1482670, "author": "Randy Fay", "author_id": 179638, "author_profile": "https://Stackoverflow.com/users/179638", "pm_score": 3, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/questions/91355/gnupg-decryption-failed-secret-key-not-available-error-from-gpg-on-windows/91457#91457\">workmad3</a> is apparently out of date, at least for current gpg, as the <code>--allow-secret-key-import</code> is now obsolete and does nothing.</p>\n\n<p>What happened to me was that I failed to export properly. Just doing <code>gpg --export</code> is not adequate, as it only exports the public keys. When exporting keys, you have to do</p>\n\n<pre><code>gpg --export-secret-keys &gt;keyfile\n</code></pre>\n" }, { "answer_id": 1731222, "author": "Bill", "author_id": 210683, "author_profile": "https://Stackoverflow.com/users/210683", "pm_score": 2, "selected": false, "text": "<p>The resolution to this problem for me, was to notify the sender that he did use the Public key that I sent them but rather someone elses. You should see the key that they used. Tell them to use the correct one.</p>\n" }, { "answer_id": 7319251, "author": "ata", "author_id": 930549, "author_profile": "https://Stackoverflow.com/users/930549", "pm_score": 3, "selected": false, "text": "<p>One more cause for the \"secret key not available\" message: GPG version mismatch.</p>\n\n<p>Practical example: I had been using GPG v1.4. Switching packaging systems, the MacPorts supplied gpg was removed, and revealed another gpg binary in the path, this one version 2.0. For decryption, it was unable to locate the secret key and gave this very error.\nFor encryption, it complained about an unusable public key.\nHowever, gpg -k and -K both listed valid keys, which was the cause of major confusion.</p>\n" }, { "answer_id": 7974613, "author": "aaronsw", "author_id": 4300, "author_profile": "https://Stackoverflow.com/users/4300", "pm_score": 5, "selected": false, "text": "<p>You need to import not only your secret key, but also the corresponding public key, or you'll get this error.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Environment: HP laptop with Windows XP SP2 I had created some encrypted files using GnuPG (gpg) for Windows. Yesterday, my hard disk failed so I had reimage the hard disk. I have now reinstalled gpg and regenerated my keys using the same passphrase as earlier. But, I am now unable to decrypt the files. I get the following error: ``` C:\sureshr>gpg -a c:\sureshr\work\passwords.gpg gpg: encrypted with 1024-bit ELG-E key, ID 279AB302, created 2008-07-21 "Suresh Ramaswamy (AAA) BBB" gpg: decryption failed: secret key not available C:\sureshr>gpg --list-keys C:/Documents and Settings/sureshr/Application Data/gnupg\pubring.gpg -------------------------------------------------------------------- pub 1024D/80059241 2008-07-21 uid Suresh Ramaswamy (AAA) BBB sub 1024g/279AB302 2008-07-21 ``` AAA = gpg comment BBB = my email address I am sure that I am using the correct passphrase. What exactly does this error mean? How do I tell gpg where to find my secret key? Thanks, Suresh
when reimporting your keys from the old keyring, you need to specify the command: ``` gpg --allow-secret-key-import --import <keyring> ``` otherwise it will only import the public keys, not the private keys.
91,357
<p>I want to log in to Stack Overflow with Techorati OpenID hosted at my site.</p> <p><a href="https://stackoverflow.com/users/login">https://stackoverflow.com/users/login</a> has some basic information.</p> <p>I understood that I should change</p> <pre><code>&lt;link rel="openid.delegate" href="http://yourname.x.com" /&gt; </code></pre> <p>to</p> <pre><code>&lt;link rel="openid.delegate" href="http://technorati.com/people/technorati/USERNAME/" /&gt; </code></pre> <p>but if I change</p> <pre><code>&lt;link rel="openid.server" href="http://x.com/server" /&gt; </code></pre> <p>to</p> <pre><code>&lt;link rel="openid.server" href="http://technorati.com/server" /&gt; </code></pre> <p>or</p> <pre><code>&lt;link rel="openid.server" href="http://technorati.com/" /&gt; </code></pre> <p>it does not work.</p>
[ { "answer_id": 91371, "author": "David Precious", "author_id": 4040, "author_profile": "https://Stackoverflow.com/users/4040", "pm_score": 3, "selected": false, "text": "<p>Yes, your secret key appears to be missing. Without it, you will not be able to decrypt the files.</p>\n\n<p>Do you have the key backed up somewhere?</p>\n\n<p>Re-creating the keys, whether you use the same passphrase or not, will not work. Each key pair is unique.</p>\n" }, { "answer_id": 91457, "author": "workmad3", "author_id": 16035, "author_profile": "https://Stackoverflow.com/users/16035", "pm_score": 5, "selected": false, "text": "<p>when reimporting your keys from the old keyring, you need to specify the command:</p>\n\n<pre><code>gpg --allow-secret-key-import --import &lt;keyring&gt;\n</code></pre>\n\n<p>otherwise it will only import the public keys, not the private keys.</p>\n" }, { "answer_id": 1482670, "author": "Randy Fay", "author_id": 179638, "author_profile": "https://Stackoverflow.com/users/179638", "pm_score": 3, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/questions/91355/gnupg-decryption-failed-secret-key-not-available-error-from-gpg-on-windows/91457#91457\">workmad3</a> is apparently out of date, at least for current gpg, as the <code>--allow-secret-key-import</code> is now obsolete and does nothing.</p>\n\n<p>What happened to me was that I failed to export properly. Just doing <code>gpg --export</code> is not adequate, as it only exports the public keys. When exporting keys, you have to do</p>\n\n<pre><code>gpg --export-secret-keys &gt;keyfile\n</code></pre>\n" }, { "answer_id": 1731222, "author": "Bill", "author_id": 210683, "author_profile": "https://Stackoverflow.com/users/210683", "pm_score": 2, "selected": false, "text": "<p>The resolution to this problem for me, was to notify the sender that he did use the Public key that I sent them but rather someone elses. You should see the key that they used. Tell them to use the correct one.</p>\n" }, { "answer_id": 7319251, "author": "ata", "author_id": 930549, "author_profile": "https://Stackoverflow.com/users/930549", "pm_score": 3, "selected": false, "text": "<p>One more cause for the \"secret key not available\" message: GPG version mismatch.</p>\n\n<p>Practical example: I had been using GPG v1.4. Switching packaging systems, the MacPorts supplied gpg was removed, and revealed another gpg binary in the path, this one version 2.0. For decryption, it was unable to locate the secret key and gave this very error.\nFor encryption, it complained about an unusable public key.\nHowever, gpg -k and -K both listed valid keys, which was the cause of major confusion.</p>\n" }, { "answer_id": 7974613, "author": "aaronsw", "author_id": 4300, "author_profile": "https://Stackoverflow.com/users/4300", "pm_score": 5, "selected": false, "text": "<p>You need to import not only your secret key, but also the corresponding public key, or you'll get this error.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91357", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17469/" ]
I want to log in to Stack Overflow with Techorati OpenID hosted at my site. <https://stackoverflow.com/users/login> has some basic information. I understood that I should change ``` <link rel="openid.delegate" href="http://yourname.x.com" /> ``` to ``` <link rel="openid.delegate" href="http://technorati.com/people/technorati/USERNAME/" /> ``` but if I change ``` <link rel="openid.server" href="http://x.com/server" /> ``` to ``` <link rel="openid.server" href="http://technorati.com/server" /> ``` or ``` <link rel="openid.server" href="http://technorati.com/" /> ``` it does not work.
when reimporting your keys from the old keyring, you need to specify the command: ``` gpg --allow-secret-key-import --import <keyring> ``` otherwise it will only import the public keys, not the private keys.
91,360
<p>I need to sum points on each level earned by a tree of users. Level 1 is the sum of users' points of the users 1 level below the user. Level 2 is the Level 1 points of the users 2 levels below the user, etc...</p> <p>The calculation happens once a month on a non production server, no worries about performance.</p> <p>What would the SQL look like to do it?</p> <p>If you're confused, don't worry, I am as well!</p> <p>User table:</p> <pre><code>ID ParentID Points 1 0 230 2 1 150 3 0 80 4 1 110 5 4 54 6 4 342 Tree: 0 |---\ 1 3 | \ 2 4--- \ \ 5 6 </code></pre> <p>Output should be:</p> <pre><code>ID Points Level1 Level2 1 230 150+110 150+110+54+342 2 150 3 80 4 110 54+342 5 54 6 342 </code></pre> <p>SQL Server Syntax and functions preferably...</p>
[ { "answer_id": 91372, "author": "Grad van Horck", "author_id": 12569, "author_profile": "https://Stackoverflow.com/users/12569", "pm_score": 1, "selected": false, "text": "<p>I would say: create a stored procedure, probably has the best performance.\nOr if you have a maximum number of levels, you could create subqueries, but they will have a very poort performance.</p>\n\n<p>(Or you could get MS SQL Server 2008 and get the new hierarchy functions... ;) )</p>\n" }, { "answer_id": 91395, "author": "Manrico Corazzi", "author_id": 4690, "author_profile": "https://Stackoverflow.com/users/4690", "pm_score": 2, "selected": false, "text": "<p>If you were using Oracle DBMS that would be pretty straightforward since Oracle supports tree queries with the <strong>CONNECT BY/STARTS WITH</strong> syntax. For SQL Server I think you might find <a href=\"http://searchwindevelopment.techtarget.com/tip/0,289483,sid8_gci1277481,00.html\" rel=\"nofollow noreferrer\">Common Table Expressions</a> useful</p>\n" }, { "answer_id": 91400, "author": "Matthias Winkelmann", "author_id": 4494, "author_profile": "https://Stackoverflow.com/users/4494", "pm_score": 2, "selected": false, "text": "<p>Trees don't work well with SQL. If you have very (very very) few write accesses, you could change the tree implementation to use nested sets, that would make this query incredibly easy.</p>\n\n<p>Example (if I'm not mistaken):</p>\n\n<pre><code>SELECT SUM(points) \nFROM users \nwhere left &gt; x and right &lt; y \n</code></pre>\n\n<p>However, any changes on the tree require touching a massive amount of rows. It's probably better to just do the recursion in you client. </p>\n" }, { "answer_id": 91406, "author": "Ilya Kochetov", "author_id": 15329, "author_profile": "https://Stackoverflow.com/users/15329", "pm_score": 0, "selected": false, "text": "<p>You have a couple of options:</p>\n\n<ol>\n<li>Use a cursor and a recursive user-defined function call (it's quite slow)</li>\n<li>Create a cache table, update it on INSERT using a trigger (it's the fastest solution but could be problematic if you have lots of updates to the main table)</li>\n<li>Do a client-side recursive calculation (preferable if you don't have too many records)</li>\n</ol>\n" }, { "answer_id": 91418, "author": "Matthias Kestenholz", "author_id": 317346, "author_profile": "https://Stackoverflow.com/users/317346", "pm_score": 1, "selected": false, "text": "<p>If you are working with trees stored in a relational database, I'd suggest looking at \"nested set\" or \"modified preorder tree traversal\". The SQL will be as simple as that:</p>\n\n<pre><code>SELECT id, \n SUM(value) AS value \nFROM table \nWHERE left&gt;left\\_value\\_of\\_your\\_node \n AND right&lt;$right\\_value\\_of\\_your\\_node;\n</code></pre>\n\n<p>... and do this for every node you are interested in.</p>\n\n<p>Maybe this will help you:\n<a href=\"http://www.dbazine.com/oracle/or-articles/tropashko4\" rel=\"nofollow noreferrer\">http://www.dbazine.com/oracle/or-articles/tropashko4</a> or use google.</p>\n" }, { "answer_id": 91464, "author": "Milan Babuškov", "author_id": 14690, "author_profile": "https://Stackoverflow.com/users/14690", "pm_score": 0, "selected": false, "text": "<p>You can write a simple recursive function to do the job. My MSSQL is a little bit rusty, but it would look like this:</p>\n\n<pre><code>CREATE FUNCTION CALC\n(\n@node integer,\n)\nreturns \n(\n@total integer\n)\nas\nbegin\n select @total = (select node_value from yourtable where node_id = @node);\n\n declare @children table (value integer);\n insert into @children \n select calc(node_id) from yourtable where parent_id = @node;\n\n @current = @current + select sum(value) from @children;\n return\nend\n</code></pre>\n" }, { "answer_id": 91903, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 1, "selected": false, "text": "<p>SQL in general, like others said, does not handle well such relations. Typically, a surrogate 'relations' table is needed (id, parent_id, unique key on (id, parent_id)), where:</p>\n\n<ul>\n<li><p>every time you add a record in 'table', you:</p>\n\n<p><code>INSERT INTO relations (id, parent_id) VALUES ([current_id], [current_id]);</code></p>\n\n<p><code>INSERT INTO relations (id, parent_id) VALUES ([current_id], [current_parent_id]);</code></p>\n\n<p><code>INSERT INTO relations (id, parent_id)</code>\n<code>SELECT [current_id], parent_id</code>\n<code>FROM relations</code>\n<code>WHERE id = [current_parent_id];</code></p></li>\n<li><p>have logic to avoid cycles</p></li>\n<li><p>make sure that updates, deletions on 'relations' are handled with stored procedures</p></li>\n</ul>\n\n<p>Given that table, you want:</p>\n\n<pre><code>SELECT rel.parent_id, SUM(tbl.points)\nFROM table tbl INNER JOIN relations rel ON tbl.id=rel.id\nWHERE rel.parent_id &lt;&gt; 0\nGROUP BY rel.parent_id;\n</code></pre>\n" }, { "answer_id": 93202, "author": "Darrel Miller", "author_id": 6819, "author_profile": "https://Stackoverflow.com/users/6819", "pm_score": 1, "selected": false, "text": "<p>Ok, this gives you the results you are looking for, but there are no guarantees that I didn't miss something. Consider it a starting point. I used SQL 2005 to do this, SQL 2000 does not support CTE's</p>\n\n<pre><code>WITH Parent (id, GrandParentId, parentId, Points, Level1Points, Level2Points)\nAS\n(\n -- Find root\n SELECT id, \n 0 AS GrandParentId,\n ParentId,\n Points,\n 0 AS Level1Points,\n 0 AS Level2Points\n FROM tblPoints ptr\n WHERE ptr.ParentId = 0\n\n UNION ALL (\n -- Level2 Points\n SELECT pa.GrandParentId AS Id,\n NULL AS GrandParentId,\n NULL AS ParentId,\n 0 AS Points, \n 0 AS Level1Points,\n pa.Points AS Level2Points\n FROM tblPoints pt\n JOIN Parent pa ON pa.GrandParentId = pt.Id \n UNION ALL\n -- Level1 Points\n SELECT pt.ParentId AS Id,\n NULL AS GrandParentId,\n NULL AS ParentId,\n 0 AS Points, \n pt.Points AS Level1Points,\n 0 AS Level2Points\n FROM tblPoints pt\n JOIN Parent pa ON pa.Id = pt.ParentId AND pa.ParentId IS NOT NULL \n UNION ALL\n -- Points\n SELECT pt.id,\n pa.ParentId AS GrandParentId,\n pt.ParentId,\n pt.Points, \n 0 AS Level1Points,\n 0 AS Level2Points\n FROM tblPoints pt\n JOIN Parent pa ON pa.Id = pt.ParentId AND pa.ParentId IS NOT NULL )\n)\nSELECT id, \n SUM(Points) AS Points, \n SUM(Level1Points) AS Level1Points,\n CASE WHEN SUM(Level2Points) &gt; 0 THEN SUM(Level1Points) + SUM(Level2Points) ELSE 0 END AS Level2Points\nFROM Parent\nGROUP BY id \nORDER by id\n</code></pre>\n" }, { "answer_id": 4429139, "author": "Stef Heyenrath", "author_id": 255966, "author_profile": "https://Stackoverflow.com/users/255966", "pm_score": 0, "selected": false, "text": "<p>The following table:</p>\n\n<pre><code>Id ParentId\n1 NULL\n11 1\n12 1\n110 11\n111 11\n112 11\n120 12\n121 12\n122 12\n123 12\n124 12\n</code></pre>\n\n<p>And the following Amount table:</p>\n\n<pre><code>Id Val\n110 500\n111 50\n112 5\n120 3000\n121 30000\n122 300000\n</code></pre>\n\n<p>Only the leaves (last level) Id's have a value defined.\nThe SQL query to get the data looks like:</p>\n\n<pre><code>;WITH Data (Id, Val) AS\n(\n select t.Id, SUM(v.val) as Val from dbo.TestTable t\n join dbo.Amount v on t.Id = v.Id\n group by t.Id\n)\n\nselect cd.Id, ISNULL(SUM(cd.Val), 0) as Amount FROM\n(\n -- level 3\n select t.Id, d.val from TestTable t\n left join Data d on d.id = t.Id\n\n UNION\n\n -- level 2\n select t.parentId as Id, sum(y.Val) from TestTable t\n left join Data y on y.id = t.Id\n where t.parentId is not null\n group by t.parentId\n\n UNION\n\n -- level 1\n select t.parentId as Id, sum(y.Val) from TestTable t\n join TestTable c on c.parentId = t.Id\n left join Data y on y.id = c.Id\n where t.parentId is not null\n group by t.parentId\n) AS cd\ngroup by id\n</code></pre>\n\n<p>this results in the output:</p>\n\n<pre><code>Id Amount\n1 333555\n11 555\n12 333000\n110 500\n111 50\n112 5\n120 3000\n121 30000\n122 300000\n123 0\n124 0\n</code></pre>\n\n<p>I hope this helps.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6681/" ]
I need to sum points on each level earned by a tree of users. Level 1 is the sum of users' points of the users 1 level below the user. Level 2 is the Level 1 points of the users 2 levels below the user, etc... The calculation happens once a month on a non production server, no worries about performance. What would the SQL look like to do it? If you're confused, don't worry, I am as well! User table: ``` ID ParentID Points 1 0 230 2 1 150 3 0 80 4 1 110 5 4 54 6 4 342 Tree: 0 |---\ 1 3 | \ 2 4--- \ \ 5 6 ``` Output should be: ``` ID Points Level1 Level2 1 230 150+110 150+110+54+342 2 150 3 80 4 110 54+342 5 54 6 342 ``` SQL Server Syntax and functions preferably...
If you were using Oracle DBMS that would be pretty straightforward since Oracle supports tree queries with the **CONNECT BY/STARTS WITH** syntax. For SQL Server I think you might find [Common Table Expressions](http://searchwindevelopment.techtarget.com/tip/0,289483,sid8_gci1277481,00.html) useful
91,362
<p>How can brackets be escaped in using <code>string.Format</code>?</p> <p>For example:</p> <pre><code>String val = &quot;1,2,3&quot; String.Format(&quot; foo {{0}}&quot;, val); </code></pre> <p>This example doesn't throw an exception, but it outputs the string <code>foo {0}</code>.</p> <p>Is there a way to escape the brackets?</p>
[ { "answer_id": 91375, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 11, "selected": true, "text": "<p>For you to output <code> foo {1, 2, 3}</code> you have to do something like:</p>\n<pre><code>string t = &quot;1, 2, 3&quot;;\nstring v = String.Format(&quot; foo {{{0}}}&quot;, t);\n</code></pre>\n<p>To output a <code>{</code> you use <code>{{</code> and to output a <code>}</code> you use <code>}}</code>.</p>\n<p><strong>Or now, you can also use C# string interpolation like this (a feature available in C# 6.0)</strong></p>\n<p><strong>Escaping brackets: String interpolation $(&quot;&quot;)</strong>. It is new feature in C# 6.0.</p>\n<pre><code>var inVal = &quot;1, 2, 3&quot;;\nvar outVal = $&quot; foo {{{inVal}}}&quot;;\n// The output will be: foo {1, 2, 3}\n</code></pre>\n" }, { "answer_id": 91385, "author": "Wolfwyrd", "author_id": 15570, "author_profile": "https://Stackoverflow.com/users/15570", "pm_score": 6, "selected": false, "text": "<p>Almost there! The escape sequence for a brace is <code>{{</code> or <code>}}</code> so for your example you would use:</p>\n\n<pre><code>string t = \"1, 2, 3\";\nstring v = String.Format(\" foo {{{0}}}\", t);\n</code></pre>\n" }, { "answer_id": 2491286, "author": "elec", "author_id": 298907, "author_profile": "https://Stackoverflow.com/users/298907", "pm_score": 5, "selected": false, "text": "<p>You can use double open brackets and double closing brackets which will only show one bracket on your page. </p>\n" }, { "answer_id": 15085178, "author": "Guru Kara", "author_id": 386161, "author_profile": "https://Stackoverflow.com/users/386161", "pm_score": 8, "selected": false, "text": "<p>Yes, to output <code>{</code> in <code>string.Format</code> you have to escape it like this: <code>{{</code></p>\n<p>So the following will output <code>&quot;foo {1,2,3}&quot;</code>.</p>\n<pre><code>String val = &quot;1,2,3&quot;;\nString.Format(&quot; foo {{{0}}}&quot;, val);\n</code></pre>\n<p><em>But</em> you have to know about a design bug in C# which is that by going on the above logic you would assume this below code will print {24.00}:</p>\n<pre><code>int i = 24;\nstring str = String.Format(&quot;{{{0:N}}}&quot;, i); // Gives '{N}' instead of {24.00}\n</code></pre>\n<p>But this prints {N}. This is because the way C# parses escape sequences and format characters. To get the desired value in the above case, you have to use this instead:</p>\n<pre><code>String.Format(&quot;{0}{1:N}{2}&quot;, &quot;{&quot;, i, &quot;}&quot;) // Evaluates to {24.00}\n</code></pre>\n<h3>Reference Articles</h3>\n<ul>\n<li><a href=\"https://learn.microsoft.com/en-us/archive/blogs/brada/string-format-gottach\" rel=\"noreferrer\">String.Format gotcha</a></li>\n<li><a href=\"https://learn.microsoft.com/en-us/archive/blogs/brada/string-formatting-faq\" rel=\"noreferrer\">String Formatting FAQ</a></li>\n</ul>\n" }, { "answer_id": 37077594, "author": "pomber", "author_id": 1325646, "author_profile": "https://Stackoverflow.com/users/1325646", "pm_score": 3, "selected": false, "text": "<pre><code>[TestMethod]\npublic void BraceEscapingTest()\n{\n var result = String.Format(\"Foo {{0}}\", \"1,2,3\"); //\"1,2,3\" is not parsed\n Assert.AreEqual(\"Foo {0}\", result);\n\n result = String.Format(\"Foo {{{0}}}\", \"1,2,3\");\n Assert.AreEqual(\"Foo {1,2,3}\", result);\n\n result = String.Format(\"Foo {0} {{bar}}\", \"1,2,3\");\n Assert.AreEqual(\"Foo 1,2,3 {bar}\", result);\n\n result = String.Format(\"{{{0:N}}}\", 24); //24 is not parsed, see @Guru Kara answer\n Assert.AreEqual(\"{N}\", result);\n\n result = String.Format(\"{0}{1:N}{2}\", \"{\", 24, \"}\");\n Assert.AreEqual(\"{24.00}\", result);\n\n result = String.Format(\"{{{0}}}\", 24.ToString(\"N\"));\n Assert.AreEqual(\"{24.00}\", result);\n}\n</code></pre>\n" }, { "answer_id": 43474880, "author": "Adam Cox", "author_id": 2250792, "author_profile": "https://Stackoverflow.com/users/2250792", "pm_score": 4, "selected": false, "text": "<p>I came here in search of how to build JSON strings ad-hoc (without serializing a class/object) in C#. In other words, how to escape braces and quotes while using <a href=\"https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/interpolated-strings\" rel=\"noreferrer\">Interpolated Strings in C#</a> and &quot;<a href=\"https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/string\" rel=\"noreferrer\">verbatim string literals</a>&quot; (double quoted strings with '@' prefix), like...</p>\n<pre><code>var json = $@&quot;{{&quot;&quot;name&quot;&quot;:&quot;&quot;{name}&quot;&quot;}}&quot;;\n</code></pre>\n" }, { "answer_id": 44661558, "author": "SliverNinja - MSFT", "author_id": 175679, "author_profile": "https://Stackoverflow.com/users/175679", "pm_score": 4, "selected": false, "text": "<p>Escaping <strong>curly brackets</strong> AND using <strong>string interpolation</strong> makes for an interesting challenge. You need to use <em>quadruple brackets</em> to escape the <strong>string interpolation</strong> parsing and <code>string.format</code> parsing. </p>\n\n<h3>Escaping Brackets: String Interpolation $(\"\") and String.Format</h3>\n\n<pre class=\"lang-cs prettyprint-override\"><code>string localVar = \"dynamic\";\nstring templateString = $@\"&lt;h2&gt;{0}&lt;/h2&gt;&lt;div&gt;this is my {localVar} template using a {{{{custom tag}}}}&lt;/div&gt;\";\nstring result = string.Format(templateString, \"String Interpolation\");\n\n// OUTPUT: &lt;h2&gt;String Interpolation&lt;/h2&gt;&lt;div&gt;this is my dynamic template using a {custom tag}&lt;/div&gt;\n</code></pre>\n" }, { "answer_id": 48081666, "author": "Aarif", "author_id": 6027876, "author_profile": "https://Stackoverflow.com/users/6027876", "pm_score": 2, "selected": false, "text": "<p>Or you can use C# string interpolation like this (feature available in C# 6.0):</p>\n<pre><code>var value = &quot;1, 2, 3&quot;;\nvar output = $&quot; foo {{{value}}}&quot;;\n</code></pre>\n" }, { "answer_id": 55636923, "author": "Goldfish", "author_id": 3355999, "author_profile": "https://Stackoverflow.com/users/3355999", "pm_score": 2, "selected": false, "text": "<p><strong>My objective:</strong></p>\n<p>I needed to assign the value <code>&quot;{CR}{LF}&quot;</code> to a <code>string</code> variable <code>delimiter</code>.</p>\n<p><strong>C# code:</strong></p>\n<pre><code>string delimiter= &quot;{{CR}}{{LF}}&quot;;\n</code></pre>\n<p>Note: To escape special characters normally you have to use \\. For opening curly bracket <code>{</code>, use one extra, like <code>{{</code>. For closing curly bracket <code>}</code>, use one extra, <code>}}</code>.</p>\n" }, { "answer_id": 58342909, "author": "Manish Kumar Gurjar", "author_id": 6265595, "author_profile": "https://Stackoverflow.com/users/6265595", "pm_score": 0, "selected": false, "text": "<p><strong>Escaping Brackets: String Interpolation $(&quot;&quot;):</strong></p>\n<p>Now, you can also use C# string interpolation like this (feature available in C# 6.0):</p>\n<pre><code>var inVal = &quot;1, 2, 3&quot;;\nvar outVal = $&quot; foo {{{inVal}}}&quot;;\n// The output will be: foo {1, 2, 3}\n</code></pre>\n" }, { "answer_id": 71252214, "author": "Mohamed Anas", "author_id": 12511391, "author_profile": "https://Stackoverflow.com/users/12511391", "pm_score": 2, "selected": false, "text": "<p>You can also use like this.\n<code>var outVal = $&quot; foo {&quot;{&quot;}{inVal}{&quot;}&quot;} --- {&quot;{&quot;}Also Like This{&quot;}&quot;}&quot;</code></p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91362", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4685/" ]
How can brackets be escaped in using `string.Format`? For example: ``` String val = "1,2,3" String.Format(" foo {{0}}", val); ``` This example doesn't throw an exception, but it outputs the string `foo {0}`. Is there a way to escape the brackets?
For you to output `foo {1, 2, 3}` you have to do something like: ``` string t = "1, 2, 3"; string v = String.Format(" foo {{{0}}}", t); ``` To output a `{` you use `{{` and to output a `}` you use `}}`. **Or now, you can also use C# string interpolation like this (a feature available in C# 6.0)** **Escaping brackets: String interpolation $("")**. It is new feature in C# 6.0. ``` var inVal = "1, 2, 3"; var outVal = $" foo {{{inVal}}}"; // The output will be: foo {1, 2, 3} ```
91,368
<p>From a shell script, how do I check if a directory contains files?</p> <p>Something similar to this</p> <pre class="lang-sh prettyprint-override"><code>if [ -e /some/dir/* ]; then echo "huzzah"; fi; </code></pre> <p>but which works if the directory contains one or several files (the above one only works with exactly 0 or 1 files).</p>
[ { "answer_id": 91387, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 5, "selected": false, "text": "<p>Try:</p>\n\n<pre><code>if [ ! -z `ls /some/dir/*` ]; then echo \"huzzah\"; fi\n</code></pre>\n" }, { "answer_id": 91394, "author": "Andrew Taylor", "author_id": 1776, "author_profile": "https://Stackoverflow.com/users/1776", "pm_score": 3, "selected": false, "text": "<pre><code>DIR=\"/some/dir\"\nif [ \"$(ls -A $DIR)\" ]; then\n echo 'There is something alive in here'\nfi\n</code></pre>\n" }, { "answer_id": 91403, "author": "DGM", "author_id": 14253, "author_profile": "https://Stackoverflow.com/users/14253", "pm_score": 3, "selected": false, "text": "<p>Could you compare the output of this?</p>\n\n<pre><code> ls -A /some/dir | wc -l\n</code></pre>\n" }, { "answer_id": 91419, "author": "Toby", "author_id": 14265, "author_profile": "https://Stackoverflow.com/users/14265", "pm_score": -1, "selected": false, "text": "<pre><code>if ls /some/dir/* &gt;/dev/null 2&gt;&amp;1 ; then echo \"huzzah\"; fi;\n</code></pre>\n" }, { "answer_id": 91558, "author": "Bruno De Fraine", "author_id": 6918, "author_profile": "https://Stackoverflow.com/users/6918", "pm_score": 7, "selected": true, "text": "<p>The solutions so far use <code>ls</code>. Here's an all bash solution:</p>\n\n<pre><code>#!/bin/bash\nshopt -s nullglob dotglob # To include hidden files\nfiles=(/some/dir/*)\nif [ ${#files[@]} -gt 0 ]; then echo \"huzzah\"; fi\n</code></pre>\n" }, { "answer_id": 91639, "author": "mweerden", "author_id": 4285, "author_profile": "https://Stackoverflow.com/users/4285", "pm_score": 6, "selected": false, "text": "<p>How about the following:</p>\n\n<pre><code>if find /some/dir/ -maxdepth 0 -empty | read v; then echo \"Empty dir\"; fi\n</code></pre>\n\n<p>This way there is no need for generating a complete listing of the contents of the directory. The <code>read</code> is both to discard the output and make the expression evaluate to true only when something is read (i.e. <code>/some/dir/</code> is found empty by <code>find</code>).</p>\n" }, { "answer_id": 91769, "author": "Gravstar", "author_id": 17381, "author_profile": "https://Stackoverflow.com/users/17381", "pm_score": 4, "selected": false, "text": "<p>Take care with directories with a lot of files! It could take a some time to evaluate the <code>ls</code> command.</p>\n\n<p>IMO the best solution is the one that uses </p>\n\n<pre><code>find /some/dir/ -maxdepth 0 -empty\n</code></pre>\n" }, { "answer_id": 410190, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>This may be a really late response but here is a solution that works. This line only recognizes th existance of files! It will not give you a false positive if directories exist.</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>if find /path/to/check/* -maxdepth 0 -type f | read\n then echo \"Files Exist\"\nfi\n</code></pre>\n" }, { "answer_id": 2403078, "author": "Roland Illig", "author_id": 225757, "author_profile": "https://Stackoverflow.com/users/225757", "pm_score": 2, "selected": false, "text": "<pre>\n# Checks whether a directory contains any nonhidden files.\n#\n# usage: if isempty \"$HOME\"; then echo \"Welcome home\"; fi\n#\nisempty() {\n for _ief in $1/*; do\n if [ -e \"$_ief\" ]; then\n return 1\n fi\n done\n return 0\n}\n</pre>\n\n<p>Some implementation notes:</p>\n\n<ul>\n<li>The <code>for</code> loop avoids a call to an external <code>ls</code> process. It still reads all the directory entries once. This can only be optimized away by writing a C program that uses readdir() explicitly.</li>\n<li>The <code>test -e</code> inside the loop catches the case of an empty directory, in which case the variable <code>_ief</code> would be assigned the value \"somedir/*\". Only if that file exists will the function return \"nonempty\"</li>\n<li>This function will work in all POSIX implementations. But be aware that the Solaris /bin/sh doesn't fall into that category. Its <code>test</code> implementation doesn't support the <code>-e</code> flag.</li>\n</ul>\n" }, { "answer_id": 4778234, "author": "gr8can8dian", "author_id": 586929, "author_profile": "https://Stackoverflow.com/users/586929", "pm_score": 4, "selected": false, "text": "<pre><code># Works on hidden files, directories and regular files\n### isEmpty()\n# This function takes one parameter:\n# $1 is the directory to check\n# Echoes \"huzzah\" if the directory has files\nfunction isEmpty(){\n if [ \"$(ls -A $1)\" ]; then\n echo \"huzzah\"\n else \n echo \"has no files\"\n fi\n}\n</code></pre>\n" }, { "answer_id": 8954828, "author": "thejartender", "author_id": 835806, "author_profile": "https://Stackoverflow.com/users/835806", "pm_score": -1, "selected": false, "text": "<p>I dislike the <code>ls - A</code> solutions posted. Most likely you wish to test if the directory is empty because you don't wish to delete it. The following does that. If however you just wish to log an empty file, surely deleting and recreating it is quicker then listing possibly infinite files?</p>\n\n<p>This should work... </p>\n\n<pre><code>if ! rmdir ${target}\nthen\n echo \"not empty\"\nelse\n echo \"empty\"\n mkdir ${target}\nfi\n</code></pre>\n" }, { "answer_id": 16307494, "author": "N D", "author_id": 780180, "author_profile": "https://Stackoverflow.com/users/780180", "pm_score": -1, "selected": false, "text": "<p>to test a specific target directory</p>\n\n<pre><code>if [ -d $target_dir ]; then\n ls_contents=$(ls -1 $target_dir | xargs); \n if [ ! -z \"$ls_contents\" -a \"$ls_contents\" != \"\" ]; then\n echo \"is not empty\";\n else\n echo \"is empty\";\n fi;\nelse\n echo \"directory does not exist\";\nfi;\n</code></pre>\n" }, { "answer_id": 17902999, "author": "oHo", "author_id": 938111, "author_profile": "https://Stackoverflow.com/users/938111", "pm_score": 7, "selected": false, "text": "<h1>Three best tricks</h1>\n\n<hr>\n\n<h2><code>shopt -s nullglob dotglob; f=your/dir/*; ((${#f}))</code></h2>\n\n<p>This trick is 100% <code>bash</code> and invokes (spawns) a sub-shell. The idea is from <a href=\"https://stackoverflow.com/a/91558/938111\">Bruno De Fraine</a> and improved by <a href=\"https://stackoverflow.com/users/141736\">teambob</a>'s comment. </p>\n\n<pre><code>files=$(shopt -s nullglob dotglob; echo your/dir/*)\nif (( ${#files} ))\nthen\n echo \"contains files\"\nelse \n echo \"empty (or does not exist or is a file)\"\nfi\n</code></pre>\n\n<p><strong>Note:</strong> no difference between an empty directory and a non-existing one (and even when the provided path is a file).</p>\n\n<p>There is a similar alternative and more details (and more examples) on the <a href=\"http://mywiki.wooledge.org/BashFAQ/004\" rel=\"noreferrer\"><em>'official'</em> FAQ for #bash IRC channel</a>:</p>\n\n<pre><code>if (shopt -s nullglob dotglob; f=(*); ((${#f[@]})))\nthen\n echo \"contains files\"\nelse \n echo \"empty (or does not exist, or is a file)\"\nfi\n</code></pre>\n\n<hr>\n\n<h2><code>[ -n \"$(ls -A your/dir)\" ]</code></h2>\n\n<p>This trick is inspired from <a href=\"http://www.cyberciti.biz/faq/linux-unix-shell-check-if-directory-empty/\" rel=\"noreferrer\">nixCraft's article</a> posted in 2007. Add <code>2&gt;/dev/null</code> to suppress the output error <code>\"No such file or directory\"</code>.<br>\n<sup>See also <a href=\"https://stackoverflow.com/a/91394/938111\">Andrew Taylor</a>'s answer (2008) and <a href=\"https://stackoverflow.com/a/4778234/938111\">gr8can8dian</a>'s answer (2011).</sup></p>\n\n<pre><code>if [ -n \"$(ls -A your/dir 2&gt;/dev/null)\" ]\nthen\n echo \"contains files (or is a file)\"\nelse\n echo \"empty (or does not exist)\"\nfi\n</code></pre>\n\n<p>or the one-line bashism version:</p>\n\n<pre><code>[[ $(ls -A your/dir) ]] &amp;&amp; echo \"contains files\" || echo \"empty\"\n</code></pre>\n\n<p><strong>Note:</strong> <code>ls</code> returns <code>$?=2</code> when the directory does not exist. But no difference between a file and an empty directory.</p>\n\n<hr>\n\n<h2><code>[ -n \"$(find your/dir -prune -empty)\" ]</code></h2>\n\n<p>This last trick is inspired from <a href=\"https://stackoverflow.com/a/91769/938111\">gravstar's answer</a> where <code>-maxdepth 0</code> is replaced by <code>-prune</code> and improved by <a href=\"https://stackoverflow.com/users/324105/phils\">phils</a>'s comment.</p>\n\n<pre><code>if [ -n \"$(find your/dir -prune -empty 2&gt;/dev/null)\" ]\nthen\n echo \"empty (directory or file)\"\nelse\n echo \"contains files (or does not exist)\"\nfi\n</code></pre>\n\n<p>a variation using <code>-type d</code>:</p>\n\n<pre><code>if [ -n \"$(find your/dir -prune -empty -type d 2&gt;/dev/null)\" ]\nthen\n echo \"empty directory\"\nelse\n echo \"contains files (or does not exist or is not a directory)\"\nfi\n</code></pre>\n\n<p><strong>Explanation:</strong> </p>\n\n<ul>\n<li><code>find -prune</code> is similar than <code>find -maxdepth 0</code> using less characters</li>\n<li><code>find -empty</code> prints the empty directories and files</li>\n<li><code>find -type d</code> prints directories only</li>\n</ul>\n\n<p><strong>Note:</strong> You could also replace <code>[ -n \"$(find your/dir -prune -empty)\" ]</code> by just the shorten version below:</p>\n\n<pre><code>if [ `find your/dir -prune -empty 2&gt;/dev/null` ]\nthen\n echo \"empty (directory or file)\"\nelse\n echo \"contains files (or does not exist)\"\nfi\n</code></pre>\n\n<p>This last code works most of the cases but be aware that malicious paths could express a command...</p>\n" }, { "answer_id": 25085215, "author": "bishop", "author_id": 2908724, "author_profile": "https://Stackoverflow.com/users/2908724", "pm_score": 1, "selected": false, "text": "<p>I am surprised the <a href=\"http://mywiki.wooledge.org/BashFAQ/004\" rel=\"nofollow\">wooledge guide on empty directories</a> hasn't been mentioned. This guide, and all of wooledge really, is a must read for shell type questions.</p>\n\n<p>Of note from that page:</p>\n\n<blockquote>\n <p>Never try to parse ls output. Even ls -A solutions can break (e.g. on HP-UX, if you are root, ls -A does \n the exact opposite of what it does if you're not root -- and no, I can't make up something that \n incredibly stupid).</p>\n \n <p>In fact, one may wish to avoid the direct question altogether. Usually people want to know whether a\n directory is empty because they want to do something involving the files therein, etc. Look to the larger \n question. For example, one of these find-based examples may be an appropriate solution:</p>\n</blockquote>\n\n<pre><code> # Bourne\n find \"$somedir\" -type f -exec echo Found unexpected file {} \\;\n find \"$somedir\" -maxdepth 0 -empty -exec echo {} is empty. \\; # GNU/BSD\n find \"$somedir\" -type d -empty -exec cp /my/configfile {} \\; # GNU/BSD\n</code></pre>\n\n<blockquote>\n <p>Most commonly, all that's really needed is something like this:</p>\n</blockquote>\n\n<pre><code> # Bourne\n for f in ./*.mpg; do\n test -f \"$f\" || continue\n mympgviewer \"$f\"\n done\n</code></pre>\n\n<blockquote>\n <p>In other words, the person asking the question may have thought an explicit empty-directory test was \n needed to avoid an error message like mympgviewer: ./*.mpg: No such file or directory when in fact no \n such test is required.</p>\n</blockquote>\n" }, { "answer_id": 25146519, "author": "Jecht Tyre", "author_id": 3542839, "author_profile": "https://Stackoverflow.com/users/3542839", "pm_score": 0, "selected": false, "text": "<p>So far I haven't seen an answer that uses grep which I think would give a simpler answer (with not too many weird symbols!). Here is how I would\ncheck if any files exist in the directory using bourne shell:</p>\n\n<p>this returns the number of files in a directory:</p>\n\n<pre><code>ls -l &lt;directory&gt; | egrep -c \"^-\"\n</code></pre>\n\n<p>you can fill in the directory path in where directory is written. The first half of the pipe ensures that the first character of output is \"-\" for each file. egrep then counts the number of line that start with that\nsymbol using regular expressions. now all you have to do is store the number you obtain and compare it using backquotes like: </p>\n\n<pre><code> #!/bin/sh \n fileNum=`ls -l &lt;directory&gt; | egrep -c \"^-\"` \n if [ $fileNum == x ] \n then \n #do what you want to do\n fi\n</code></pre>\n\n<p>x is a variable of your choice.</p>\n" }, { "answer_id": 25818893, "author": "Alex", "author_id": 2498790, "author_profile": "https://Stackoverflow.com/users/2498790", "pm_score": 2, "selected": false, "text": "<pre><code>dir_is_empty() {\n [ \"${1##*/}\" = \"*\" ]\n}\n\nif dir_is_empty /some/dir/* ; then\n echo \"huzzah\"\nfi\n</code></pre>\n\n<p>Assume you don't have a file named <code>*</code> into <code>/any/dir/you/check</code>, it should work on <code>bash</code> <code>dash</code> <code>posh</code> <code>busybox sh</code> and <code>zsh</code> but (for zsh) require <code>unsetopt nomatch</code>.</p>\n\n<p>Performances should be comparable to any <code>ls</code> which use <code>*</code>(glob), I guess will be slow on directories with many nodes (my <code>/usr/bin</code> with 3000+ files went not that slow), will use at least memory enough to allocate all dirs/filenames (and more) as they are all passed (resolved) to the function as arguments, some shell probably have limits on number of arguments and/or length of arguments.</p>\n\n<p>A portable fast O(1) zero resources way to check if a directory is empty would be nice to have.</p>\n\n<p><strong>update</strong></p>\n\n<p>The version above doesn't account for hidden files/dirs, in case some more test is required, like the <code>is_empty</code> from <a href=\"http://www.etalabs.net/sh_tricks.html\" rel=\"nofollow\">Rich’s sh (POSIX shell) tricks</a>:</p>\n\n<pre><code>is_empty () (\ncd \"$1\"\nset -- .[!.]* ; test -f \"$1\" &amp;&amp; return 1\nset -- ..?* ; test -f \"$1\" &amp;&amp; return 1\nset -- * ; test -f \"$1\" &amp;&amp; return 1\nreturn 0 )\n</code></pre>\n\n<p>But, instead, I'm thinking about something like this:</p>\n\n<pre><code>dir_is_empty() {\n [ \"$(find \"$1\" -name \"?*\" | dd bs=$((${#1}+3)) count=1 2&gt;/dev/null)\" = \"$1\" ]\n}\n</code></pre>\n\n<p>Some concern about trailing slashes differences from the argument and the find output when the dir is empty, and trailing newlines (but this should be easy to handle), sadly on my <code>busybox</code> <code>sh</code> show what is probably a bug on the <code>find -&gt; dd</code> pipe with the output truncated randomically (if I used <code>cat</code> the output is always the same, seems to be <code>dd</code> with the argument <code>count</code>).</p>\n" }, { "answer_id": 28332702, "author": "jerzyjerzy", "author_id": 3459193, "author_profile": "https://Stackoverflow.com/users/3459193", "pm_score": -1, "selected": false, "text": "<p>Works well for me this (when dir exist):</p>\n\n<pre><code>some_dir=\"/some/dir with whitespace &amp; other characters/\"\nif find \"`echo \"$some_dir\"`\" -maxdepth 0 -empty | read v; then echo \"Empty dir\"; fi\n</code></pre>\n\n<p>With full check:</p>\n\n<pre><code>if [ -d \"$some_dir\" ]; then\n if find \"`echo \"$some_dir\"`\" -maxdepth 0 -empty | read v; then echo \"Empty dir\"; else \"Dir is NOT empty\" fi\nfi\n</code></pre>\n" }, { "answer_id": 29841389, "author": "Daishi", "author_id": 2003537, "author_profile": "https://Stackoverflow.com/users/2003537", "pm_score": 2, "selected": false, "text": "<p>This tells me if the directory is empty or if it's not, the number of files it contains.</p>\n\n<pre><code>directory=\"/some/dir\"\nnumber_of_files=$(ls -A $directory | wc -l)\n\nif [ \"$number_of_files\" == \"0\" ]; then\n echo \"directory $directory is empty\"\nelse\n echo \"directory $directory contains $number_of_files files\"\nfi\n</code></pre>\n" }, { "answer_id": 32603647, "author": "loockass", "author_id": 4450526, "author_profile": "https://Stackoverflow.com/users/4450526", "pm_score": 1, "selected": false, "text": "<p>Small variation of <a href=\"https://stackoverflow.com/a/91558/4450526\">Bruno's answer</a>:</p>\n\n<pre><code>files=$(ls -1 /some/dir| wc -l)\nif [ $files -gt 0 ] \nthen\n echo \"Contains files\"\nelse\n echo \"Empty\"\nfi\n</code></pre>\n\n<p>It works for me</p>\n" }, { "answer_id": 36041465, "author": "Laurent G", "author_id": 4693472, "author_profile": "https://Stackoverflow.com/users/4693472", "pm_score": 0, "selected": false, "text": "<p>Mixing prune things and last answers, I got to</p>\n\n<pre><code>find \"$some_dir\" -prune -empty -type d | read &amp;&amp; echo empty || echo \"not empty\"\n</code></pre>\n\n<p>that works for paths with spaces too</p>\n" }, { "answer_id": 36903410, "author": "Thomas Steinbach", "author_id": 1768273, "author_profile": "https://Stackoverflow.com/users/1768273", "pm_score": 0, "selected": false, "text": "<p>Simple answer with <em>bash</em>:</p>\n\n<pre><code>if [[ $(ls /some/dir/) ]]; then echo \"huzzah\"; fi;\n</code></pre>\n" }, { "answer_id": 37342326, "author": "fedorqui", "author_id": 1983854, "author_profile": "https://Stackoverflow.com/users/1983854", "pm_score": 0, "selected": false, "text": "<p>I would go for <code>find</code>:</p>\n\n<pre><code>if [ -z \"$(find $dir -maxdepth 1 -type f)\" ]; then\n echo \"$dir has NO files\"\nelse\n echo \"$dir has files\"\n</code></pre>\n\n<p>This checks the output of looking for just files in the directory, without going through the subdirectories. Then it checks the output using the <code>-z</code> option taken from <code>man test</code>:</p>\n\n<pre><code> -z STRING\n the length of STRING is zero\n</code></pre>\n\n<hr>\n\n<p>See some outcomes:</p>\n\n<pre><code>$ mkdir aaa\n$ dir=\"aaa\"\n</code></pre>\n\n<p>Empty dir:</p>\n\n<pre><code>$ [ -z \"$(find aaa/ -maxdepth 1 -type f)\" ] &amp;&amp; echo \"empty\"\nempty\n</code></pre>\n\n<p>Just dirs in it:</p>\n\n<pre><code>$ mkdir aaa/bbb\n$ [ -z \"$(find aaa/ -maxdepth 1 -type f)\" ] &amp;&amp; echo \"empty\"\nempty\n</code></pre>\n\n<p>A file in the directory:</p>\n\n<pre><code>$ touch aaa/myfile\n$ [ -z \"$(find aaa/ -maxdepth 1 -type f)\" ] &amp;&amp; echo \"empty\"\n$ rm aaa/myfile \n</code></pre>\n\n<p>A file in a subdirectory:</p>\n\n<pre><code>$ touch aaa/bbb/another_file\n$ [ -z \"$(find aaa/ -maxdepth 1 -type f)\" ] &amp;&amp; echo \"empty\"\nempty\n</code></pre>\n" }, { "answer_id": 42857176, "author": "igiannak", "author_id": 2538200, "author_profile": "https://Stackoverflow.com/users/2538200", "pm_score": -1, "selected": false, "text": "<p>Try with command find.\nSpecify the directory hardcoded or as argument.\nThen initiate find to search all files inside the directory.\nCheck if return of find is null.\nEcho the data of find</p>\n\n<pre><code>#!/bin/bash\n\n_DIR=\"/home/user/test/\"\n#_DIR=$1\n_FIND=$(find $_DIR -type f )\nif [ -n \"$_FIND\" ]\nthen\n echo -e \"$_DIR contains files or subdirs with files \\n\\n \"\n echo \"$_FIND\"\nelse\necho \"empty (or does not exist)\"\nfi\n</code></pre>\n" }, { "answer_id": 50751686, "author": "Zorawar", "author_id": 498730, "author_profile": "https://Stackoverflow.com/users/498730", "pm_score": 2, "selected": false, "text": "<h1>ZSH</h1>\n<p>I know the question was marked for bash; but, just for reference, for <strong>zsh</strong> users:</p>\n<h2>Test for non-empty directory</h2>\n<p>To check if <code>foo</code> is non-empty:</p>\n<pre><code>$ for i in foo(NF) ; do ... ; done\n</code></pre>\n<p>where, if <code>foo</code> is non-empty, the code in the <code>for</code> block will be executed.</p>\n<h2>Test for empty directory</h2>\n<p>To check if <code>foo</code> is empty:</p>\n<pre><code>$ for i in foo(N/^F) ; do ... ; done\n</code></pre>\n<p>where, if <code>foo</code> is empty, the code in the <code>for</code> block will be executed.</p>\n<h2>Notes</h2>\n<p>We did not need to quote the directory <code>foo</code> above, but we can do so if we need to:</p>\n<pre><code>$ for i in 'some directory!'(NF) ; do ... ; done\n</code></pre>\n<p>We can also test more than one object, even if it is not a directory:</p>\n<pre><code>$ mkdir X # empty directory\n$ touch f # regular file\n$ for i in X(N/^F) f(N/^F) ; do echo $i ; done # echo empty directories\nX\n</code></pre>\n<p>Anything that is not a directory will just be ignored.</p>\n<h2>Extras</h2>\n<p>Since we are globbing, we can use any glob (or brace expansion):</p>\n<pre><code>$ mkdir X X1 X2 Y Y1 Y2 Z\n$ touch Xf # create regular file\n$ touch X1/f # directory X1 is not empty\n$ touch Y1/.f # directory Y1 is not empty\n$ ls -F # list all objects\nX/ X1/ X2/ Xf Y/ Y1/ Y2/ Z/\n$ for i in {X,Y}*(N/^F); do printf &quot;$i &quot;; done; echo # print empty directories\nX X2 Y Y2\n</code></pre>\n<p>We can also examine objects that are placed in an array. With the directories as above, for example:</p>\n<pre><code>$ ls -F # list all objects\nX/ X1/ X2/ Xf Y/ Y1/ Y2/ Z/\n$ arr=(*) # place objects into array &quot;arr&quot;\n$ for i in ${^arr}(N/^F); do printf &quot;$i &quot;; done; echo\nX X2 Y Y2 Z\n</code></pre>\n<p>Thus, we can test objects that may already be set in an array parameter.</p>\n<p>Note that the code in the <code>for</code> block is, obviously, executed on every directory in turn. If this is not desirable then you can simply populate an array parameter and then operate on that parameter:</p>\n<pre><code>$ for i in *(NF) ; do full_directories+=($i) ; done\n$ do_something $full_directories\n</code></pre>\n<h1>Explanation</h1>\n<p>For zsh users there is the <code>(F)</code> glob qualifier (see <code>man zshexpn</code>), which matches &quot;full&quot; (non-empty) directories:</p>\n<pre><code>$ mkdir X Y\n$ touch Y/.f # Y is now not empty\n$ touch f # create a regular file\n$ ls -dF * # list everything in the current directory\nf X/ Y/\n$ ls -dF *(F) # will list only &quot;full&quot; directories\nY/\n</code></pre>\n<p>The qualifier <code>(F)</code> lists objects that match: is a directory AND is not empty. So, <code>(^F)</code> matches: not a directory OR is empty. Thus, <code>(^F)</code> alone would also list regular files, for example. Thus, as explained on the <code>zshexp</code> man page, we also need the <code>(/)</code> glob qualifier, which lists only directories:</p>\n<pre><code>$ mkdir X Y Z\n$ touch X/f Y/.f # directories X and Y now not empty\n$ for i in *(/^F) ; do echo $i ; done\nZ\n</code></pre>\n<p>Thus, to check if a given directory is empty, you can therefore run:</p>\n<pre><code>$ mkdir X\n$ for i in X(/^F) ; do echo $i ; done ; echo &quot;finished&quot;\nX\nfinished\n</code></pre>\n<p>and just to be sure that a non-empty directory would not be captured:</p>\n<pre><code>$ mkdir Y\n$ touch Y/.f\n$ for i in Y(/^F) ; do echo $i ; done ; echo &quot;finished&quot;\nzsh: no matches found: Y(/^F)\nfinished\n</code></pre>\n<p>Oops! Since <code>Y</code> is not empty, zsh finds no matches for <code>(/^F)</code> (&quot;directories that are empty&quot;) and thus spits out an error message saying that no matches for the glob were found. We therefore need to suppress these possible error messages with the <code>(N)</code> glob qualifier:</p>\n<pre><code>$ mkdir Y\n$ touch Y/.f\n$ for i in Y(N/^F) ; do echo $i ; done ; echo &quot;finished&quot;\nfinished\n</code></pre>\n<p>Thus, for empty directories we need the qualifier <code>(N/^F)</code>, which you can read as: &quot;don't warn me about failures, directories that are not full&quot;.</p>\n<p>Similarly, for non-empty directories we need the qualifier <code>(NF)</code>, which we can likewise read as: &quot;don't warn me about failures, full directories&quot;.</p>\n" }, { "answer_id": 51402122, "author": "chanaka777", "author_id": 1190837, "author_profile": "https://Stackoverflow.com/users/1190837", "pm_score": 1, "selected": false, "text": "<p>With some workaround I could find a simple way to find out whether there are files in a directory. This can extend with more with grep commands to check specifically .xml or .txt files etc. Ex : <code>ls /some/dir | grep xml | wc -l | grep -w \"0\"</code></p>\n\n<pre><code>#!/bin/bash\nif ([ $(ls /some/dir | wc -l | grep -w \"0\") ])\n then\n echo 'No files'\n else\n echo 'Found files'\nfi\n</code></pre>\n" }, { "answer_id": 57086669, "author": "ForDummies", "author_id": 1422472, "author_profile": "https://Stackoverflow.com/users/1422472", "pm_score": 2, "selected": false, "text": "<p>Taking a hint (or several) from olibre's answer, I like a Bash function:</p>\n\n<pre><code>function isEmptyDir {\n [ -d $1 -a -n \"$( find $1 -prune -empty 2&gt;/dev/null )\" ]\n}\n</code></pre>\n\n<p>Because while it creates one subshell, it's as close to an O(1) solution as I can imagine and giving it a name makes it readable. I can then write</p>\n\n<pre><code>if isEmptyDir somedir\nthen\n echo somedir is an empty directory\nelse\n echo somedir does not exist, is not a dir, is unreadable, or is not empty\nfi\n</code></pre>\n\n<p>As for O(1) there are outlier cases: if a large directory has had all or all but the last entry deleted, \"find\" may have to read the whole thing to determine whether it's empty. I believe that expected performance is O(1) but worst-case is linear in the directory size. I have not measured this.</p>\n" }, { "answer_id": 66515306, "author": "Phi", "author_id": 4423190, "author_profile": "https://Stackoverflow.com/users/4423190", "pm_score": 0, "selected": false, "text": "<p>In another thread <a href=\"https://stackoverflow.com/questions/6845525/how-to-test-if-a-directory-is-empty-with-find/66515079#66515079\">How to test if a directory is empty with find</a> i proposed this</p>\n<pre><code>[ &quot;$(cd $dir;echo *)&quot; = &quot;*&quot; ] &amp;&amp; echo empty || echo non-empty\n</code></pre>\n<p>With the rationale that, $dir do exist because the question is &quot;Checking from shell script if a directory contains files&quot;, and that * even on big dir is not that big, on my system /usr/bin/* is just 12Kb.</p>\n<p>Update: Thanx @hh skladby, the fixed one.</p>\n<pre><code>[ &quot;$(cd $dir;echo .* *)&quot; = &quot;. .. *&quot; ] &amp;&amp; echo empty || echo non-empty\n</code></pre>\n" }, { "answer_id": 67232142, "author": "Zenexer", "author_id": 1188377, "author_profile": "https://Stackoverflow.com/users/1188377", "pm_score": 1, "selected": false, "text": "<pre><code>if [[ -s somedir ]]; then\n echo &quot;Files present&quot;\nfi\n</code></pre>\n<p>In my testing with bash 5.0.17, <code>[[ -s somedir ]]</code> will return true if <code>somedir</code> has any children. The same is true of <code>[ -s somedir ]</code>. Note that this will also return true if there are hidden files or subdirectories. It may also be filesystem-dependent.</p>\n" }, { "answer_id": 69463817, "author": "hh skladby", "author_id": 15979256, "author_profile": "https://Stackoverflow.com/users/15979256", "pm_score": 0, "selected": false, "text": "<h2>Without <a href=\"http://mywiki.wooledge.org/ParsingLs\" rel=\"nofollow noreferrer\">calling utils like ls</a>, find, etc.:</h2>\n<p>POSIX safe, i.e. not dependent on your Bash / xyz shell / ls / etc. version:</p>\n<pre><code>dir=&quot;/some/dir&quot;\n[ &quot;$(echo $dir/*)x&quot; != &quot;$dir/*x&quot; ] || [ &quot;$(echo $dir/.[^.]*)x&quot; != &quot;$dir/.[^.]*x&quot; ] || echo &quot;empty dir&quot;\n</code></pre>\n<p>The idea:</p>\n<ul>\n<li><code>echo *</code> lists non-dot files</li>\n<li><code>echo .[^.]*</code> lists dot files except of &quot;.&quot; and &quot;..&quot;</li>\n<li>if <code>echo</code> finds no matches, it returns the search expression, i.e. here <code>*</code> or <code>.[^.]*</code> - <strong>which both are no real strings and have to be concatenated with e.g. a letter to coerce a string</strong></li>\n<li><code>||</code> alternates the possibilities in a <a href=\"https://en.wikipedia.org/wiki/Short-circuit_evaluation\" rel=\"nofollow noreferrer\">short circuit</a>: there is at least one non-dot file or dir OR at least one dot file or dir OR the directory is empty - on execution level: &quot;if first possibility fails, try next one, if this fails, try next one&quot;; here technically Bash &quot;tries to execute&quot; <code>echo &quot;empty dir&quot;</code>, put your action for empty dirs here (eg. exit).</li>\n</ul>\n<p>Checked with symlinks, yet to check with more exotic possible file types.</p>\n" }, { "answer_id": 72997050, "author": "Chris K", "author_id": 5128431, "author_profile": "https://Stackoverflow.com/users/5128431", "pm_score": 1, "selected": false, "text": "<p>It really feels like there should be an option to <code>test</code> for an empty directory.\nI'll leave that editorial comment as a suggestion to the maintainers of the test command, but the counterpart exists for empty files.</p>\n<p>In the trivial use case that brought me here, I'm not worried about looping through a huge number of files, nor am I worried about .files. I was hoping to find the aforementioned &quot;missing&quot; operand to <code>test</code>. C'est la guerre.</p>\n<p>In the example below directory empty is empty, and full has files.</p>\n<pre><code>$ for f in empty/*; do test -e $f; done\n$ echo $?\n1\n$ for f in full/*; do test -e $f; done\n$ echo $?\n0\n</code></pre>\n<p>Or, shorter and uglier still, but again only for relatively trivial use cases:</p>\n<pre><code>$ echo empty/*| grep \\*\n$ echo $?\n1\n\n$ echo full/* | grep \\*\n$ echo $?\n0\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91368", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17491/" ]
From a shell script, how do I check if a directory contains files? Something similar to this ```sh if [ -e /some/dir/* ]; then echo "huzzah"; fi; ``` but which works if the directory contains one or several files (the above one only works with exactly 0 or 1 files).
The solutions so far use `ls`. Here's an all bash solution: ``` #!/bin/bash shopt -s nullglob dotglob # To include hidden files files=(/some/dir/*) if [ ${#files[@]} -gt 0 ]; then echo "huzzah"; fi ```
91,420
<p>I have a static library written in C++ and I have a structure describing data format, i.e.<br></p> <pre><code>struct Format{ long fmtId; long dataChunkSize; long headerSize; Format(long, long, long); bool operator==(Format const &amp; other) const; }; </code></pre> <p>Some of data formats are widely used, like <code>{fmtId=0, dataChunkSize=128, headerSize=0}</code> and <code>{fmtId=0, dataChunkSize=256, headerSize=0}</code><br><br> Some data structure classes receive format in constructor. I'd like to have some sort of shortcuts for those widely used formats, like a couple of global <code>Format</code> members <code>gFmt128, gFmt256</code> that I can pass by reference. I instantiate them in a .cpp file like </p> <p><code>Format gFmt128(0, 128, 0);</code></p> <p>and in .h there is</p> <p><code>extern Format gFmt128;</code></p> <p>also, I declare <code>Format const &amp; Format::Fmt128(){return gFmt128;}</code> and try to use it in the main module.</p> <p>But if I try and do it in the main module that uses the lib, the linker complains about unresolved external <code>gFmt128</code>.</p> <p>How can I make my library 'export' those global vars, so I can use them from other modules?</p>
[ { "answer_id": 91433, "author": "yrp", "author_id": 7228, "author_profile": "https://Stackoverflow.com/users/7228", "pm_score": 2, "selected": false, "text": "<p>Are they defined in .cpp file as well? Roughly, it should look like:</p>\n\n<pre><code>struct Format\n{\n [...]\n static Format gFmt128;\n};\n// Format.cpp\nFormat Format::gFmt128 = { 0, 128, 0 }\n</code></pre>\n" }, { "answer_id": 91437, "author": "Seb Rose", "author_id": 12405, "author_profile": "https://Stackoverflow.com/users/12405", "pm_score": 2, "selected": false, "text": "<p>You need to declare your Format objects as <strong>extern</strong> not <strong>static</strong></p>\n" }, { "answer_id": 91456, "author": "Skizz", "author_id": 1898, "author_profile": "https://Stackoverflow.com/users/1898", "pm_score": 4, "selected": true, "text": "<p>Don't use the static keyword on global declarations. <a href=\"http://msdn.microsoft.com/en-us/library/s1sb61xd.aspx\" rel=\"nofollow noreferrer\">Here is an article explain the visibility of variables with/without static</a>. The static gives globals internal linkage, that is, only visible in the translation unit they are declared in.</p>\n" }, { "answer_id": 95357, "author": "xtofl", "author_id": 6610, "author_profile": "https://Stackoverflow.com/users/6610", "pm_score": 1, "selected": false, "text": "<p>Morhveus, I tried this out, too. <em>My</em> linker rather says it has the gFmt128 symbol already defined. This is indeed the behaviour I would expect: the compiler adds the function body to both the library and the client object since it's defined in the include file.</p>\n\n<p>The only way I get unresolved externals is by </p>\n\n<ul>\n<li>not adding the static library to the objects-to-be-linked</li>\n<li>not defining the symbol gFmt128 in the static library's source file</li>\n</ul>\n\n<p>I'm puzzled... How come we see something different? Can you explain what happens?</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91420", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17481/" ]
I have a static library written in C++ and I have a structure describing data format, i.e. ``` struct Format{ long fmtId; long dataChunkSize; long headerSize; Format(long, long, long); bool operator==(Format const & other) const; }; ``` Some of data formats are widely used, like `{fmtId=0, dataChunkSize=128, headerSize=0}` and `{fmtId=0, dataChunkSize=256, headerSize=0}` Some data structure classes receive format in constructor. I'd like to have some sort of shortcuts for those widely used formats, like a couple of global `Format` members `gFmt128, gFmt256` that I can pass by reference. I instantiate them in a .cpp file like `Format gFmt128(0, 128, 0);` and in .h there is `extern Format gFmt128;` also, I declare `Format const & Format::Fmt128(){return gFmt128;}` and try to use it in the main module. But if I try and do it in the main module that uses the lib, the linker complains about unresolved external `gFmt128`. How can I make my library 'export' those global vars, so I can use them from other modules?
Don't use the static keyword on global declarations. [Here is an article explain the visibility of variables with/without static](http://msdn.microsoft.com/en-us/library/s1sb61xd.aspx). The static gives globals internal linkage, that is, only visible in the translation unit they are declared in.
91,434
<p>I want to display an error message on my asp.net application. This message is a warning message, this is the way I did it:</p> <pre class="lang-js prettyprint-override"><code>CmdCalcInvoke.Attributes[&quot;onclick&quot;] = &quot;return confirm('Are you sure you want to calculate the certification? WARNING: If the quarter has not finished, all the partners status will change')&quot;; </code></pre> <p>The code above works fine. The <code>CmdCalcInvoke</code> is an <code>htmlInputButton</code>. This is the message that the message box displays;</p> <blockquote> <p><em>Are you sure you want to calculate the certification? WARNING: If the quarter has not finished, all the partners status will change</em></p> </blockquote> <p>What I want to do is to display this message, but wanted to highlight the WARNING word by making it bold, or displaying the word in red, can this be done???, can't remember seeing a message box with this characteristics, but I though i would ask in case</p> <p>Any suggestions will be welcome</p>
[ { "answer_id": 91461, "author": "redsquare", "author_id": 6440, "author_profile": "https://Stackoverflow.com/users/6440", "pm_score": 2, "selected": false, "text": "<p>you can if you dont use the default alert boxes. Try using a javascript modal window which is just normal div markup that you can control the styling of. Look at blockui for jquery (there are loads of others)</p>\n" }, { "answer_id": 91467, "author": "leppie", "author_id": 15541, "author_profile": "https://Stackoverflow.com/users/15541", "pm_score": 0, "selected": false, "text": "<p>You can try something like: <a href=\"http://weblogs.asp.net/johnkatsiotis/archive/2008/09/14/asp-net-messagebox-server-and-client.aspx\" rel=\"nofollow noreferrer\">http://weblogs.asp.net/johnkatsiotis/archive/2008/09/14/asp-net-messagebox-server-and-client.aspx</a></p>\n" }, { "answer_id": 91474, "author": "RB.", "author_id": 15393, "author_profile": "https://Stackoverflow.com/users/15393", "pm_score": 0, "selected": false, "text": "<p>The modal dialog control I use is :\n<a href=\"http://foohack.com/tests/vertical-align/dialog.html\" rel=\"nofollow noreferrer\">http://foohack.com/tests/vertical-align/dialog.html</a> \n<a href=\"http://foohack.com/2007/11/css-modal-dialog-that-works-right/\" rel=\"nofollow noreferrer\">http://foohack.com/2007/11/css-modal-dialog-that-works-right/</a></p>\n\n<p>I find it works well across all browsers. I've hacked it round to work well with ASP .NET, and that was pretty easy.</p>\n" }, { "answer_id": 91477, "author": "A Nony Mouse", "author_id": 7182, "author_profile": "https://Stackoverflow.com/users/7182", "pm_score": 0, "selected": false, "text": "<p>It isn't possible to apply formatting to a standard dialogue box. However if you <em>really</em> want to format it you could flash up the message in HTML either next to the button or as a absolutely placed div, which you could format with CSS.</p>\n" }, { "answer_id": 91519, "author": "Adhip Gupta", "author_id": 384, "author_profile": "https://Stackoverflow.com/users/384", "pm_score": 0, "selected": false, "text": "<p>Else, use something like a LightBox based solution like <a href=\"http://codylindley.com/Javascript/257/thickbox-one-box-to-rule-them-all\" rel=\"nofollow noreferrer\">Thickbox</a>?</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91434", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I want to display an error message on my asp.net application. This message is a warning message, this is the way I did it: ```js CmdCalcInvoke.Attributes["onclick"] = "return confirm('Are you sure you want to calculate the certification? WARNING: If the quarter has not finished, all the partners status will change')"; ``` The code above works fine. The `CmdCalcInvoke` is an `htmlInputButton`. This is the message that the message box displays; > > *Are you sure you want to calculate the certification? WARNING: If the quarter has not finished, all the partners status will change* > > > What I want to do is to display this message, but wanted to highlight the WARNING word by making it bold, or displaying the word in red, can this be done???, can't remember seeing a message box with this characteristics, but I though i would ask in case Any suggestions will be welcome
you can if you dont use the default alert boxes. Try using a javascript modal window which is just normal div markup that you can control the styling of. Look at blockui for jquery (there are loads of others)
91,479
<p>By default data extracted by the <code>GROUP BY</code> clause is ordered as ascending. How to change it to descending.</p>
[ { "answer_id": 91485, "author": "RB.", "author_id": 15393, "author_profile": "https://Stackoverflow.com/users/15393", "pm_score": 3, "selected": false, "text": "<p>Add <code>DESC</code> to the <code>GROUP BY</code> clause, e.g. :</p>\n\n<pre><code>GROUP BY myDate DESC\n</code></pre>\n" }, { "answer_id": 91491, "author": "Hank Gay", "author_id": 4203, "author_profile": "https://Stackoverflow.com/users/4203", "pm_score": 1, "selected": false, "text": "<p><code>ORDER BY foo DESC</code>?</p>\n" }, { "answer_id": 97096, "author": "Shinhan", "author_id": 18219, "author_profile": "https://Stackoverflow.com/users/18219", "pm_score": 3, "selected": false, "text": "<p>As the <a href=\"http://dev.mysql.com/doc/refman/5.0/en/order-by-optimization.html\" rel=\"noreferrer\" title=\"ORDER BY Optimization\">MySQL documentation</a> says, </p>\n\n<pre><code>SELECT * FROM foo GROUP BY bar\n</code></pre>\n\n<p>is equivalent to</p>\n\n<pre><code>SELECT * FROM foo GROUP BY bar ORDER BY bar\n</code></pre>\n\n<p>Default behaviour can not be changed, but you can use </p>\n\n<pre><code>SELECT * FROM foo GROUP BY bar ORDER BY bar DESC\n</code></pre>\n\n<p>without experiencing any speed penalties as the sorting will be performed on the grouped field anyway. \nBy the way, when sorting is not important you can get (small) speed-up by using ORDER BY NULL.</p>\n" }, { "answer_id": 3915087, "author": "Giancarlo Frison", "author_id": 473384, "author_profile": "https://Stackoverflow.com/users/473384", "pm_score": 4, "selected": false, "text": "<p>You should use the derived tables on your SQL. \nFor example if you want to pick up the most recent row for an specific activity you're attempt to use:</p>\n\n<pre><code>select * \nfrom activities \ngroup by id_customer \norder by creation_date\n</code></pre>\n\n<p>but it doesn't work. Try instead:</p>\n\n<pre><code>SELECT * \nFROM ( select * \n from activities \n order by creation_date desc ) sorted_list \nGROUP BY id_customer\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91479", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
By default data extracted by the `GROUP BY` clause is ordered as ascending. How to change it to descending.
You should use the derived tables on your SQL. For example if you want to pick up the most recent row for an specific activity you're attempt to use: ``` select * from activities group by id_customer order by creation_date ``` but it doesn't work. Try instead: ``` SELECT * FROM ( select * from activities order by creation_date desc ) sorted_list GROUP BY id_customer ```
91,480
<p>I would like to know where can I find the code which eclipse uses to display the forms in the plugin.xml file. In particular I am looking for the form layout used in the extension tab in the plugin.xml</p>
[ { "answer_id": 91485, "author": "RB.", "author_id": 15393, "author_profile": "https://Stackoverflow.com/users/15393", "pm_score": 3, "selected": false, "text": "<p>Add <code>DESC</code> to the <code>GROUP BY</code> clause, e.g. :</p>\n\n<pre><code>GROUP BY myDate DESC\n</code></pre>\n" }, { "answer_id": 91491, "author": "Hank Gay", "author_id": 4203, "author_profile": "https://Stackoverflow.com/users/4203", "pm_score": 1, "selected": false, "text": "<p><code>ORDER BY foo DESC</code>?</p>\n" }, { "answer_id": 97096, "author": "Shinhan", "author_id": 18219, "author_profile": "https://Stackoverflow.com/users/18219", "pm_score": 3, "selected": false, "text": "<p>As the <a href=\"http://dev.mysql.com/doc/refman/5.0/en/order-by-optimization.html\" rel=\"noreferrer\" title=\"ORDER BY Optimization\">MySQL documentation</a> says, </p>\n\n<pre><code>SELECT * FROM foo GROUP BY bar\n</code></pre>\n\n<p>is equivalent to</p>\n\n<pre><code>SELECT * FROM foo GROUP BY bar ORDER BY bar\n</code></pre>\n\n<p>Default behaviour can not be changed, but you can use </p>\n\n<pre><code>SELECT * FROM foo GROUP BY bar ORDER BY bar DESC\n</code></pre>\n\n<p>without experiencing any speed penalties as the sorting will be performed on the grouped field anyway. \nBy the way, when sorting is not important you can get (small) speed-up by using ORDER BY NULL.</p>\n" }, { "answer_id": 3915087, "author": "Giancarlo Frison", "author_id": 473384, "author_profile": "https://Stackoverflow.com/users/473384", "pm_score": 4, "selected": false, "text": "<p>You should use the derived tables on your SQL. \nFor example if you want to pick up the most recent row for an specific activity you're attempt to use:</p>\n\n<pre><code>select * \nfrom activities \ngroup by id_customer \norder by creation_date\n</code></pre>\n\n<p>but it doesn't work. Try instead:</p>\n\n<pre><code>SELECT * \nFROM ( select * \n from activities \n order by creation_date desc ) sorted_list \nGROUP BY id_customer\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91480", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17512/" ]
I would like to know where can I find the code which eclipse uses to display the forms in the plugin.xml file. In particular I am looking for the form layout used in the extension tab in the plugin.xml
You should use the derived tables on your SQL. For example if you want to pick up the most recent row for an specific activity you're attempt to use: ``` select * from activities group by id_customer order by creation_date ``` but it doesn't work. Try instead: ``` SELECT * FROM ( select * from activities order by creation_date desc ) sorted_list GROUP BY id_customer ```
91,487
<p>I keep running into this problem when debugging JSP pages in OpenNMS. The Jetty wiki talks about keepGenerated (<a href="http://docs.codehaus.org/display/JETTY/KeepGenerated" rel="nofollow noreferrer">http://docs.codehaus.org/display/JETTY/KeepGenerated</a>) in webdefault.xml but it seems unclear how this works in embedded setups.</p>
[ { "answer_id": 92213, "author": "Javaxpert", "author_id": 15241, "author_profile": "https://Stackoverflow.com/users/15241", "pm_score": 0, "selected": false, "text": "<p>It is dumped already.\nfor example if you have a file called <code>index.jsp</code>, a file will be created called <code>index_jsp.java</code>\nJust search for something like that in the work directory.</p>\n" }, { "answer_id": 92233, "author": "Roel Spilker", "author_id": 12634, "author_profile": "https://Stackoverflow.com/users/12634", "pm_score": 2, "selected": false, "text": "<p>If you are using Jetty 6 you can use the following code:</p>\n\n<pre><code>String webApp = \"./web/myapp\"; // Location of the jsp files\nString contextPath = \"/myapp\";\nWebAppContext webAppContext = new WebAppContext(webApp, contextPath); \nServletHandler servletHandler = webAppContext.getServletHandler();\nServletHolder holder = new ServletHolder(JspServlet.class);\nservletHandler.addServletWithMapping(holder, \"*.jsp\");\nholder.setInitOrder(0);\nholder.setInitParameter(\"compiler\", \"modern\");\nholder.setInitParameter(\"fork\", \"false\");\n\nFile dir = new File(\"./web/compiled/\" + webApp);\ndir.mkdirs();\nholder.setInitParameter(\"scratchdir\", dir.getAbsolutePath());\n</code></pre>\n" }, { "answer_id": 8297734, "author": "James B", "author_id": 217850, "author_profile": "https://Stackoverflow.com/users/217850", "pm_score": 2, "selected": false, "text": "<p>I know this is ages old, but I haven't found the answer anywhere else on the internet and it doesn't seem as though this has gotten any easier. Hopefully this will help someone:</p>\n\n<p>extract your webdefault.xml from the jetty-version.jar, mine was in :C:\\Documents and \nSettings\\JB.m2\\repository\\org\\mortbay\\jetty\\jetty\\6.1.22\\jetty-6.1.22.jar inside the org/mortbay/jetty/webapp/webdefault.xml file</p>\n\n<p>Put the webdefault.xml into my project directory</p>\n\n<p>Edit the webdefault.xml and add the following line:</p>\n\n<pre><code>&lt;servlet id=\"jsp\"&gt;\n ....\n &lt;init-param&gt;\n &lt;param-name&gt;keepgenerated&lt;/param-name&gt;\n &lt;param-value&gt;true&lt;/param-value&gt;\n &lt;/init-param&gt;\n</code></pre>\n\n<p>Add the following into your maven pom.xml config:</p>\n\n<pre><code>&lt;plugin&gt;\n &lt;groupId&gt;org.mortbay.jetty&lt;/groupId&gt;\n &lt;artifactId&gt;maven-jetty-plugin&lt;/artifactId&gt;\n &lt;configuration&gt; \n &lt;webDefaultXml&gt;webdefault.xml&lt;/webDefaultXml&gt;\n &lt;/configuration&gt;\n&lt;/plugin&gt;\n</code></pre>\n\n<p>When you run the <code>mvn jetty:run</code> maven goal my jsp code is now kept in target\\work\\jsp\\org\\apache\\jsp\\WEB_002dINF\\jsp</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91487", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17507/" ]
I keep running into this problem when debugging JSP pages in OpenNMS. The Jetty wiki talks about keepGenerated (<http://docs.codehaus.org/display/JETTY/KeepGenerated>) in webdefault.xml but it seems unclear how this works in embedded setups.
If you are using Jetty 6 you can use the following code: ``` String webApp = "./web/myapp"; // Location of the jsp files String contextPath = "/myapp"; WebAppContext webAppContext = new WebAppContext(webApp, contextPath); ServletHandler servletHandler = webAppContext.getServletHandler(); ServletHolder holder = new ServletHolder(JspServlet.class); servletHandler.addServletWithMapping(holder, "*.jsp"); holder.setInitOrder(0); holder.setInitParameter("compiler", "modern"); holder.setInitParameter("fork", "false"); File dir = new File("./web/compiled/" + webApp); dir.mkdirs(); holder.setInitParameter("scratchdir", dir.getAbsolutePath()); ```
91,511
<p>I have a memory buffer corresponding to my screen resolution (1280x800 at 24-bits-per-pixel) that contains my screen contents at 24bpp. I want to convert this to 8-bpp (ie. Halftone color palette in Windows). I currently do this: 1. Use CreateDIBSection to allocate a new 1280x800 24-bpp buffer and access it as a DC, as well as a plain memory buffer 2. Use memcpy to copy from my original buffer to this new buffer from step 1 3. Use BitBlt to let GDI perform the color conversion</p> <p>I want to avoid the extra memcpy of step 2. To do this, I can think of two approaches:</p> <p>a. Wrap my original mem buf in a DC to perform BitBlt directly from it</p> <p>b. Write my own 24-bpp to 8-bpp color conversion. I can't find any info on how Windows implements this halftone color conversion. Besides even if I find out, I won't be using the accelerated features of GDI that BitBlt has access to.</p> <p>So how do I do either (a) or (b)?</p> <p>thanks!</p>
[ { "answer_id": 91575, "author": "Ray Hayes", "author_id": 7093, "author_profile": "https://Stackoverflow.com/users/7093", "pm_score": 3, "selected": true, "text": "<p>OK, to address the two parts of the problem.</p>\n\n<ol>\n<li><p>the following code shows how to get at the pixels inside of a bitmap, change them and put them back into the bitmap. You could always generate a dummy bitmap of the correct size and format, open it up, copy over your data and you then have a bitmap object with your data:</p>\n\n<pre><code>private void LockUnlockBitsExample(PaintEventArgs e)\n{\n\n // Create a new bitmap.\n Bitmap bmp = new Bitmap(\"c:\\\\fakePhoto.jpg\");\n\n // Lock the bitmap's bits. \n Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);\n System.Drawing.Imaging.BitmapData bmpData =\n bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite,\n bmp.PixelFormat);\n\n // Get the address of the first line.\n IntPtr ptr = bmpData.Scan0;\n\n // Declare an array to hold the bytes of the bitmap.\n int bytes = bmpData.Stride * bmp.Height;\n byte[] rgbValues = new byte[bytes];\n\n // Copy the RGB values into the array.\n System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes);\n\n // Set every third value to 255. A 24bpp bitmap will look red. \n for (int counter = 2; counter &lt; rgbValues.Length; counter += 3)\n rgbValues[counter] = 255;\n\n // Copy the RGB values back to the bitmap\n System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, ptr, bytes);\n\n // Unlock the bits.\n bmp.UnlockBits(bmpData);\n\n // Draw the modified image.\n e.Graphics.DrawImage(bmp, 0, 150);\n}\n</code></pre></li>\n</ol>\n\n<p>To convert the contents to 8bpp you'll want to use the System.Drawing.Imaging.ColorMatrix class. I don't have at hand the correct matrix values for half-tone, but this example grayscales and adjustment of the values should give you an idea of the effect:</p>\n\n<pre><code>Graphics g = e.Graphics;\nBitmap bmp = new Bitmap(\"sample.jpg\");\ng.FillRectangle(Brushes.White, this.ClientRectangle);\n\n// Create a color matrix\n// The value 0.6 in row 4, column 4 specifies the alpha value\nfloat[][] matrixItems = {\n new float[] {1, 0, 0, 0, 0},\n new float[] {0, 1, 0, 0, 0},\n new float[] {0, 0, 1, 0, 0},\n new float[] {0, 0, 0, 0.6f, 0}, \n new float[] {0, 0, 0, 0, 1}};\nColorMatrix colorMatrix = new ColorMatrix(matrixItems);\n\n// Create an ImageAttributes object and set its color matrix\nImageAttributes imageAtt = new ImageAttributes();\nimageAtt.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);\n\n// Now draw the semitransparent bitmap image.\ng.DrawImage(bmp, this.ClientRectangle, 0.0f, 0.0f, bmp.Width, bmp.Height, \n GraphicsUnit.Pixel, imageAtt);\n\nimageAtt.Dispose();\n</code></pre>\n\n<p>I shall try and update later with the matrix values for half-tone, it's likely to be lots 0.5 or 0.333 values in there!</p>\n" }, { "answer_id": 92480, "author": "Mike Dimmick", "author_id": 6970, "author_profile": "https://Stackoverflow.com/users/6970", "pm_score": 1, "selected": false, "text": "<p>Use CreateDIBitmap rather than CreateDIBSection.</p>\n" }, { "answer_id": 95227, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>If you want to eliminate the copy (step 2), just use CreateDIBSection to create your original memory buffer in the first place. Then you can just create a compatible DC for that bitmap and use it as the source for the BitBlt operation.</p>\n\n<p>I.e. there is no need to copy the memory from a \"plain memory\" buffer to a CreateDIBSection bitmap prior to blitting if you use a CreateDIBSection bitmap instead of a \"plain memory\" buffer in the first place.</p>\n\n<p>After all, a buffer allocated using CreateDIBSection is essentially just a \"plain memory\" buffer that is compatible with CreateCompatibleDC, which is what you are looking for.</p>\n" }, { "answer_id": 198061, "author": "Chris Becke", "author_id": 27491, "author_profile": "https://Stackoverflow.com/users/27491", "pm_score": 0, "selected": false, "text": "<p>How did you get the screen contents into this 24bpp memory buffer in the first place?</p>\n\n<p>The obvious route to avoiding a needless memcpy is to subvert the original screengrab by creating the 24bpp DIBSection first, and passing it to the screengrab function as the destination buffer.</p>\n\n<p>If thats not possible, you can still try and coerce GDI into doing the hard lifting by creating a BITMAPINFOHEADER describing the format of the memory buffer, and just call StretchDIBits to blit it onto your 8bpp DIBSection.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17465/" ]
I have a memory buffer corresponding to my screen resolution (1280x800 at 24-bits-per-pixel) that contains my screen contents at 24bpp. I want to convert this to 8-bpp (ie. Halftone color palette in Windows). I currently do this: 1. Use CreateDIBSection to allocate a new 1280x800 24-bpp buffer and access it as a DC, as well as a plain memory buffer 2. Use memcpy to copy from my original buffer to this new buffer from step 1 3. Use BitBlt to let GDI perform the color conversion I want to avoid the extra memcpy of step 2. To do this, I can think of two approaches: a. Wrap my original mem buf in a DC to perform BitBlt directly from it b. Write my own 24-bpp to 8-bpp color conversion. I can't find any info on how Windows implements this halftone color conversion. Besides even if I find out, I won't be using the accelerated features of GDI that BitBlt has access to. So how do I do either (a) or (b)? thanks!
OK, to address the two parts of the problem. 1. the following code shows how to get at the pixels inside of a bitmap, change them and put them back into the bitmap. You could always generate a dummy bitmap of the correct size and format, open it up, copy over your data and you then have a bitmap object with your data: ``` private void LockUnlockBitsExample(PaintEventArgs e) { // Create a new bitmap. Bitmap bmp = new Bitmap("c:\\fakePhoto.jpg"); // Lock the bitmap's bits. Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height); System.Drawing.Imaging.BitmapData bmpData = bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, bmp.PixelFormat); // Get the address of the first line. IntPtr ptr = bmpData.Scan0; // Declare an array to hold the bytes of the bitmap. int bytes = bmpData.Stride * bmp.Height; byte[] rgbValues = new byte[bytes]; // Copy the RGB values into the array. System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes); // Set every third value to 255. A 24bpp bitmap will look red. for (int counter = 2; counter < rgbValues.Length; counter += 3) rgbValues[counter] = 255; // Copy the RGB values back to the bitmap System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, ptr, bytes); // Unlock the bits. bmp.UnlockBits(bmpData); // Draw the modified image. e.Graphics.DrawImage(bmp, 0, 150); } ``` To convert the contents to 8bpp you'll want to use the System.Drawing.Imaging.ColorMatrix class. I don't have at hand the correct matrix values for half-tone, but this example grayscales and adjustment of the values should give you an idea of the effect: ``` Graphics g = e.Graphics; Bitmap bmp = new Bitmap("sample.jpg"); g.FillRectangle(Brushes.White, this.ClientRectangle); // Create a color matrix // The value 0.6 in row 4, column 4 specifies the alpha value float[][] matrixItems = { new float[] {1, 0, 0, 0, 0}, new float[] {0, 1, 0, 0, 0}, new float[] {0, 0, 1, 0, 0}, new float[] {0, 0, 0, 0.6f, 0}, new float[] {0, 0, 0, 0, 1}}; ColorMatrix colorMatrix = new ColorMatrix(matrixItems); // Create an ImageAttributes object and set its color matrix ImageAttributes imageAtt = new ImageAttributes(); imageAtt.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap); // Now draw the semitransparent bitmap image. g.DrawImage(bmp, this.ClientRectangle, 0.0f, 0.0f, bmp.Width, bmp.Height, GraphicsUnit.Pixel, imageAtt); imageAtt.Dispose(); ``` I shall try and update later with the matrix values for half-tone, it's likely to be lots 0.5 or 0.333 values in there!
91,518
<p>Suppose I have a simple XHTML document that uses a custom namespace for attributes:</p> <pre><code>&lt;html xmlns="..." xmlns:custom="http://www.example.com/ns"&gt; ... &lt;div class="foo" custom:attr="bla"/&gt; ... &lt;/html&gt; </code></pre> <p>How do I match each element that has a certain custom attribute using jQuery? Using</p> <pre><code>$("div[custom:attr]") </code></pre> <p>does not work. (Tried with Firefox only, so far.)</p>
[ { "answer_id": 91607, "author": "redsquare", "author_id": 6440, "author_profile": "https://Stackoverflow.com/users/6440", "pm_score": 2, "selected": false, "text": "<p>You should use <code>$('div').attr('custom:attr')</code>.</p>\n" }, { "answer_id": 91807, "author": "Devon", "author_id": 13850, "author_profile": "https://Stackoverflow.com/users/13850", "pm_score": 6, "selected": true, "text": "<p><a href=\"https://jquery.com/\" rel=\"nofollow noreferrer\">jQuery</a> does not support custom namespaces directly, but you can find the divs you are looking for by using filter function.</p>\n\n<pre><code>// find all divs that have custom:attr\n$('div').filter(function() { return $(this).attr('custom:attr'); }).each(function() {\n // matched a div with custom::attr\n $(this).html('I was found.');\n});\n</code></pre>\n" }, { "answer_id": 2184474, "author": "Fyrd", "author_id": 193099, "author_profile": "https://Stackoverflow.com/users/193099", "pm_score": 4, "selected": false, "text": "<p>This works in some conditions:</p>\n\n<p><code>$(\"div[custom\\\\:attr]\")</code></p>\n\n<p>However, for a more advanced method, see <a href=\"http://www.rfk.id.au/blog/entry/xmlns-selectors-jquery\" rel=\"noreferrer\">this XML Namespace jQuery plug-in</a></p>\n" }, { "answer_id": 2927811, "author": "Suphi Basdemir", "author_id": 352737, "author_profile": "https://Stackoverflow.com/users/352737", "pm_score": 3, "selected": false, "text": "<p>the syntax for matching by attribute is:</p>\n\n<p><code>$(\"div[customattr=bla]\")</code> matches <code>div customattr=\"bla\"</code></p>\n\n<p><code>$(\"[customattr]\")</code> matches all tags with the attribute <code>\"customattr\"</code></p>\n\n<p>with namespace attributes like <code>'custom:attr'</code> its not working</p>\n\n<p><a href=\"http://www.pamaya.com/jquery-selectors-and-attribute-selectors-reference-and-examples/\" rel=\"nofollow noreferrer\">Here</a> you can find a good overview.</p>\n" }, { "answer_id": 10015279, "author": "Katie Kilian", "author_id": 645511, "author_profile": "https://Stackoverflow.com/users/645511", "pm_score": 2, "selected": false, "text": "<p>Here is an implementation of a custom selector that works for me.</p>\n\n<pre><code>// Custom jQuery selector to select on custom namespaced attributes\n$.expr[':'].nsAttr = function(obj, index, meta, stack) {\n\n // if the parameter isn't a string, the selector is invalid, \n // so always return false.\n if ( typeof meta[3] != 'string' )\n return false;\n\n // if the parameter doesn't have an '=' character in it, \n // assume it is an attribute name with no value, \n // and match all elements that have only that attribute name.\n if ( meta[3].indexOf('=') == -1 )\n {\n var val = $(obj).attr(meta[3]);\n return (typeof val !== 'undefined' &amp;&amp; val !== false);\n }\n // if the parameter does contain an '=' character, \n // we should only match elements that have an attribute \n // with a matching name and value.\n else\n {\n // split the parameter into name/value pairs\n var arr = meta[3].split('=', 2);\n var attrName = arr[0];\n var attrValue = arr[1];\n\n // if the current object has an attribute matching the specified \n // name &amp; value, include it in our selection.\n return ( $(obj).attr(attrName) == attrValue );\n }\n};\n</code></pre>\n\n<p>Example usage:</p>\n\n<pre><code>// Show all divs where the custom attribute matches both name and value.\n$('div:nsAttr(MyNameSpace:customAttr=someValue)').show();\n\n// Show all divs that have the custom attribute, regardless of its value.\n$('div:nsAttr(MyNameSpace:customAttr)').show();\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91518", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7779/" ]
Suppose I have a simple XHTML document that uses a custom namespace for attributes: ``` <html xmlns="..." xmlns:custom="http://www.example.com/ns"> ... <div class="foo" custom:attr="bla"/> ... </html> ``` How do I match each element that has a certain custom attribute using jQuery? Using ``` $("div[custom:attr]") ``` does not work. (Tried with Firefox only, so far.)
[jQuery](https://jquery.com/) does not support custom namespaces directly, but you can find the divs you are looking for by using filter function. ``` // find all divs that have custom:attr $('div').filter(function() { return $(this).attr('custom:attr'); }).each(function() { // matched a div with custom::attr $(this).html('I was found.'); }); ```
91,563
<p>How can I make this work?</p> <pre><code>switch(property.PropertyType){ case typeof(Boolean): //doStuff break; case typeof(String): //doOtherStuff break; default: break; } </code></pre> <p>I don't want to use the name since string comparing for types is just awfull and can be subject to change.</p>
[ { "answer_id": 91590, "author": "Phil Wright", "author_id": 6276, "author_profile": "https://Stackoverflow.com/users/6276", "pm_score": 0, "selected": false, "text": "<p>Do not worry about using strings within a switch because if you have several the compiler will automatically convert it into a hash lookup giving decent performance despite it looking pretty aweful. </p>\n\n<p>The problem of type strings changing can be solved by making it into an explicit hash lookup yourself and populating the constents of the hash in a static constructor. That way the hash is populate with the correct strings at runtime so they remain correct.</p>\n" }, { "answer_id": 91591, "author": "Sam Meldrum", "author_id": 16005, "author_profile": "https://Stackoverflow.com/users/16005", "pm_score": 0, "selected": false, "text": "<p>You can't do this with switch in c# as the case has to be constant.</p>\n\n<p>What is wrong with:</p>\n\n<pre><code>if(property.PropertyType == typeof(bool)) {\n //dostuff;\n}\nelse if (property.PropertyType == typeof(string)) {\n //do other stuff;\n}\n</code></pre>\n" }, { "answer_id": 91594, "author": "user17527", "author_id": 17527, "author_profile": "https://Stackoverflow.com/users/17527", "pm_score": -1, "selected": false, "text": "<p>Just use the normal if/else if/else pattern:</p>\n\n<pre><code>if (property.PropertyType == typeof(Boolean))\n{\n} \nelse if (property.PropertyType == typeof(String))\n{\n}\nelse if (...)\n{\n}\n</code></pre>\n" }, { "answer_id": 91597, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 7, "selected": true, "text": "<pre><code> System.Type propertyType = typeof(Boolean);\n System.TypeCode typeCode = Type.GetTypeCode(propertyType);\n switch (typeCode)\n {\n case TypeCode.Boolean:\n //doStuff\n break;\n case TypeCode.String:\n //doOtherStuff\n break;\n default: break;\n }\n</code></pre>\n\n<p>You can use an hybrid approach for TypeCode.Object where you dynamic if with typeof. This is very fast because for the first part - the switch - the compiler can decide based on a lookup table.</p>\n" }, { "answer_id": 91609, "author": "Paul van Brenk", "author_id": 1837197, "author_profile": "https://Stackoverflow.com/users/1837197", "pm_score": 2, "selected": false, "text": "<p>You can't. What you can do is create a mapping between Types and a delegate using a dictionary:</p>\n\n<pre><code>var TypeMapping = new Dictionary&lt;Type, Action&lt;string&gt;&gt;(){\n {typeof(string), (x)=&gt;Console.WriteLine(\"string\")},\n {typeof(bool), (x)=&gt;Console.WriteLine(\"bool\")}\n};\n\n\n\nstring s = \"my string\";\n\nTypeMapping[s.GetType()](\"foo\");\nTypeMapping[true.GetType()](\"true\");\n</code></pre>\n" }, { "answer_id": 91614, "author": "xan", "author_id": 15667, "author_profile": "https://Stackoverflow.com/users/15667", "pm_score": 0, "selected": false, "text": "<p>I recently had to do something similar and using switch wasn't an option. Doing an == on the typeof(x) is fine, but a more elegant way might be to do something like this:</p>\n\n<pre><code>if(property.PropertyType is bool){\n //dostuff;\n}\nelse if (property.PropertyType is string){\n //do other stuff;\n}\n</code></pre>\n\n<p>But, I'm not certain that you can use the \"is\" keyword in this way, I think it only works for objects... </p>\n" }, { "answer_id": 91615, "author": "Josh", "author_id": 11702, "author_profile": "https://Stackoverflow.com/users/11702", "pm_score": 2, "selected": false, "text": "<p>I think what you are looking for here is a good Map. Using delegates and a Generic IDictionary you can do what you want.</p>\n\n<p>Try something like this:</p>\n\n<pre><code>private delegate object MyDelegate();\n\nprivate IDictionary&lt;Type, MyDelegate&gt; functionMap = new IDictionary&lt;Type, MyDelegate&gt;();\n\npublic Init()\n{\n functionMap.Add(typeof(String), someFunction);\n functionMap.Add(tyepof(Boolean), someOtherFunction);\n}\n\npublic T doStuff&lt;T&gt;(Type someType)\n{\n return (T)functionMap[someType]();\n}\n</code></pre>\n" }, { "answer_id": 91711, "author": "timvw", "author_id": 15267, "author_profile": "https://Stackoverflow.com/users/15267", "pm_score": -1, "selected": false, "text": "<p>I personally prefer the <code>Dictionary&lt;Type, other&gt;</code> approach the most... I can even provide you another example: <a href=\"http://www.timvw.be/presenting-namevaluecollectionhelper/\" rel=\"nofollow noreferrer\">http://www.timvw.be/presenting-namevaluecollectionhelper/</a></p>\n\n<p>In case you insist on writing a switch-case statement you could use the Type name...</p>\n\n<pre><code>switch (blah.PropertyType.FullName)\n{\n case typeof(int).FullName: break;\n case typeof(string).FullName: break;\n}\n</code></pre>\n" }, { "answer_id": 91786, "author": "Boris Callens", "author_id": 11333, "author_profile": "https://Stackoverflow.com/users/11333", "pm_score": 0, "selected": false, "text": "<p>About the stringmatching: it was one of the reqs in the question to not do it through stringmatching.</p>\n\n<p>The dictionary is an approach I will use when I put this entire serialization algorithm in its own library.\nAs for now I will first try the typeCode as my case only uses basic types.\nIf that doesn't work I will go back to the swarm of if/elses :S</p>\n\n<p>Before ppl ask me why I want my own serialization:\n1) .net xml serialization doesn't serialize properties without setters\n2) serialization has to comply to some legacy rules</p>\n" }, { "answer_id": 41089461, "author": "Krzysztof Branicki", "author_id": 5297231, "author_profile": "https://Stackoverflow.com/users/5297231", "pm_score": 2, "selected": false, "text": "<p>C# 7.0 will support switch on types as a part of bigger pattern matching feature.\nThis example is taken from <a href=\"https://blogs.msdn.microsoft.com/dotnet/2016/08/24/whats-new-in-csharp-7-0/\" rel=\"nofollow noreferrer\">.NET blog post</a> that announces new features:</p>\n\n<pre><code>switch(shape)\n{\n case Circle c:\n WriteLine($\"circle with radius {c.Radius}\");\n break;\n case Rectangle s when (s.Length == s.Height):\n WriteLine($\"{s.Length} x {s.Height} square\");\n break;\n case Rectangle r:\n WriteLine($\"{r.Length} x {r.Height} rectangle\");\n break;\n default:\n WriteLine(\"&lt;unknown shape&gt;\");\n break;\n case null:\n throw new ArgumentNullException(nameof(shape));\n}\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11333/" ]
How can I make this work? ``` switch(property.PropertyType){ case typeof(Boolean): //doStuff break; case typeof(String): //doOtherStuff break; default: break; } ``` I don't want to use the name since string comparing for types is just awfull and can be subject to change.
``` System.Type propertyType = typeof(Boolean); System.TypeCode typeCode = Type.GetTypeCode(propertyType); switch (typeCode) { case TypeCode.Boolean: //doStuff break; case TypeCode.String: //doOtherStuff break; default: break; } ``` You can use an hybrid approach for TypeCode.Object where you dynamic if with typeof. This is very fast because for the first part - the switch - the compiler can decide based on a lookup table.
91,576
<p>I'm building a project using a GNU tool chain and everything works fine until I get to linking it, where the linker complains that it is missing/can't find <code>crti.o</code>. This is not one of my object files, it seems to be related to libc but I can't understand why it would need this <code>crti.o</code>, wouldn't it use a library file, e.g. <code>libc.a</code>?</p> <p>I'm cross compiling for the arm platform. I have the file in the toolchain, but how do I get the linker to include it? </p> <p><code>crti.o</code> is on one of the 'libraries' search path, but should it look for <code>.o</code> file on the library path? </p> <p>Is the search path the same for <code>gcc</code> and <code>ld</code>?</p>
[ { "answer_id": 91595, "author": "stsquad", "author_id": 17507, "author_profile": "https://Stackoverflow.com/users/17507", "pm_score": 6, "selected": true, "text": "<p><code>crti.o</code> is the bootstrap library, generally quite small. It's usually statically linked into your binary. It should be found in <code>/usr/lib</code>.</p>\n\n<p>If you're running a binary distribution they tend to put all the developer stuff into -dev packages (e.g. libc6-dev) as it's not needed to run compiled programs, just to build them.</p>\n\n<p>You're not cross-compiling are you? </p>\n\n<p>If you're cross-compiling it's usually a problem with gcc's search path not matching where your crti.o is. It should have been built when the toolchain was. The first thing to check is <code>gcc -print-search-dirs</code> and see if crti.o is in any of those paths.</p>\n\n<p>The linking is actually done by ld but it has its paths passed down to it by gcc. Probably the quickest way to find out what's going on is compile a helloworld.c program and strace it to see what is getting passed to ld and see what's going on.</p>\n\n<pre><code>strace -v -o log -f -e trace=open,fork,execve gcc hello.c -o test\n</code></pre>\n\n<p>Open the log file and search for crti.o, as you can see my non-cross compiler:</p>\n\n<pre><code>10616 execve(\"/usr/bin/ld\", [\"/usr/bin/ld\", \"--eh-frame-hdr\", \"-m\", \"elf_x86_64\", \"--hash-style=both\", \"-dynamic-linker\", \"/lib64/ld-linux-x86-64.so.2\", \"-o\"\n, \"test\", \"/usr/lib/gcc/x86_64-linux-gnu/4.\"..., \"/usr/lib/gcc/x86_64-linux-gnu/4.\"..., \"/usr/lib/gcc/x86_64-linux-gnu/4.\"..., \"-L/usr/lib/gcc/x86_64-linux-g\nnu/\"..., \"-L/usr/lib/gcc/x86_64-linux-gnu/\"..., \"-L/usr/lib/gcc/x86_64-linux-gnu/\"..., \"-L/lib/../lib\", \"-L/usr/lib/../lib\", \"-L/usr/lib/gcc/x86_64-linux-gnu\n/\"..., \"/tmp/cc4rFJWD.o\", \"-lgcc\", \"--as-needed\", \"-lgcc_s\", \"--no-as-needed\", \"-lc\", \"-lgcc\", \"--as-needed\", \"-lgcc_s\", \"--no-as-needed\", \"/usr/lib/gcc/x86_\n64-linux-gnu/4.\"..., \"/usr/lib/gcc/x86_64-linux-gnu/4.\"...], \"COLLECT_GCC=gcc\", \"COLLECT_GCC_OPTIONS=\\'-o\\' \\'test\\' \"..., \"COMPILER_PATH=/usr/lib/gcc/x86_6\"..., \"LIBRARY_PATH=/usr/lib/gcc/x86_64\"..., \"CO\nLLECT_NO_DEMANGLE=\"]) = 0\n10616 open(\"/etc/ld.so.cache\", O_RDONLY) = 3\n10616 open(\"/usr/lib/libbfd-2.18.0.20080103.so\", O_RDONLY) = 3\n10616 open(\"/lib/libc.so.6\", O_RDONLY) = 3\n10616 open(\"test\", O_RDWR|O_CREAT|O_TRUNC, 0666) = 3\n10616 open(\"/usr/lib/gcc/x86_64-linux-gnu/4.2.3/../../../../lib/crt1.o\", O_RDONLY) = 4\n10616 open(\"/usr/lib/gcc/x86_64-linux-gnu/4.2.3/../../../../lib/crti.o\", O_RDONLY) = 5\n10616 open(\"/usr/lib/gcc/x86_64-linux-gnu/4.2.3/crtbegin.o\", O_RDONLY) = 6\n10616 open(\"/tmp/cc4rFJWD.o\", O_RDONLY) = 7\n</code></pre>\n\n<p>If you see a bunch of attempts to <code>open(...crti.o) = -1 ENOENT</code>, <code>ld</code> is getting confused and you want to see where the path it's opening came from...</p>\n" }, { "answer_id": 91596, "author": "leppie", "author_id": 15541, "author_profile": "https://Stackoverflow.com/users/15541", "pm_score": 0, "selected": false, "text": "<p>I get the same kind of issue on a default Ubuntu 8.04 install. I had to get the libc developer headers/files manually for it to work.</p>\n" }, { "answer_id": 93166, "author": "Richard", "author_id": 76121, "author_profile": "https://Stackoverflow.com/users/76121", "pm_score": 1, "selected": false, "text": "<p>OK I had to reinstall the tool chain, so that the missing files were then included. It seems strange since it should have found it on the gcc path. The main problem I guess was that I had 15 or so different crti.o files on my computer and wasn't point to the correct one. Still doesn't make since but it works now :-) Thanks for your help :-)</p>\n" }, { "answer_id": 7837638, "author": "Rob Fisher", "author_id": 991411, "author_profile": "https://Stackoverflow.com/users/991411", "pm_score": 1, "selected": false, "text": "<p>I had a similar problem with a badly set-up cross-compiler. I got around it like so:</p>\n\n<pre><code>/home/rob/compiler/usr/bin/arm-linux-gcc --sysroot=/home/rob/compiler hello.c\n</code></pre>\n\n<p>This assumes /lib, /usr/include and so on exist in the location pointed to by the sysroot option. This is probably not how things are supposed to be done, but it got me out of trouble when I needed to compile a simple C file.</p>\n" }, { "answer_id": 25900752, "author": "FractalSpace", "author_id": 175169, "author_profile": "https://Stackoverflow.com/users/175169", "pm_score": 0, "selected": false, "text": "<p>This solved for me (cross compiling pjsip for ARM):</p>\n\n<pre><code>export LDFLAGS='--sysroot=/home/me/&lt;path-to-my-sysroot-parent&gt;/sysroot'\n</code></pre>\n" }, { "answer_id": 30117539, "author": "chris", "author_id": 469276, "author_profile": "https://Stackoverflow.com/users/469276", "pm_score": 3, "selected": false, "text": "<p>I had the same issue while cross-compiling. crti.o was in <strong>&lt;sysroot&gt;/usr/lib64</strong> but the linker would not find it.</p>\n\n<p>Turns out that creating an empty directory <strong>&lt;sysroot&gt;/usr/lib</strong> fixed the issue. It seems that the linker would search for a path <strong>&lt;sysroot&gt;/usr/lib</strong> first, and only if it exists it would even consider <strong>&lt;sysroot&gt;/usr/lib64</strong>.</p>\n\n<p>Is this a bug in the linker? Or is this behaviour documented somewhere?</p>\n" }, { "answer_id": 40129998, "author": "Eugen Konkov", "author_id": 4632019, "author_profile": "https://Stackoverflow.com/users/4632019", "pm_score": 3, "selected": false, "text": "<p>In my case <code>Linux Mint 18.0/Ubuntu 16.04</code>, I have no <code>crti.o</code> at all:</p>\n\n<pre><code>$ find /usr/ -name crti*\n</code></pre>\n\n<p>I find nothing so I install developer package:</p>\n\n<pre><code>sudo apt-get install libc6-dev\n</code></pre>\n\n<p>If you find some libs <a href=\"https://stackoverflow.com/a/16605434/4632019\">read here</a></p>\n" }, { "answer_id": 59244724, "author": "Surajit Sinha", "author_id": 5521476, "author_profile": "https://Stackoverflow.com/users/5521476", "pm_score": 1, "selected": false, "text": "<p>If you are cross-compiling , add sysroot option in LDFLAGS</p>\n\n<pre><code>export LDFLAGS=\"\"--sysroot=${SDKTARGETSYSROOT}\" -L${SDKTARGETSYSROOT}/lib -L${SDKTARGETSYSROOT}/usr/lib -L${SDKTARGETSYSROOT}/usr/lib/arm-poky-linux-gnueabi/5.3.0\"\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91576", "https://Stackoverflow.com", "https://Stackoverflow.com/users/76121/" ]
I'm building a project using a GNU tool chain and everything works fine until I get to linking it, where the linker complains that it is missing/can't find `crti.o`. This is not one of my object files, it seems to be related to libc but I can't understand why it would need this `crti.o`, wouldn't it use a library file, e.g. `libc.a`? I'm cross compiling for the arm platform. I have the file in the toolchain, but how do I get the linker to include it? `crti.o` is on one of the 'libraries' search path, but should it look for `.o` file on the library path? Is the search path the same for `gcc` and `ld`?
`crti.o` is the bootstrap library, generally quite small. It's usually statically linked into your binary. It should be found in `/usr/lib`. If you're running a binary distribution they tend to put all the developer stuff into -dev packages (e.g. libc6-dev) as it's not needed to run compiled programs, just to build them. You're not cross-compiling are you? If you're cross-compiling it's usually a problem with gcc's search path not matching where your crti.o is. It should have been built when the toolchain was. The first thing to check is `gcc -print-search-dirs` and see if crti.o is in any of those paths. The linking is actually done by ld but it has its paths passed down to it by gcc. Probably the quickest way to find out what's going on is compile a helloworld.c program and strace it to see what is getting passed to ld and see what's going on. ``` strace -v -o log -f -e trace=open,fork,execve gcc hello.c -o test ``` Open the log file and search for crti.o, as you can see my non-cross compiler: ``` 10616 execve("/usr/bin/ld", ["/usr/bin/ld", "--eh-frame-hdr", "-m", "elf_x86_64", "--hash-style=both", "-dynamic-linker", "/lib64/ld-linux-x86-64.so.2", "-o" , "test", "/usr/lib/gcc/x86_64-linux-gnu/4."..., "/usr/lib/gcc/x86_64-linux-gnu/4."..., "/usr/lib/gcc/x86_64-linux-gnu/4."..., "-L/usr/lib/gcc/x86_64-linux-g nu/"..., "-L/usr/lib/gcc/x86_64-linux-gnu/"..., "-L/usr/lib/gcc/x86_64-linux-gnu/"..., "-L/lib/../lib", "-L/usr/lib/../lib", "-L/usr/lib/gcc/x86_64-linux-gnu /"..., "/tmp/cc4rFJWD.o", "-lgcc", "--as-needed", "-lgcc_s", "--no-as-needed", "-lc", "-lgcc", "--as-needed", "-lgcc_s", "--no-as-needed", "/usr/lib/gcc/x86_ 64-linux-gnu/4."..., "/usr/lib/gcc/x86_64-linux-gnu/4."...], "COLLECT_GCC=gcc", "COLLECT_GCC_OPTIONS=\'-o\' \'test\' "..., "COMPILER_PATH=/usr/lib/gcc/x86_6"..., "LIBRARY_PATH=/usr/lib/gcc/x86_64"..., "CO LLECT_NO_DEMANGLE="]) = 0 10616 open("/etc/ld.so.cache", O_RDONLY) = 3 10616 open("/usr/lib/libbfd-2.18.0.20080103.so", O_RDONLY) = 3 10616 open("/lib/libc.so.6", O_RDONLY) = 3 10616 open("test", O_RDWR|O_CREAT|O_TRUNC, 0666) = 3 10616 open("/usr/lib/gcc/x86_64-linux-gnu/4.2.3/../../../../lib/crt1.o", O_RDONLY) = 4 10616 open("/usr/lib/gcc/x86_64-linux-gnu/4.2.3/../../../../lib/crti.o", O_RDONLY) = 5 10616 open("/usr/lib/gcc/x86_64-linux-gnu/4.2.3/crtbegin.o", O_RDONLY) = 6 10616 open("/tmp/cc4rFJWD.o", O_RDONLY) = 7 ``` If you see a bunch of attempts to `open(...crti.o) = -1 ENOENT`, `ld` is getting confused and you want to see where the path it's opening came from...
91,617
<p>I am looking for a tool that can take a unit test, like </p> <pre><code>IPerson p = new Person(); p.Name = "Sklivvz"; Assert.AreEqual("Sklivvz", p.Name); </code></pre> <p>and generate, automatically, the corresponding stub class and interface</p> <pre><code>interface IPerson // inferred from IPerson p = new Person(); { string Name { get; // inferred from Assert.AreEqual("Sklivvz", p.Name); set; // inferred from p.Name = "Sklivvz"; } } class Person: IPerson // inferred from IPerson p = new Person(); { private string name; // inferred from p.Name = "Sklivvz"; public string Name // inferred from p.Name = "Sklivvz"; { get { return name; // inferred from Assert.AreEqual("Sklivvz", p.Name); } set { name = value; // inferred from p.Name = "Sklivvz"; } } public Person() // inferred from IPerson p = new Person(); { } } </code></pre> <p>I know ReSharper and Visual Studio do some of these, but I need a complete tool -- command line or whatnot -- that automatically infers what needs to be done. If there is no such tool, how would you write it (e.g. extending ReSharper, from scratch, using which libraries)?</p>
[ { "answer_id": 91665, "author": "Carlos Villela", "author_id": 16944, "author_profile": "https://Stackoverflow.com/users/16944", "pm_score": -1, "selected": false, "text": "<p>I find that whenever I need a code generation tool like this, I am probably writing code that could be made a little bit more generic so I only need to write it once. In your example, those getters and setters don't seem to be adding any value to the code - in fact, it is really just asserting that the getter/setter mechanism in C# works.</p>\n\n<p>I would refrain from writing (or even using) such a tool before understanding what the motivations for writing these kinds of tests are.</p>\n\n<p>BTW, you might want to have a look at <a href=\"http://code.google.com/p/nbehave/\" rel=\"nofollow noreferrer\">NBehave</a>?</p>\n" }, { "answer_id": 91682, "author": "FryHard", "author_id": 231, "author_profile": "https://Stackoverflow.com/users/231", "pm_score": 1, "selected": false, "text": "<p>If you plan to write your own implementation I would definately suggest that you take a look at the <a href=\"http://www.castleproject.org/others/nvelocity/index.html\" rel=\"nofollow noreferrer\">NVelocity</a> (C#) or <a href=\"http://velocity.apache.org/engine/index.html\" rel=\"nofollow noreferrer\">Velocity</a> (Java) template engines.</p>\n\n<p>I have used these in a code generator before and have found that they make the job a whole lot easier.</p>\n" }, { "answer_id": 91693, "author": "Hibri", "author_id": 15946, "author_profile": "https://Stackoverflow.com/users/15946", "pm_score": -1, "selected": false, "text": "<p>I use Rhino Mocks for this, when I just need a simple stub.</p>\n\n<p><a href=\"http://www.ayende.com/wiki/Rhino+Mocks+-+Stubs.ashx\" rel=\"nofollow noreferrer\">http://www.ayende.com/wiki/Rhino+Mocks+-+Stubs.ashx</a></p>\n" }, { "answer_id": 93321, "author": "Jay Bazuzi", "author_id": 5314, "author_profile": "https://Stackoverflow.com/users/5314", "pm_score": -1, "selected": false, "text": "<p>Visual Studio ships with some features that can be helpful for you here:</p>\n\n<p><strong>Generate Method Stub</strong>. When you write a call to a method that doesn't exist, you'll get a little smart tag on the method name, which you can use to generate a method stub based on the parameters you're passing.</p>\n\n<p>If you're a keyboard person (I am), then right after typing the close parenthesis, you can do:</p>\n\n<ul>\n<li><strong>Ctrl-.</strong> (to open the smart tag)</li>\n<li><strong>ENTER</strong> (to generate the stub)</li>\n<li><strong>F12</strong> (go to definition, to take you to the new method)</li>\n</ul>\n\n<p>The smart tag only appears if the IDE thinks there isn't a method that matches. If you want to generate when the smart tag isn't up, you can go to <strong>Edit->Intellisense->Generate Method Stub</strong>.</p>\n\n<p><strong>Snippets</strong>. Small code templates that makes it easy to generate bits of common code. Some are simple (try \"if[TAB][TAB]\"). Some are complex ('switch' will generate cases for an enum). You can also write your own. For your case, try \"class\" and \"prop\".</p>\n\n<p>See also \"<a href=\"https://stackoverflow.com/questions/46003/how-to-change-generate-method-stub-to-throw-notimplementedexception-in-vs\">How to change “Generate Method Stub” to throw NotImplementedException in VS?</a>\" for information snippets in the context of GMS.</p>\n\n<p><strong>autoprops</strong>. Remember that properties can be much simpler:</p>\n\n<pre><code>public string Name { get; set; }\n</code></pre>\n\n<p><strong>create class</strong>. In Solution Explorer, RClick on the project name or a subfolder, select <strong>Add->Class</strong>. Type the name of your new class. Hit <strong>ENTER</strong>. You'll get a class declaration in the right namespace, etc.</p>\n\n<p><strong>Implement interface</strong>. When you want a class to implement an interface, write the interface name part, activate the smart tag, and select either option to generate stubs for the interface members.</p>\n\n<p>These aren't quite the 100% automated solution you're looking for, but I think it's a good mitigation.</p>\n" }, { "answer_id": 107796, "author": "adriaanp", "author_id": 12230, "author_profile": "https://Stackoverflow.com/users/12230", "pm_score": 0, "selected": false, "text": "<p>I like CodeRush from DevExpress. They have a huge customizable templating engine. And the best for me their is no Dialog boxes. They also have functionality to create methods and interfaces and classes from interface that does not exist.</p>\n" }, { "answer_id": 143329, "author": "mattlant", "author_id": 14642, "author_profile": "https://Stackoverflow.com/users/14642", "pm_score": 2, "selected": false, "text": "<p>Its amazing how no one really gave anything towards what you were asking.</p>\n\n<p>I dont know the answer, but I will give my thoughts on it.</p>\n\n<p>If I were to attempt to write something like this myself I would probably see about a resharper plugin. The reason I say that is because as you stated, resharper can do it, but in individual steps. So I would write something that went line by line and applied the appropriate resharper creation methods chained together.</p>\n\n<p>Now by no means do I even know how to do this, as I have never built anything for resharper, but that is what I would try to do. It makes logical sense that it could be done.</p>\n\n<p>And if you do write up some code, PLEASE post it, as I could find that usefull as well, being able to generate the entire skeleton in one step. Very useful.</p>\n" }, { "answer_id": 420499, "author": "Dmitri Nesteruk", "author_id": 9476, "author_profile": "https://Stackoverflow.com/users/9476", "pm_score": 1, "selected": false, "text": "<p>It's doable - at least in theory. What I would do is use something like <a href=\"http://www.codeplex.com/csparser\" rel=\"nofollow noreferrer\">csparser</a> to parse the unit test (you cannot compile it, unfortunately) and then take it from there. The only problem I can see is that what you are doing is wrong in terms of methodology - it makes more sense to generate unit tests from entity classes (indeed, Visual Studio does precisely this) than doing it the other way around.</p>\n" }, { "answer_id": 1316124, "author": "vijaysylvester", "author_id": 146383, "author_profile": "https://Stackoverflow.com/users/146383", "pm_score": 0, "selected": false, "text": "<p>Try looking at the Pex , A microsoft project on unit testing , which is still under research</p>\n\n<p>research.microsoft.com/en-us/projects/Pex/ </p>\n" }, { "answer_id": 9969981, "author": "Ira Baxter", "author_id": 120163, "author_profile": "https://Stackoverflow.com/users/120163", "pm_score": 3, "selected": true, "text": "<p>What you appear to need is a parser for your language (Java), and a name and type resolver. (\"Symbol table builder\"). </p>\n\n<p>After parsing the source text, a compiler usually has a name resolver, that tries to record the definition of names and their corresponding types, and a type checker, that verifies that each expression has a valid type.</p>\n\n<p>Normally the name/type resolver complains when it can't find a definition. What you want it to do is to find the \"undefined\" thing that is causing the problem, and infer a type for it.</p>\n\n<p>For</p>\n\n<pre><code> IPerson p = new Person();\n</code></pre>\n\n<p>the name resolver knows that \"Person\" and \"IPerson\" aren't defined. If it were</p>\n\n<pre><code> Foo p = new Bar();\n</code></pre>\n\n<p>there would be no clue that you wanted an interface, just that Foo is some kind of abstract parent of Bar (e.g., a class or an interface). So the decision as which is it must be known to the tool (\"whenever you find such a construct, assume Foo is an interface ...\"). You could use a heuristic: IFoo and Foo means IFoo should be an interface, and somewhere somebody has to define Foo as a class realizing that interface. Once the\ntool has made this decision, it would need to update its symbol tables so that it can\nmove on to other statements:</p>\n\n<p>For</p>\n\n<pre><code> p.Name = \"Sklivvz\";\n</code></pre>\n\n<p>given that p must be an Interface (by the previous inference), then Name must be a field member, and it appears its type is String from the assignment.</p>\n\n<p>With that, the statement:</p>\n\n<pre><code> Assert.AreEqual(\"Sklivvz\", p.Name);\n</code></pre>\n\n<p>names and types resolve without further issue. </p>\n\n<p>The content of the IFoo and Foo entities is sort of up to you; you didn't have to use get and set but that's personal taste.</p>\n\n<p>This won't work so well when you have multiple entities in the same statement:</p>\n\n<pre><code> x = p.a + p.b ;\n</code></pre>\n\n<p>We know a and b are likely fields, but you can't guess what numeric type if indeed they are numeric, or if they are strings (this is legal for strings in Java, dunno about C#).\nFor C++ you don't even know what \"+\" means; it might be an operator on the Bar class.\nSo what you have to do is collect <em>constraints</em>, e.g., \"a is some indefinite number or string\", etc. and as the tool collects evidence, it narrows the set of possible constraints. (This works like those word problems: \"Joe has seven sons. Jeff is taller than Sam. Harry can't hide behind Sam. ... who is Jeff's twin?\" where you have to collect the evidence and remove the impossibilities). You also have to worry about the case where you end up with a contradiction.</p>\n\n<p>You could rule out p.a+p.b case, but then you can't write your unit tests with impunity. There are standard constraint solvers out there if you want impunity. (What a concept).</p>\n\n<p>OK, we have the ideas, now, can this be done in a practical way?</p>\n\n<p>The first part of this requires a parser and a bendable name and type resolver. You need a constraint solver or at least a \"defined value flows to undefined value\" operation (trivial constraint solver). </p>\n\n<p>Our <a href=\"http://www.semanticdesigns.com/Products/DMS/DMSToolkit.html\" rel=\"nofollow\">DMS Software Reengineering Toolkit</a> with its <a href=\"http://www.semanticdesigns.com/Products/FrontEnds/JavaFrontEnd.html\" rel=\"nofollow\">Java Front End</a> could probably do this. DMS is a tool builder's tool, for people that want to build tools that process computer langauges in arbitrary ways. (Think of \"computing with program fragments rather than numbers\").</p>\n\n<p>DMS provides general purpose parsing machinery, and can build an tree for whatever front end it is given (e.g., Java, and there's a C# front end).\nThe reason I chose Java is that our Java front end has all that name and type resolution machinery, and it is provided in source form so it can be bent. If you stuck to the trivial constraint solver, you could probably bend the Java name resolver to figure out the types. DMS will let you assemble trees that correspond to code fragments, and coalesce them into larger ones; as your tool collected facts for the symbol table, it could build the primitive trees. </p>\n\n<p>Somewhere, you have to decide you are done. How many unit tests the tool have to see\nbefore it knows the entire interface? (I guess it eats all the ones you provide?).\nOnce complete, it assembles the fragments for the various members and build an AST for an interface; DMS can use its prettyprinter to convert that AST back into source code like you've shown.</p>\n\n<p>I suggest Java here because our Java front end has name and type resolution. Our C# front end does not. This is a \"mere\" matter of ambition; somebody has to write one, but that's quite a lot of work (at least it was for Java and I can't imagine C# is really different).</p>\n\n<p>But the idea works fine in principle using DMS. </p>\n\n<p>You could do this with some other infrastructure that gave you access to a parser and an a bendable name and type resolver. That might not be so easy to get for C#; I suspect MS may give you a parser, and access to name and type resolution, but not any way to change that. Maybe Mono is the answer? </p>\n\n<p>You still need a was to generate code fragments and assemble them. You might try to do this by string hacking; my (long) experience with gluing program bits together is that if you do it with strings you eventually make a mess of it. You really want pieces that represent code fragments of known type, that can only be combined in ways the grammar allows; DMS does that thus no mess.</p>\n" }, { "answer_id": 10061673, "author": "Jaco", "author_id": 1230841, "author_profile": "https://Stackoverflow.com/users/1230841", "pm_score": 0, "selected": false, "text": "<p>I think what you are looking for is a fuzzing tool kit (https://en.wikipedia.org/wiki/Fuzz_testing). </p>\n\n<p>Al tough I never used, you might give Randoop.NET a chance to generate 'unit tests' <a href=\"http://randoop.codeplex.com/\" rel=\"nofollow\">http://randoop.codeplex.com/</a></p>\n" }, { "answer_id": 10064880, "author": "Jordão", "author_id": 31158, "author_profile": "https://Stackoverflow.com/users/31158", "pm_score": 1, "selected": false, "text": "<p>I think a real solution to this problem would be a very specialized parser. Since that's not so easy to do, I have a cheaper idea. Unfortunately, you'd have to change the way you write your tests (namely, just the creation of the object):</p>\n\n<pre><code>dynamic p = someFactory.Create(\"MyNamespace.Person\");\np.Name = \"Sklivvz\";\nAssert.AreEqual(\"Sklivvz\", p.Name);\n</code></pre>\n\n<p>A factory object would be used. If it can find the named object, it will create it and return it (this is the normal test execution). If it doesn't find it, it will create a recording proxy (a <a href=\"http://msdn.microsoft.com/en-us/library/system.dynamic.dynamicobject.aspx\" rel=\"nofollow\"><code>DynamicObject</code></a>) that will record all calls and at the end (maybe on tear down) could emit class files (maybe based on some templates) that reflect what it \"saw\" being called.</p>\n\n<p>Some disadvantages that I see:</p>\n\n<ul>\n<li>Need to run the code in \"two\" modes, which is annoying.</li>\n<li>In order for the proxy to \"see\" and record calls, they must be executed; so code in a <code>catch</code> block, for example, has to run.</li>\n<li>You have to change the way you create your object under test.</li>\n<li>You have to use <code>dynamic</code>; you'll lose compile-time safety in subsequent runs and it has a performance hit.</li>\n</ul>\n\n<p>The only advantage that I see is that it's <em>a lot cheaper</em> to create than a specialized parser.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7028/" ]
I am looking for a tool that can take a unit test, like ``` IPerson p = new Person(); p.Name = "Sklivvz"; Assert.AreEqual("Sklivvz", p.Name); ``` and generate, automatically, the corresponding stub class and interface ``` interface IPerson // inferred from IPerson p = new Person(); { string Name { get; // inferred from Assert.AreEqual("Sklivvz", p.Name); set; // inferred from p.Name = "Sklivvz"; } } class Person: IPerson // inferred from IPerson p = new Person(); { private string name; // inferred from p.Name = "Sklivvz"; public string Name // inferred from p.Name = "Sklivvz"; { get { return name; // inferred from Assert.AreEqual("Sklivvz", p.Name); } set { name = value; // inferred from p.Name = "Sklivvz"; } } public Person() // inferred from IPerson p = new Person(); { } } ``` I know ReSharper and Visual Studio do some of these, but I need a complete tool -- command line or whatnot -- that automatically infers what needs to be done. If there is no such tool, how would you write it (e.g. extending ReSharper, from scratch, using which libraries)?
What you appear to need is a parser for your language (Java), and a name and type resolver. ("Symbol table builder"). After parsing the source text, a compiler usually has a name resolver, that tries to record the definition of names and their corresponding types, and a type checker, that verifies that each expression has a valid type. Normally the name/type resolver complains when it can't find a definition. What you want it to do is to find the "undefined" thing that is causing the problem, and infer a type for it. For ``` IPerson p = new Person(); ``` the name resolver knows that "Person" and "IPerson" aren't defined. If it were ``` Foo p = new Bar(); ``` there would be no clue that you wanted an interface, just that Foo is some kind of abstract parent of Bar (e.g., a class or an interface). So the decision as which is it must be known to the tool ("whenever you find such a construct, assume Foo is an interface ..."). You could use a heuristic: IFoo and Foo means IFoo should be an interface, and somewhere somebody has to define Foo as a class realizing that interface. Once the tool has made this decision, it would need to update its symbol tables so that it can move on to other statements: For ``` p.Name = "Sklivvz"; ``` given that p must be an Interface (by the previous inference), then Name must be a field member, and it appears its type is String from the assignment. With that, the statement: ``` Assert.AreEqual("Sklivvz", p.Name); ``` names and types resolve without further issue. The content of the IFoo and Foo entities is sort of up to you; you didn't have to use get and set but that's personal taste. This won't work so well when you have multiple entities in the same statement: ``` x = p.a + p.b ; ``` We know a and b are likely fields, but you can't guess what numeric type if indeed they are numeric, or if they are strings (this is legal for strings in Java, dunno about C#). For C++ you don't even know what "+" means; it might be an operator on the Bar class. So what you have to do is collect *constraints*, e.g., "a is some indefinite number or string", etc. and as the tool collects evidence, it narrows the set of possible constraints. (This works like those word problems: "Joe has seven sons. Jeff is taller than Sam. Harry can't hide behind Sam. ... who is Jeff's twin?" where you have to collect the evidence and remove the impossibilities). You also have to worry about the case where you end up with a contradiction. You could rule out p.a+p.b case, but then you can't write your unit tests with impunity. There are standard constraint solvers out there if you want impunity. (What a concept). OK, we have the ideas, now, can this be done in a practical way? The first part of this requires a parser and a bendable name and type resolver. You need a constraint solver or at least a "defined value flows to undefined value" operation (trivial constraint solver). Our [DMS Software Reengineering Toolkit](http://www.semanticdesigns.com/Products/DMS/DMSToolkit.html) with its [Java Front End](http://www.semanticdesigns.com/Products/FrontEnds/JavaFrontEnd.html) could probably do this. DMS is a tool builder's tool, for people that want to build tools that process computer langauges in arbitrary ways. (Think of "computing with program fragments rather than numbers"). DMS provides general purpose parsing machinery, and can build an tree for whatever front end it is given (e.g., Java, and there's a C# front end). The reason I chose Java is that our Java front end has all that name and type resolution machinery, and it is provided in source form so it can be bent. If you stuck to the trivial constraint solver, you could probably bend the Java name resolver to figure out the types. DMS will let you assemble trees that correspond to code fragments, and coalesce them into larger ones; as your tool collected facts for the symbol table, it could build the primitive trees. Somewhere, you have to decide you are done. How many unit tests the tool have to see before it knows the entire interface? (I guess it eats all the ones you provide?). Once complete, it assembles the fragments for the various members and build an AST for an interface; DMS can use its prettyprinter to convert that AST back into source code like you've shown. I suggest Java here because our Java front end has name and type resolution. Our C# front end does not. This is a "mere" matter of ambition; somebody has to write one, but that's quite a lot of work (at least it was for Java and I can't imagine C# is really different). But the idea works fine in principle using DMS. You could do this with some other infrastructure that gave you access to a parser and an a bendable name and type resolver. That might not be so easy to get for C#; I suspect MS may give you a parser, and access to name and type resolution, but not any way to change that. Maybe Mono is the answer? You still need a was to generate code fragments and assemble them. You might try to do this by string hacking; my (long) experience with gluing program bits together is that if you do it with strings you eventually make a mess of it. You really want pieces that represent code fragments of known type, that can only be combined in ways the grammar allows; DMS does that thus no mess.
91,628
<p>I would like to automatically increment a field named `incrementID' anytime any field in any row within the table named 'tb_users' is updated. Currently I am doing it via the sql update statement. i.e "UPDATE tb_users SET name = @name, incrementID = incrementID + 1 .....WHERE id = @id;</p> <p>I'm wondering how I can do this automatically. for example, by changing the way sql server treats the field - kind of like the increment setting of 'Identity'. Before I update a row, I wish to check whether the incrementID of the object to be updated is different to the incrementID of the row of the db.</p>
[ { "answer_id": 91684, "author": "Galwegian", "author_id": 3201, "author_profile": "https://Stackoverflow.com/users/3201", "pm_score": 2, "selected": false, "text": "<p>You could use a trigger for this (if I've read you correctly and you want the value incremented each time you update the row).</p>\n" }, { "answer_id": 91685, "author": "Robbo", "author_id": 2418, "author_profile": "https://Stackoverflow.com/users/2418", "pm_score": 2, "selected": false, "text": "<p>Columns in the Table can have an <strong>Identity Specification</strong> set. Simply expand the node in the property window and fill in the details (Is Identity, Increment, Seed).</p>\n\n<p>The <strong>IDENTITYCOL</strong> keyword can be used for operations on Identity Specifications.</p>\n" }, { "answer_id": 92442, "author": "Mike Dimmick", "author_id": 6970, "author_profile": "https://Stackoverflow.com/users/6970", "pm_score": 2, "selected": false, "text": "<p>If you just need to know that it changed, rather than specifically that this is a later version or how many changes there have been, consider using a <code>rowversion</code> column.</p>\n" }, { "answer_id": 92505, "author": "TrevorD", "author_id": 12492, "author_profile": "https://Stackoverflow.com/users/12492", "pm_score": 3, "selected": true, "text": "<p>This trigger should do the trick:</p>\n\n<pre><code>create trigger update_increment for update as\nif not update(incrementID) \n UPDATE tb_users SET incrementID = incrementID + 1 \n from inserted WHERE tb_users.id = inserted.id\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17510/" ]
I would like to automatically increment a field named `incrementID' anytime any field in any row within the table named 'tb\_users' is updated. Currently I am doing it via the sql update statement. i.e "UPDATE tb\_users SET name = @name, incrementID = incrementID + 1 .....WHERE id = @id; I'm wondering how I can do this automatically. for example, by changing the way sql server treats the field - kind of like the increment setting of 'Identity'. Before I update a row, I wish to check whether the incrementID of the object to be updated is different to the incrementID of the row of the db.
This trigger should do the trick: ``` create trigger update_increment for update as if not update(incrementID) UPDATE tb_users SET incrementID = incrementID + 1 from inserted WHERE tb_users.id = inserted.id ```
91,629
<p>I'm trying to match elements with a name that is <code>'container1$container2$chkChecked'</code>, using a regex of <code>'.+\$chkChecked'</code>, but I'm not getting the matches I expect when the element name is as described. What am I doing wrong?</p>
[ { "answer_id": 91647, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 2, "selected": false, "text": "<p>try</p>\n\n<pre><code>string.match( /[$]chkChecked$/ ) \n</code></pre>\n\n<p>alternatively, you could try </p>\n\n<pre><code>string.match( /[^a-zA-Z0-9]chkChecked/ ) \n</code></pre>\n\n<p>( Also, make sure your using <code>//</code> around your regex, otherwise you might be matching using string literals. Not obvious tho without a larger code snippet )</p>\n" }, { "answer_id": 91648, "author": "brien", "author_id": 4219, "author_profile": "https://Stackoverflow.com/users/4219", "pm_score": 0, "selected": false, "text": "<p>It looks like it should work.</p>\n\n<p>There's a good <a href=\"http://www.regular-expressions.info/javascriptexample.html\" rel=\"nofollow noreferrer\">Javascript Regex Tester</a> that also says it matches.</p>\n" }, { "answer_id": 91724, "author": "Steven Noble", "author_id": 10393, "author_profile": "https://Stackoverflow.com/users/10393", "pm_score": 3, "selected": true, "text": "<p>my guess, by your use of quotes, is you did something like</p>\n\n<pre><code>re = new RegExp('.+\\$chkChecked');\n</code></pre>\n\n<p>which won't work because js takes advantage of the \\ in its string interpretation as an escape so it never makes it into the regex interpreter</p>\n\n<p>instead you want</p>\n\n<pre><code>re = new RegExp('.+\\\\$chkChecked');\n</code></pre>\n" }, { "answer_id": 91789, "author": "ProfK", "author_id": 8741, "author_profile": "https://Stackoverflow.com/users/8741", "pm_score": 0, "selected": false, "text": "<blockquote>\n<blockquote>\n<p>Steven Noble:</p>\n</blockquote>\n<p>which won't work because js takes advantage of the \\ in its string interpretation as an escape so it never makes it into the regex interpreter</p>\n</blockquote>\n<p>I intended to use \\ as an escape because I'm really looking for a $ in the element name.</p>\n" }, { "answer_id": 91811, "author": "moonshadow", "author_id": 11834, "author_profile": "https://Stackoverflow.com/users/11834", "pm_score": 2, "selected": false, "text": "<p>There's two levels of escaping: one when your code is first parsed (e.g. in case you want to include a <code>'</code> inside the string), and the second in the regexp engine. So you need two <code>\\s</code> before the <code>$</code> to make the regexp engine not treat it as a special character.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91629", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8741/" ]
I'm trying to match elements with a name that is `'container1$container2$chkChecked'`, using a regex of `'.+\$chkChecked'`, but I'm not getting the matches I expect when the element name is as described. What am I doing wrong?
my guess, by your use of quotes, is you did something like ``` re = new RegExp('.+\$chkChecked'); ``` which won't work because js takes advantage of the \ in its string interpretation as an escape so it never makes it into the regex interpreter instead you want ``` re = new RegExp('.+\\$chkChecked'); ```
91,635
<p>I am considering using Postsharp framework to ease the burden of application method logging. It basically allows me to adorn methods with logging attribute and at compile time injects the logging code needed into the il. I like this solution as it keeps the noise out of the deign time code environment. Any thoughts, experiences or better alternatives?</p>
[ { "answer_id": 91659, "author": "Chris Canal", "author_id": 5802, "author_profile": "https://Stackoverflow.com/users/5802", "pm_score": 4, "selected": true, "text": "<p>I apply logging with AOP using Castle Windsor DynamicProxies. I was already using Castle for it's IoC container, so using it for AOP was the path of least resistence for me. If you want more info let me know, I'm in the process of tidying the code up for releasing it as a blog post</p>\n\n<p>Edit</p>\n\n<p>Ok, here's the basic Intercepter code, faily basic but it does everything I need. There are two intercepters, one logs everyhing and the other allows you to define method names to allow for more fine grained logging. This solution is faily dependant on Castle Windsor</p>\n\n<p><strong>Abstract Base class</strong></p>\n\n<pre><code>namespace Tools.CastleWindsor.Interceptors\n{\nusing System;\nusing System.Text;\nusing Castle.Core.Interceptor;\nusing Castle.Core.Logging;\n\npublic abstract class AbstractLoggingInterceptor : IInterceptor\n{\n protected readonly ILoggerFactory logFactory;\n\n protected AbstractLoggingInterceptor(ILoggerFactory logFactory)\n {\n this.logFactory = logFactory;\n }\n\n public virtual void Intercept(IInvocation invocation)\n {\n ILogger logger = logFactory.Create(invocation.TargetType);\n\n try\n {\n StringBuilder sb = null;\n\n if (logger.IsDebugEnabled)\n {\n sb = new StringBuilder(invocation.TargetType.FullName).AppendFormat(\".{0}(\", invocation.Method);\n\n for (int i = 0; i &lt; invocation.Arguments.Length; i++)\n {\n if (i &gt; 0)\n sb.Append(\", \");\n\n sb.Append(invocation.Arguments[i]);\n }\n\n sb.Append(\")\");\n\n logger.Debug(sb.ToString());\n }\n\n invocation.Proceed();\n\n if (logger.IsDebugEnabled &amp;&amp; invocation.ReturnValue != null)\n {\n logger.Debug(\"Result of \" + sb + \" is: \" + invocation.ReturnValue);\n }\n }\n catch (Exception e)\n {\n logger.Error(string.Empty, e);\n throw;\n }\n }\n}\n}\n</code></pre>\n\n<p><strong>Full Logging Implemnetation</strong></p>\n\n<pre><code>namespace Tools.CastleWindsor.Interceptors\n{\nusing Castle.Core.Logging;\n\npublic class LoggingInterceptor : AbstractLoggingInterceptor\n{\n public LoggingInterceptor(ILoggerFactory logFactory) : base(logFactory)\n {\n }\n}\n}\n</code></pre>\n\n<p><strong>Method logging</strong></p>\n\n<pre><code>namespace Tools.CastleWindsor.Interceptors\n{\nusing Castle.Core.Interceptor;\nusing Castle.Core.Logging;\nusing System.Linq;\n\npublic class MethodLoggingInterceptor : AbstractLoggingInterceptor\n{\n private readonly string[] methodNames;\n\n public MethodLoggingInterceptor(string[] methodNames, ILoggerFactory logFactory) : base(logFactory)\n {\n this.methodNames = methodNames;\n }\n\n public override void Intercept(IInvocation invocation)\n {\n if ( methodNames.Contains(invocation.Method.Name) )\n base.Intercept(invocation);\n }\n}\n}\n</code></pre>\n" }, { "answer_id": 135707, "author": "Luis Abreu", "author_id": 15848, "author_profile": "https://Stackoverflow.com/users/15848", "pm_score": 3, "selected": false, "text": "<p>+1 on postsharp. Have been using for several things (including some attempts on adding preconditions and postconditions to C# code) and don't know how I'd make it without it...</p>\n" }, { "answer_id": 135804, "author": "Greg Beech", "author_id": 13552, "author_profile": "https://Stackoverflow.com/users/13552", "pm_score": 3, "selected": false, "text": "<p>It depends to an extent on how long you'll be developing and supporting the project for. Sure, IL weaving is a nice technology, but what happens if the IL and/or assembly metadata format changes again (as it did between 1.1 and 2.0) and those changes make the tool incompatible with the new format.</p>\n\n<p>If you depend on the tool then it prevents you from upgrading your technology until the tool supports it. With no guarantees in place about this (or even that development will continue, though it does seem likely) then I'd be very wary about using it on a long term project.</p>\n\n<p>Short term, no problem though.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91635", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6440/" ]
I am considering using Postsharp framework to ease the burden of application method logging. It basically allows me to adorn methods with logging attribute and at compile time injects the logging code needed into the il. I like this solution as it keeps the noise out of the deign time code environment. Any thoughts, experiences or better alternatives?
I apply logging with AOP using Castle Windsor DynamicProxies. I was already using Castle for it's IoC container, so using it for AOP was the path of least resistence for me. If you want more info let me know, I'm in the process of tidying the code up for releasing it as a blog post Edit Ok, here's the basic Intercepter code, faily basic but it does everything I need. There are two intercepters, one logs everyhing and the other allows you to define method names to allow for more fine grained logging. This solution is faily dependant on Castle Windsor **Abstract Base class** ``` namespace Tools.CastleWindsor.Interceptors { using System; using System.Text; using Castle.Core.Interceptor; using Castle.Core.Logging; public abstract class AbstractLoggingInterceptor : IInterceptor { protected readonly ILoggerFactory logFactory; protected AbstractLoggingInterceptor(ILoggerFactory logFactory) { this.logFactory = logFactory; } public virtual void Intercept(IInvocation invocation) { ILogger logger = logFactory.Create(invocation.TargetType); try { StringBuilder sb = null; if (logger.IsDebugEnabled) { sb = new StringBuilder(invocation.TargetType.FullName).AppendFormat(".{0}(", invocation.Method); for (int i = 0; i < invocation.Arguments.Length; i++) { if (i > 0) sb.Append(", "); sb.Append(invocation.Arguments[i]); } sb.Append(")"); logger.Debug(sb.ToString()); } invocation.Proceed(); if (logger.IsDebugEnabled && invocation.ReturnValue != null) { logger.Debug("Result of " + sb + " is: " + invocation.ReturnValue); } } catch (Exception e) { logger.Error(string.Empty, e); throw; } } } } ``` **Full Logging Implemnetation** ``` namespace Tools.CastleWindsor.Interceptors { using Castle.Core.Logging; public class LoggingInterceptor : AbstractLoggingInterceptor { public LoggingInterceptor(ILoggerFactory logFactory) : base(logFactory) { } } } ``` **Method logging** ``` namespace Tools.CastleWindsor.Interceptors { using Castle.Core.Interceptor; using Castle.Core.Logging; using System.Linq; public class MethodLoggingInterceptor : AbstractLoggingInterceptor { private readonly string[] methodNames; public MethodLoggingInterceptor(string[] methodNames, ILoggerFactory logFactory) : base(logFactory) { this.methodNames = methodNames; } public override void Intercept(IInvocation invocation) { if ( methodNames.Contains(invocation.Method.Name) ) base.Intercept(invocation); } } } ```
91,672
<p>In an application where users can belong to multiple groups, I'm currently storing their groups in a column called <code>groups</code> as a binary. Every four bytes is a 32 bit integer which is the <code>GroupID</code>. However, this means that to enumerate all the users in a group I have to programatically select all users, and manually find out if they contain that group.</p> <p>Another method was to use a unicode string, where each character is the integer denoting a group, and this makes searching easy, but is a bit of a fudge.</p> <p>Another method is to create a separate table, linking users to groups. One column called <code>UserID</code> and another called <code>GroupID</code>.</p> <p>Which of these ways would be the best to do it? Or is there a better way?</p>
[ { "answer_id": 91686, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 1, "selected": false, "text": "<p>The more standard, usable and comprehensible way is the join table. It's easily supported by many ORMs, in addition to being reasonably performant for most cases. Only enter in \"clever\" ways if you have a reason to, say a million of users and having to answer that question every half a second.</p>\n" }, { "answer_id": 91700, "author": "Nick Pierpoint", "author_id": 4003, "author_profile": "https://Stackoverflow.com/users/4003", "pm_score": 2, "selected": false, "text": "<p>I'd definitely go for the separate table - certainly the best relational view of data. If you have indexes on both UserID and GroupID you have a quick way of getting users per group and groups per user.</p>\n" }, { "answer_id": 91702, "author": "JacquesB", "author_id": 7488, "author_profile": "https://Stackoverflow.com/users/7488", "pm_score": 4, "selected": true, "text": "<p>You have a many-to-many relationship between users and groups. This calls for a separate table to combine users with groups:</p>\n\n<pre><code>User: (UserId[PrimaryKey], UserName etc.)\nGroup: (GroupId[PrimaryKey], GroupName etc.)\nUserInGroup: (UserId[ForeignKey], GroupId[ForeignKey])\n</code></pre>\n\n<p>To find all users in a given group, you just say:</p>\n\n<pre><code>select * from User join UserInGroup on UserId Where GroupId=&lt;the GroupId you want&gt;\n</code></pre>\n\n<p>Rule of thumb: If you feel like you need to encode multiple values in the same field, you probably need a foreign key to a separate table. Your tricks with byte-blocks or Unicode chars are just clever tricks to encode multiple values in one field. Database design should not use clever tricks - save that for application code ;-)</p>\n" }, { "answer_id": 91742, "author": "Vertigo", "author_id": 5468, "author_profile": "https://Stackoverflow.com/users/5468", "pm_score": 0, "selected": false, "text": "<p>I would make 3 tables. users, groups and usersgroups which is used as cross-reference table to link users and groups. In usersgroups table I would add userId and groupId columns and make them as primary key. BTW. What naming conventions there are to name those xref tables?</p>\n" }, { "answer_id": 92084, "author": "AJ.", "author_id": 7211, "author_profile": "https://Stackoverflow.com/users/7211", "pm_score": 0, "selected": false, "text": "<p>It depends what you're trying to do, but if your database supports it, you might consider using roles. The advantage of this is that the database provides security around roles, and you don't have to create any tables. </p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91672", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16299/" ]
In an application where users can belong to multiple groups, I'm currently storing their groups in a column called `groups` as a binary. Every four bytes is a 32 bit integer which is the `GroupID`. However, this means that to enumerate all the users in a group I have to programatically select all users, and manually find out if they contain that group. Another method was to use a unicode string, where each character is the integer denoting a group, and this makes searching easy, but is a bit of a fudge. Another method is to create a separate table, linking users to groups. One column called `UserID` and another called `GroupID`. Which of these ways would be the best to do it? Or is there a better way?
You have a many-to-many relationship between users and groups. This calls for a separate table to combine users with groups: ``` User: (UserId[PrimaryKey], UserName etc.) Group: (GroupId[PrimaryKey], GroupName etc.) UserInGroup: (UserId[ForeignKey], GroupId[ForeignKey]) ``` To find all users in a given group, you just say: ``` select * from User join UserInGroup on UserId Where GroupId=<the GroupId you want> ``` Rule of thumb: If you feel like you need to encode multiple values in the same field, you probably need a foreign key to a separate table. Your tricks with byte-blocks or Unicode chars are just clever tricks to encode multiple values in one field. Database design should not use clever tricks - save that for application code ;-)
91,678
<p>My Tomcat instance is listening to multiple IP addresses, but I want to control which source IP address is used when opening a <code>URLConnection</code>. </p> <p>How can I specify this?</p>
[ { "answer_id": 91998, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 1, "selected": false, "text": "<p>The obvious portable way would be to set a Proxy in URL.openConnection. The proxy can be in local host, you can then write a very simple proxy that binds the local address of the client socket.</p>\n\n<p>If you can't modify the source where the URL is connected, you can replace the URLStreamHandler either when calling the URL constructor or globally through URL.setURLStreamHandlerFactory. The URLStreamHandler can then delegate to the default http/https handler, modifying the openConnection call.</p>\n\n<p>A more extreme method would be to completely replace the handler (perhaps extending the implementation in your JRE). Alternatively, alternative (open source) http clients are available.</p>\n" }, { "answer_id": 92124, "author": "Javaxpert", "author_id": 15241, "author_profile": "https://Stackoverflow.com/users/15241", "pm_score": 4, "selected": true, "text": "<p>This should do the trick:</p>\n\n<pre><code>URL url = new URL(yourUrlHere);\nProxy proxy = new Proxy(Proxy.Type.DIRECT, \n new InetSocketAddress( \n InetAddress.getByAddress(\n new byte[]{your, ip, interface, here}), yourTcpPortHere));\nURLConnection conn = url.openConnection(proxy);\n</code></pre>\n\n<p>And you are done.\nDont forget to handle exceptions nicely and off course change the values to suit your scenario.</p>\n\n<p>Ah and I omitted the import statements</p>\n" }, { "answer_id": 93213, "author": "stian", "author_id": 17542, "author_profile": "https://Stackoverflow.com/users/17542", "pm_score": 2, "selected": false, "text": "<p>Using the Apache commons HttpClient I have also found the following to work (removed try/catch for clarity):</p>\n\n<pre><code>HostConfiguration hostConfiguration = new HostConfiguration();\nbyte b[] = new byte[4];\nb[0] = new Integer(192).byteValue();\nb[1] = new Integer(168).byteValue();\nb[2] = new Integer(1).byteValue();\nb[3] = new Integer(11).byteValue();\n\nhostConfiguration.setLocalAddress(InetAddress.getByAddress(b));\n\nHttpClient client = new HttpClient();\nclient.setHostConfiguration(hostConfiguration);\nGetMethod method = new GetMethod(\"http://remoteserver/\");\nmethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,\n new DefaultHttpMethodRetryHandler(3, false));\nint statusCode = client.executeMethod(method);\n\nif (statusCode != HttpStatus.SC_OK) {\n System.err.println(\"Method failed: \" + method.getStatusLine());\n}\n\nbyte[] responseBody = method.getResponseBody();\nSystem.out.println(new String(responseBody));\");\n</code></pre>\n\n<p>However, I still wonder what would happen if the gateway of the IP is down (192.168.1.11 in this case). Will the next gateway be tried or will it fail?</p>\n" }, { "answer_id": 17530095, "author": "Enzo", "author_id": 2561264, "author_profile": "https://Stackoverflow.com/users/2561264", "pm_score": 0, "selected": false, "text": "<p>Setting manually socket work fine ...</p>\n\n<pre><code>private HttpsURLConnection openConnection(URL src, URL dest, SSLContext sslContext)\n throws IOException, ProtocolException {\n HttpsURLConnection connection = (HttpsURLConnection) dest.openConnection();\n HttpsHostNameVerifier httpsHostNameVerifier = new HttpsHostNameVerifier();\n connection.setHostnameVerifier(httpsHostNameVerifier);\n connection.setConnectTimeout(CONNECT_TIMEOUT);\n connection.setReadTimeout(READ_TIMEOUT);\n connection.setRequestMethod(POST_METHOD);\n connection.setRequestProperty(CONTENT_TYPE, SoapConstants.CONTENT_TYPE_HEADER);\n connection.setDoOutput(true);\n connection.setDoInput(true);\n connection.setSSLSocketFactory(sslContext.getSocketFactory());\n if ( src!=null ) {\n InetAddress inetAddress = InetAddress.getByName(src.getHost());\n int destPort = dest.getPort();\n if ( destPort &lt;=0 ) \n destPort=SERVER_HTTPS_PORT;\n int srcPort = src.getPort();\n if ( srcPort &lt;=0 ) \n srcPort=CLIENT_HTTPS_PORT;\n connectionSocket = connection.getSSLSocketFactory().createSocket(dest.getHost(), destPort, inetAddress, srcPort);\n }\n connection.connect();\n return connection;\n} \n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91678", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17542/" ]
My Tomcat instance is listening to multiple IP addresses, but I want to control which source IP address is used when opening a `URLConnection`. How can I specify this?
This should do the trick: ``` URL url = new URL(yourUrlHere); Proxy proxy = new Proxy(Proxy.Type.DIRECT, new InetSocketAddress( InetAddress.getByAddress( new byte[]{your, ip, interface, here}), yourTcpPortHere)); URLConnection conn = url.openConnection(proxy); ``` And you are done. Dont forget to handle exceptions nicely and off course change the values to suit your scenario. Ah and I omitted the import statements
91,692
<p>Can anyone recommend a framework for templating/formatting messages in a standalone application along the lines of the JSP EL (Expression Language)?</p> <p>I would expect to be able to instantiate a an object of some sort, give it a template along the lines of</p> <pre><code>Dear ${customer.firstName}. You order will be dispatched on ${order.estimatedDispatchDate} </code></pre> <p>provide it with a context which would include a value dictionary of parameter objects (in this case an object of type Customer with a name 'customer', say, and an object of type Order with a name 'order').</p> <p>I know there are many template frameworks out there - many of which work outside the web application context, but I do not see this as a big heavyweight templating framework. Just a better version of the basic Message Format functionality Java already provides </p> <p>For example, I can accomplish the above with java.text.MessageFormat by using a template (or a 'pattern' as they call it) such as</p> <pre><code>Dear {0}. You order will be dispatched on {1,date,EEE dd MMM yyyy} </code></pre> <p>and I can pass it an Object array, in my calling Java program</p> <pre><code>new Object[] { customer.getFirstName(), order.getEstimatedDispatchDate() }; </code></pre> <p>However, in this usage, the code and the pattern are intimately linked. While I could put the pattern in a resource properties file, the code and the pattern need to know intimate details about each other. With an EL-like system, the contract between the code and the pattern would be at a much higher level (e.g. customer and order, rather then customer.firstName and order.estimatedDispatchDate), making it easier to change the structure, order and contents of the message without changing any code.</p>
[ { "answer_id": 91755, "author": "arturh", "author_id": 4186, "author_profile": "https://Stackoverflow.com/users/4186", "pm_score": 2, "selected": false, "text": "<p>I would recommend looking into <a href=\"http://velocity.apache.org/\" rel=\"nofollow noreferrer\">Apache Velocity</a>. It is quite simple and lightweight. </p>\n\n<p>We are currently using it for our e-mail templates, and it works very well.</p>\n" }, { "answer_id": 91764, "author": "Matt Quail", "author_id": 15790, "author_profile": "https://Stackoverflow.com/users/15790", "pm_score": 1, "selected": false, "text": "<p>You might want to look at <a href=\"http://www.ognl.org/\" rel=\"nofollow noreferrer\">OGNL</a> which is the kind of library you are after. OGNL can be reasonably powerful, and is the expression language used in the <a href=\"http://www.opensymphony.com/webwork/\" rel=\"nofollow noreferrer\">WebWork</a> web framework.</p>\n" }, { "answer_id": 91819, "author": "Garth Gilmour", "author_id": 2635682, "author_profile": "https://Stackoverflow.com/users/2635682", "pm_score": 2, "selected": false, "text": "<p>The idea of using EL itself outside of Java EE was <a href=\"http://weblogs.java.net/blog/edburns/archive/2006/08/the_case_for_el.html\" rel=\"nofollow noreferrer\">advocated by Ed Burns</a> and <a href=\"http://www.theserverside.com/news/thread.tss?thread_id=41768\" rel=\"nofollow noreferrer\">discussed on The Server Side</a>. Tomcats implementation <a href=\"http://commons.apache.org/el/proposal.html\" rel=\"nofollow noreferrer\">ships in a separate JAR</a> but I don't know if it can be used outside the server.</p>\n" }, { "answer_id": 91827, "author": "McDowell", "author_id": 304, "author_profile": "https://Stackoverflow.com/users/304", "pm_score": 5, "selected": true, "text": "<p>You can just use the Universal Expression Language itself. You need an implementation (but there are a few to choose from). After that, you need to implement three classes: ELResolver, FunctionMapper and VariableMapper.</p>\n\n<p>This blog post describes how to do it: <a href=\"http://illegalargumentexception.blogspot.com/2008/04/java-using-el-outside-j2ee.html\" rel=\"noreferrer\">Java: using EL outside J2EE</a>.</p>\n" }, { "answer_id": 91841, "author": "Alexandre Victoor", "author_id": 11897, "author_profile": "https://Stackoverflow.com/users/11897", "pm_score": 0, "selected": false, "text": "<p>Freemarker would do exactly what you need. This is a template engine with a syntax very similar to JSP :</p>\n\n<p><a href=\"http://freemarker.org/\" rel=\"nofollow noreferrer\">http://freemarker.org/</a></p>\n" }, { "answer_id": 122184, "author": "Dónal", "author_id": 2648, "author_profile": "https://Stackoverflow.com/users/2648", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://www.stringtemplate.org/\" rel=\"nofollow noreferrer\">StringTemplate</a> is a more lightweight alternative to Velocity and Freemarker.</p>\n" }, { "answer_id": 132568, "author": "Vihung", "author_id": 15452, "author_profile": "https://Stackoverflow.com/users/15452", "pm_score": 1, "selected": false, "text": "<p>Re: Jasper and Juel being built for 1.5: And then I discovered RetroTranslator (<a href=\"http://retrotranslator.sourceforge.net/\" rel=\"nofollow noreferrer\">http://retrotranslator.sourceforge.net/</a>). Once retrotranslated, EL and Jasper works like a charm</p>\n" }, { "answer_id": 133028, "author": "Vihung", "author_id": 15452, "author_profile": "https://Stackoverflow.com/users/15452", "pm_score": 0, "selected": false, "text": "<p>AAh. Whereas with MessageFormat, I can do</p>\n\n<pre><code>Dear {0}. Your order will be dispatched on {1,date,EEE dd MMM yyyy}\n</code></pre>\n\n<p>where parameter #1 is a Date object and it gets formatted according to the pattern, there is no equivalent in EL. </p>\n\n<p>In JSP, I would have used, perhaps, a format tag. In this standalone example, I am going to have to format the Date as a String in my code prior to evaluating the expression.</p>\n" }, { "answer_id": 4423412, "author": "Casper", "author_id": 539772, "author_profile": "https://Stackoverflow.com/users/539772", "pm_score": 2, "selected": false, "text": "<p>You can use Casper very similar to jsp and easy to use : <a href=\"http://code.google.com/p/casper/\" rel=\"nofollow\">Casper</a></p>\n" }, { "answer_id": 28663050, "author": "yglodt", "author_id": 272180, "author_profile": "https://Stackoverflow.com/users/272180", "pm_score": 2, "selected": false, "text": "<p>I would go for the Spring Expression language:</p>\n\n<p><a href=\"http://docs.spring.io/spring/docs/current/spring-framework-reference/html/expressions.html\" rel=\"nofollow\">http://docs.spring.io/spring/docs/current/spring-framework-reference/html/expressions.html</a></p>\n\n<p>A few examples which demonstrate the power (the first two are from the documentation):</p>\n\n<pre><code>int year = (Integer) parser.parseExpression(\"Birthdate.Year + 1900\").getValue(context);\n\nString city = (String) parser.parseExpression(\"placeOfBirth.City\").getValue(context);\n\n// weekday is a String, e.g. \"Mon\", time is an int, e.g. 1400 or 900\n{\"Thu\", \"Fri\"}.contains(weekday) and time matches '\\d{4}'\n</code></pre>\n\n<p>Expressions can also use object properties:</p>\n\n<pre><code>public class Data {\n private String name; // getter and setter omitted\n}\n\nData data = new Data();\ndata.setName(\"John Doe\");\n\nExpressionParser p = new SpelExpressionParser();\nExpression e = p.parseExpression(\"name == 'John Doe'\");\nBoolean r = (Boolean) e.getValue(data); // will return true\n\ne = p.parseExpression(\"Hello \" + name + \", how are you ?\");\nString text = e.getValue(data, String.class); // text will be \"Hello John Doe, how are you ?\"\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91692", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15452/" ]
Can anyone recommend a framework for templating/formatting messages in a standalone application along the lines of the JSP EL (Expression Language)? I would expect to be able to instantiate a an object of some sort, give it a template along the lines of ``` Dear ${customer.firstName}. You order will be dispatched on ${order.estimatedDispatchDate} ``` provide it with a context which would include a value dictionary of parameter objects (in this case an object of type Customer with a name 'customer', say, and an object of type Order with a name 'order'). I know there are many template frameworks out there - many of which work outside the web application context, but I do not see this as a big heavyweight templating framework. Just a better version of the basic Message Format functionality Java already provides For example, I can accomplish the above with java.text.MessageFormat by using a template (or a 'pattern' as they call it) such as ``` Dear {0}. You order will be dispatched on {1,date,EEE dd MMM yyyy} ``` and I can pass it an Object array, in my calling Java program ``` new Object[] { customer.getFirstName(), order.getEstimatedDispatchDate() }; ``` However, in this usage, the code and the pattern are intimately linked. While I could put the pattern in a resource properties file, the code and the pattern need to know intimate details about each other. With an EL-like system, the contract between the code and the pattern would be at a much higher level (e.g. customer and order, rather then customer.firstName and order.estimatedDispatchDate), making it easier to change the structure, order and contents of the message without changing any code.
You can just use the Universal Expression Language itself. You need an implementation (but there are a few to choose from). After that, you need to implement three classes: ELResolver, FunctionMapper and VariableMapper. This blog post describes how to do it: [Java: using EL outside J2EE](http://illegalargumentexception.blogspot.com/2008/04/java-using-el-outside-j2ee.html).
91,699
<p>Python's convention is that variables are created by first assignment, and trying to read their value before one has been assigned raises an exception. PHP by contrast implicitly creates a variable when it is read, with a null value. This means it is easy to do this in PHP:</p> <pre><code>function mymodule_important_calculation() { $result = /* ... long and complex calculation ... */; return $resukt; } </code></pre> <p>This function always returns null, and if null is a valid value for the functuion then the bug might go undetected for some time. The Python equivalent would complain that the variable <code>resukt</code> is being used before it is assigned.</p> <p>So... is there a way to configure PHP to be stricter with variable assignments?</p>
[ { "answer_id": 91713, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 2, "selected": false, "text": "<p>There is no way to make it fail as far as I know, but with E_NOTICE in error_reporting settings you can make it throw a warning (well, a notice :-) But still a string you can search for ).</p>\n" }, { "answer_id": 91717, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 4, "selected": true, "text": "<p><strong>PHP</strong> doesn't do much forward checking of things at parse time. </p>\n\n<p>The best you can do is crank up the warning level to report your mistakes, but by the time you get an E_NOTICE, its too late, and its not possible to force E_NOTICES to occur in advance yet.</p>\n\n<p>A lot of people are toting the \"error_reporting E_STRICT\" flag, but its still retroactive warning, and won't protect you from bad code mistakes like you posted.</p>\n\n<p>This gem turned up on the php-dev mailing-list this week and I think its just the tool you want. Its more a lint-checker, but it adds scope to the current lint checking PHP does. </p>\n\n<p><a href=\"http://code.google.com/p/php-initialized/wiki/Features\" rel=\"noreferrer\"><strong>PHP-Initialized Google Project</strong></a></p>\n\n<p>There's the hope that with a bit of attention we can get this behaviour implemented in PHP itself. So put your 2-cents on the PHP mailing list / bug system / feature requests and see if we can encourage its integration. </p>\n" }, { "answer_id": 91720, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 0, "selected": false, "text": "<p>I'm pretty sure that it generates an error if the variable wasn't previously declared. If your installation isn't showing such errors, check the error_reporting() level in your php.ini file.</p>\n" }, { "answer_id": 91723, "author": "gizmo", "author_id": 9396, "author_profile": "https://Stackoverflow.com/users/9396", "pm_score": 0, "selected": false, "text": "<p>You can try to play with the error reporting level as indicated here: <a href=\"http://us3.php.net/error_reporting\" rel=\"nofollow noreferrer\">http://us3.php.net/error_reporting</a> but I'm not sure it mention the usage of non initiated variable, even with E_STRICT.</p>\n" }, { "answer_id": 91738, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Check out error reporting, <a href=\"http://php.net/manual/en/function.error-reporting.php\" rel=\"nofollow noreferrer\">http://php.net/manual/en/function.error-reporting.php</a></p>\n\n<p>What you want is probably E_STRICT. Just bare in mind that PHP has no namespaces, and error reporting becomes global. Kind of sucks to be you if you use a 3rd party library from developers that did not have error reporting switched on.</p>\n" }, { "answer_id": 91776, "author": "e-satis", "author_id": 9951, "author_profile": "https://Stackoverflow.com/users/9951", "pm_score": 0, "selected": false, "text": "<p>There is something similar : in PHP you can change the error reporting level. It's a best practice to set it to maximum in a dev environnement. To do so :</p>\n\n<p>Add in your PHP.ini: </p>\n\n<pre><code>error_reporting = E_ALL\n</code></pre>\n\n<p>Or you can just add this at the top of the file your are working on :</p>\n\n<pre><code>error_reporting(E_ALL);\n</code></pre>\n\n<p>This won't prevent your code from running but the lack of variable assignments will display a very clear error message in your browser.</p>\n" }, { "answer_id": 95717, "author": "Kris Erickson", "author_id": 3798, "author_profile": "https://Stackoverflow.com/users/3798", "pm_score": 0, "selected": false, "text": "<p>If you use the \"Analyze Code\" on files, or your project in Zend Studio it will warn you about any uninitialized variables (this actually helped find a ton of misspelled variables lurking in seldom used portions of the code just waiting to cause very difficult to detect errors). Perhaps someone could add that functionality in the PHP lint function (php -l), which currently only checks for syntax errors. </p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91699", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8925/" ]
Python's convention is that variables are created by first assignment, and trying to read their value before one has been assigned raises an exception. PHP by contrast implicitly creates a variable when it is read, with a null value. This means it is easy to do this in PHP: ``` function mymodule_important_calculation() { $result = /* ... long and complex calculation ... */; return $resukt; } ``` This function always returns null, and if null is a valid value for the functuion then the bug might go undetected for some time. The Python equivalent would complain that the variable `resukt` is being used before it is assigned. So... is there a way to configure PHP to be stricter with variable assignments?
**PHP** doesn't do much forward checking of things at parse time. The best you can do is crank up the warning level to report your mistakes, but by the time you get an E\_NOTICE, its too late, and its not possible to force E\_NOTICES to occur in advance yet. A lot of people are toting the "error\_reporting E\_STRICT" flag, but its still retroactive warning, and won't protect you from bad code mistakes like you posted. This gem turned up on the php-dev mailing-list this week and I think its just the tool you want. Its more a lint-checker, but it adds scope to the current lint checking PHP does. [**PHP-Initialized Google Project**](http://code.google.com/p/php-initialized/wiki/Features) There's the hope that with a bit of attention we can get this behaviour implemented in PHP itself. So put your 2-cents on the PHP mailing list / bug system / feature requests and see if we can encourage its integration.
91,715
<p>I've not used C++ very much in the past, and have recently been doing a lot of C#, and I'm really struggling to get back into the basics of C++ again. This is particularly tricky as work mandates that none of the most handy C++ constructs can be used, so all strings must be char *'s, and there is no provision for STL lists.</p> <p>What I'm currently trying to do is to create a list of strings, something which would take me no time at all using STL or in C#. Basically I want to have a function such as:</p> <pre><code>char **registeredNames = new char*[numberOfNames]; </code></pre> <p>Then,</p> <pre><code>RegisterName(const * char const name, const int length) { //loop to see if name already registered snipped if(notFound) { registeredNames[lastIndex++] = name; } } </code></pre> <p>or, if it was C#...</p> <pre><code>if(!registeredNames.Contains(name)) { registeredNames.Add(name); } </code></pre> <p>and I realize that it doesn't work. I know the const nature of the passed variables (a const pointer and a const string) makes it rather difficult, but my basic problem is that I've always avoided this situation in the past by using STL lists etc. so I've never had to work around it!</p>
[ { "answer_id": 91749, "author": "Maximilian", "author_id": 1733, "author_profile": "https://Stackoverflow.com/users/1733", "pm_score": 1, "selected": false, "text": "<p>Edit: I guess I misunderstood your question. There is no constness problem in this code I'm aware of.</p>\n\n<p>I'm doing this from my head but it should be about right:</p>\n\n<pre><code>static int lastIndex = 0;\nstatic char **registeredNames = new char*[numberOfNames];\n\nvoid RegisterName(const * char const name)\n{\n bool found = false;\n //loop to see if name already registered snipped\n for (int i = 0; i &lt; lastIndex; i++)\n {\n if (strcmp(name, registeredNames[i] == 0))\n {\n found = true;\n break;\n }\n }\n\n if (!found)\n {\n registeredNames[lastIndex++] = name;\n }\n}\n</code></pre>\n" }, { "answer_id": 91759, "author": "Seb Rose", "author_id": 12405, "author_profile": "https://Stackoverflow.com/users/12405", "pm_score": 4, "selected": true, "text": "<p>You'll probably need to use strcmp to see if the string is already stored:</p>\n\n<pre><code>for (int index=0; index&lt;=lastIndex; index++)\n{\n if (strcmp(registeredNames[index], name) == 0)\n {\n return; // Already registered\n }\n}\n</code></pre>\n\n<p>Then if you really need to store a copy of the string, then you'll need to allocate a buffer and copy the characters over.</p>\n\n<pre><code>char* nameCopy = malloc(length+1);\nstrcpy(nameCopy, name);\nregisteredNames[lastIndex++] = nameCopy;\n</code></pre>\n\n<p>You didn't mention whether your input is NULL terminated - if not, then extra care is needed, and strcmp/strcpy won't be suitable.</p>\n" }, { "answer_id": 91761, "author": "PierreBdR", "author_id": 7136, "author_profile": "https://Stackoverflow.com/users/7136", "pm_score": 1, "selected": false, "text": "<p>Working with char* requires you to work with C functions. In your case, what you really need is to copy the strings around. To help you, you have the strndup function. Then you'll have to write something like:</p>\n\n<pre><code>void RegisterName(const char* name)\n{\n // loop to see if name already registered snipped\n if(notFound)\n {\n registerNames[lastIndex++] = stdndup(name, MAX_STRING_LENGTH);\n }\n}\n</code></pre>\n\n<p>This code suppose your array is big enough.</p>\n\n<p>Of course, the very best would be to properly implement your own string and array and list, ... or to convince your boss the STL is not evil anymore !</p>\n" }, { "answer_id": 91762, "author": "Skizz", "author_id": 1898, "author_profile": "https://Stackoverflow.com/users/1898", "pm_score": 1, "selected": false, "text": "<p>Using:</p>\n\n<pre><code>const char **registeredNames = new const char * [numberOfNames];\n</code></pre>\n\n<p>will allow you to assign a <code>const * char const</code> to an element of the array.</p>\n\n<p>Just out of curiosity, why does \"work mandates that none of the most handy C++ constructs can be used\"?</p>\n" }, { "answer_id": 91763, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 2, "selected": false, "text": "<p>Why can't you use the STL?</p>\n\n<p>Anyway, I would suggest that you implement a simple string class and list templates of your own. That way you can use the same techniques as you normally would and keep the pointer and memory management confined to those classes. If you mimic the STL, it would be even better.</p>\n" }, { "answer_id": 91828, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 3, "selected": false, "text": "<p>If portability is an issue, you may want to check out <a href=\"http://www.stlport.org/\" rel=\"nofollow noreferrer\">STLport</a>.</p>\n" }, { "answer_id": 91867, "author": "David Sykes", "author_id": 259, "author_profile": "https://Stackoverflow.com/users/259", "pm_score": 2, "selected": false, "text": "<p>If you really can't use stl (and I regret believing that was true when I was in the games industry) then can you not create your own string class? The most basic of string class would allocate memory on construction and assignment, and handle the delete in the destructor. Later you could add further functionality as you need it. Totally portable, and very easy to write and unit test.</p>\n" }, { "answer_id": 91958, "author": "graham.reeds", "author_id": 342, "author_profile": "https://Stackoverflow.com/users/342", "pm_score": 1, "selected": false, "text": "<p>I can understand why you can't use STL - most do bloat your code terribly. However there are implementations for games programmers by games programmers - <a href=\"http://code.google.com/p/rdestl/\" rel=\"nofollow noreferrer\">RDESTL</a> is one such library.</p>\n" }, { "answer_id": 91988, "author": "Mark", "author_id": 4405, "author_profile": "https://Stackoverflow.com/users/4405", "pm_score": 3, "selected": false, "text": "<p>There are legitimate reasons that STL might be avoided. When working in fixed environments where memory or speed is a premium, it's sometimes difficult to tell what is going on under the hood with STL. Yes, you can write your own memory allocators, and yes, speed generally isn't a problem, but there are differences between STL implementations across platforms, and those differences mighe be subtle and potentially buggy. Memory is perhaps my biggest concern when thinking about using it.</p>\n\n<p>Memory is precious, and how we use it needs to be tightly controlled. Unless you've been down this road, this concept might not make sense, but it's true. We do allow for STL usage in tools (outside of game code), but it's prohibited inside of the actual game. One other related problem is code size. I am slightly unsure of how much STL can contribute to executable size, but we've seen marked increases in code size when using STL. Even if your executable is \"only\" 2M bigger, that's 2M less RAM for something else for your game.</p>\n\n<p>STL is nice for sure. But it can be abused by programmers who don't know what they are doing. It's not intentional, but it can provide nasty surprises when you don't want to see them (again, memory bloat and performance issues)</p>\n\n<p>I'm sure that you are close with your solution.</p>\n\n<pre><code>for ( i = 0; i &lt; lastIndex; i++ ) {\n if ( !strcmp(&amp;registeredNames[i], name ) {\n break; // name was found\n }\n}\nif ( i == lastIndex ) {\n // name was not found in the registeredNames list\n registeredNames[lastIndex++] = strdup(name);\n}\n</code></pre>\n\n<p>You might not want to use strdup. That's simply an example of how to to store the name given your example. You might want to make sure that you either don't want to allocate space for the new name yourself, or use some other memory construct that might already be available in your app.</p>\n\n<p>And please, don't write a string class. I have held up string classes as perhaps the worst example of how not to re-engineer a basic C construct in C++. Yes, the string class can hide lots of nifty details from you, but it's memory usage patterns are terrible, and those don't fit well into a console (i.e. ps3 or 360, etc) environment. About 8 years ago we did the same time. 200000+ memory allocations before we hit the main menu. Memory was terribly fragmented and we couldn't get the rest of the game to fit in the fixed environment. We wound up ripping it out.</p>\n\n<p>Class design is great for some things, but this isn't one of them. This is an opinion, but it's based on real world experience.</p>\n" }, { "answer_id": 92149, "author": "jheriko", "author_id": 17604, "author_profile": "https://Stackoverflow.com/users/17604", "pm_score": 0, "selected": false, "text": "<p>If you are not worried about conventions and just want to get the job done use realloc. I do this sort of thing for lists all of the time, it goes something like this:</p>\n\n<pre><code>T** list = 0;\nunsigned int length = 0;\n\nT* AddItem(T Item)\n{\n list = realloc(list, sizeof(T)*(length+1));\n if(!list) return 0;\n list[length] = new T(Item);\n ++length;\n return list[length];\n}\n\nvoid CleanupList()\n{\n for(unsigned int i = 0; i &lt; length; ++i)\n {\n delete item[i];\n }\n free(list)\n}\n</code></pre>\n\n<p>There is more you can do, e.g. only realloc each time the list size doubles, functions for removing items from list by index or by checking equality, make a template class for handling lists etc... (I have one I wrote ages ago and always use myself... but sadly I am at work and can't just copy-paste it here). To be perfectly honest though, this will probably not outperform the STL equivalent, although it may equal its performance if you do a ton of work or have an especially poor implementation of STL.</p>\n\n<p>Annoyingly C++ is without an operator renew/resize to replace realloc, which would be very useful.</p>\n\n<p>Oh, and apologies if my code is error ridden, I just pulled it out from memory.</p>\n" }, { "answer_id": 92447, "author": "titanae", "author_id": 2387, "author_profile": "https://Stackoverflow.com/users/2387", "pm_score": 0, "selected": false, "text": "<p>All the approaches suggested are valid, my point is if the way C# does it is appealing replicate it, create your own classes/interfaces to present the same abstraction, i.e. a simple linked list class with methods Contains and Add, using the sample code provided by other answers this should be relatively simple.</p>\n\n<p>One of the great things about C++ is generally you can make it look and act the way you want, if another language has a great implementation of something you can usually reproduce it.</p>\n" }, { "answer_id": 92584, "author": "Greg Rogers", "author_id": 5963, "author_profile": "https://Stackoverflow.com/users/5963", "pm_score": 0, "selected": false, "text": "<p>const correctness is still const correctness regardless of whether you use the STL or not. I believe what you are looking for is to make registeredNames a <code>const char **</code> so that the assignment to <code>registeredNames[i]</code> (which is a <code>const char *</code>) works.</p>\n\n<p>Moreover, is this really what you want to be doing? It seems like making a copy of the string is probably more appropriate.</p>\n\n<p>Moreover still, you shouldn't be thinking about storing this in a list given the operation you are doing on it, a set would be better.</p>\n" }, { "answer_id": 97874, "author": "Roger Nelson", "author_id": 14964, "author_profile": "https://Stackoverflow.com/users/14964", "pm_score": 0, "selected": false, "text": "<p>I have used this String class for years.</p>\n\n<p><a href=\"http://www.robertnz.net/string.htm\" rel=\"nofollow noreferrer\" title=\"String class\">http://www.robertnz.net/string.htm</a></p>\n\n<p>It provides practically all the features of the\nSTL string but is implemented as a true class not a template\nand does not use STL.</p>\n" }, { "answer_id": 103911, "author": "Jeroen Dirks", "author_id": 7743, "author_profile": "https://Stackoverflow.com/users/7743", "pm_score": 0, "selected": false, "text": "<p>This is a clear case of you get to roll your own. And do the same for a vector class.</p>\n\n<ul>\n<li>Do it with test-first programming.</li>\n<li>Keep it simple.</li>\n</ul>\n\n<p>Avoid reference counting the string buffer if you are in MT environment.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91715", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15667/" ]
I've not used C++ very much in the past, and have recently been doing a lot of C#, and I'm really struggling to get back into the basics of C++ again. This is particularly tricky as work mandates that none of the most handy C++ constructs can be used, so all strings must be char \*'s, and there is no provision for STL lists. What I'm currently trying to do is to create a list of strings, something which would take me no time at all using STL or in C#. Basically I want to have a function such as: ``` char **registeredNames = new char*[numberOfNames]; ``` Then, ``` RegisterName(const * char const name, const int length) { //loop to see if name already registered snipped if(notFound) { registeredNames[lastIndex++] = name; } } ``` or, if it was C#... ``` if(!registeredNames.Contains(name)) { registeredNames.Add(name); } ``` and I realize that it doesn't work. I know the const nature of the passed variables (a const pointer and a const string) makes it rather difficult, but my basic problem is that I've always avoided this situation in the past by using STL lists etc. so I've never had to work around it!
You'll probably need to use strcmp to see if the string is already stored: ``` for (int index=0; index<=lastIndex; index++) { if (strcmp(registeredNames[index], name) == 0) { return; // Already registered } } ``` Then if you really need to store a copy of the string, then you'll need to allocate a buffer and copy the characters over. ``` char* nameCopy = malloc(length+1); strcpy(nameCopy, name); registeredNames[lastIndex++] = nameCopy; ``` You didn't mention whether your input is NULL terminated - if not, then extra care is needed, and strcmp/strcpy won't be suitable.
91,734
<p>I'm a little blockheaded right now…</p> <p>I have a date string in european format <strong>dd.mm.yyyy</strong> and need to transform it to <strong>mm.dd.yyyy</strong> with classic ASP. Any quick ideas?</p>
[ { "answer_id": 91780, "author": "Anheledir", "author_id": 5703, "author_profile": "https://Stackoverflow.com/users/5703", "pm_score": 2, "selected": false, "text": "<p>OK, I just found a solution myself:</p>\n\n<pre><code>payment_date = MID(payment_date,4,3) &amp; LEFT(payment_date,3) &amp; MID(payment_date,7)\n</code></pre>\n" }, { "answer_id": 91787, "author": "Re0sless", "author_id": 2098, "author_profile": "https://Stackoverflow.com/users/2098", "pm_score": 4, "selected": true, "text": "<p>If its always in that format you could use split</p>\n\n<pre><code>d = split(\".\",\"dd.mm.yyyy\")\ns = d(1) &amp; \".\" &amp; d(0) &amp; \".\" &amp; d(2)\n</code></pre>\n\n<p>this would allow for dates like 1.2.99 as well</p>\n" }, { "answer_id": 91802, "author": "Vincent McNabb", "author_id": 16299, "author_profile": "https://Stackoverflow.com/users/16299", "pm_score": 2, "selected": false, "text": "<pre><code>Dim arrParts() As String\nDim theDate As Date\n\narrParts = Split(strOldFormat, \".\")\ntheDate = DateTime.DateSerial(parts(2), parts(1), parts(0))\n\nstrNewFormat = Format(theDate, \"mm.dd.yyyy\")\n</code></pre>\n" }, { "answer_id": 132689, "author": "CJM", "author_id": 6898, "author_profile": "https://Stackoverflow.com/users/6898", "pm_score": 0, "selected": false, "text": "<p>I have my own date manipulation functions which I use in all my apps, but it was originally based on this sample:</p>\n\n<p><a href=\"http://www.adopenstatic.com/resources/code/formatdate.asp\" rel=\"nofollow noreferrer\">http://www.adopenstatic.com/resources/code/formatdate.asp</a></p>\n" }, { "answer_id": 132742, "author": "jamting", "author_id": 2639, "author_profile": "https://Stackoverflow.com/users/2639", "pm_score": 2, "selected": false, "text": "<p>This is a way to do it with built in sanity check for dates:</p>\n\n<pre><code>Dim OldString, NewString\n\nOldString = \"31.12.2008\"\n\nDim myRegExp\nSet myRegExp = New RegExp\nmyRegExp.Global = True\nmyRegExp.Pattern = \"(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.]((19|20)[0-9]{2})\"\n\nIf myRegExp.Test Then\n NewString = myRegExp.Replace(OldString, \"$2.$1.$3\")\nElse\n ' A date of for instance 32 December would end up here\n NewString = \"Invalid date\"\nEnd If\n</code></pre>\n" }, { "answer_id": 62530580, "author": "Miguel", "author_id": 10343244, "author_profile": "https://Stackoverflow.com/users/10343244", "pm_score": 0, "selected": false, "text": "<pre><code>function MyDateFormat(mydate)\n 'format: YYYYMMDDHHMMSS\n MyDateFormat = year(mydate) &amp; right(&quot;0&quot; &amp; month(mydate),2) &amp; _\n right(&quot;0&quot; &amp; day(mydate),2) &amp; right(&quot;0&quot; &amp; hour(mydate),2) &amp;_\n right(&quot;0&quot; &amp; minute(mydate),2) &amp; right(&quot;0&quot; &amp; second(mydate),2)\nend function\n\nresponse.write(MyDateFormat(Now))\n</code></pre>\n<p>show: 20200623102805</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91734", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5703/" ]
I'm a little blockheaded right now… I have a date string in european format **dd.mm.yyyy** and need to transform it to **mm.dd.yyyy** with classic ASP. Any quick ideas?
If its always in that format you could use split ``` d = split(".","dd.mm.yyyy") s = d(1) & "." & d(0) & "." & d(2) ``` this would allow for dates like 1.2.99 as well
91,745
<p>I am building a table using the DataGridView where a user can select items from a dropdown in each cell. To simplify the problem, lets say i have 1 column. I am using the DataGridViewComboBoxColumn in the designer. I am trying to support having each row in that column have a different list of items to choose from.</p> <p>Is this possible?</p>
[ { "answer_id": 163247, "author": "WaterBoy", "author_id": 3270, "author_profile": "https://Stackoverflow.com/users/3270", "pm_score": 5, "selected": true, "text": "<p>Yes. This can be done using the DataGridViewComboBoxCell.</p>\n\n<p>Here is an example method to add the items to just one cell, rather than the whole column.</p>\n\n<pre><code>private void setCellComboBoxItems(DataGridView dataGrid, int rowIndex, int colIndex, object[] itemsToAdd)\n{\n DataGridViewComboBoxCell dgvcbc = (DataGridViewComboBoxCell) dataGrid.Rows[rowIndex].Cells[colIndex];\n // You might pass a boolean to determine whether to clear or not.\n dgvcbc.Items.Clear();\n foreach (object itemToAdd in itemsToAdd)\n {\n dgvcbc.Items.Add(itemToAdd);\n }\n}\n</code></pre>\n" }, { "answer_id": 1641437, "author": "Steve", "author_id": 198620, "author_profile": "https://Stackoverflow.com/users/198620", "pm_score": 2, "selected": false, "text": "<pre><code>private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)\n{\n if (e.ColumnIndex == DataGridViewComboBoxColumnNumber)\n {\n setCellComboBoxItems(myDataGridView, e.RowIndex, e.ColumnIndex, someObj);\n }\n}\n</code></pre>\n" }, { "answer_id": 8879383, "author": "Jay", "author_id": 1151740, "author_profile": "https://Stackoverflow.com/users/1151740", "pm_score": 1, "selected": false, "text": "<p>Just in case anyone finds this thread, this is my solution in VB 2008. The advantage this offers is that it allows you to assign an ID to each value in the combobox.</p>\n\n<pre><code> Private Sub FillGroups()\n Try\n 'Create Connection and SQLCommand here.\n\n Conn.Open()\n Dim dr As SqlDataReader = cm.ExecuteReader\n\n dgvGroups.Rows.Clear()\n\n Dim PreviousGroup As String = \"\"\n\n Dim l As New List(Of Groups)\n\n While dr.Read\n\n Dim g As New Groups\n g.RegionID = CheckInt(dr(\"cg_id\"))\n g.RegionName = CheckString(dr(\"cg_name\"))\n g.GroupID = CheckInt(dr(\"vg_id\"))\n g.GroupName = CheckString(dr(\"vg_name\"))\n l.Add(g)\n\n End While\n dr.Close()\n Conn.Close()\n\n For Each a In (From r In l Select r.RegionName, r.RegionID).Distinct\n\n Dim RegionID As Integer = a.RegionID 'Doing it this way avoids a warning\n\n dgvGroups.Rows.Add(New Object() {a.RegionID, a.RegionName})\n\n Dim c As DataGridViewComboBoxCell = CType(dgvGroups.Rows(dgvGroups.RowCount - 1).Cells(colGroup.Index), DataGridViewComboBoxCell)\n c.DataSource = (From g In l Where g.RegionID = RegionID Select g.GroupID, g.GroupName).ToArray\n c.DisplayMember = \"GroupName\"\n c.ValueMember = \"GroupID\"\n Next\n\n Catch ex As Exception\n End Try\nEnd Sub\n\nPrivate Class Groups\n\n Private _RegionID As Integer\n Public Property RegionID() As Integer\n Get\n Return _RegionID\n End Get\n Set(ByVal value As Integer)\n _RegionID = value\n End Set\n End Property\n\n Private _RegionName As String\n Public Property RegionName() As String\n Get\n Return _RegionName\n End Get\n Set(ByVal value As String)\n _RegionName = value\n End Set\n End Property\n\n Private _GroupName As String\n Public Property GroupName() As String\n Get\n Return _GroupName\n End Get\n Set(ByVal value As String)\n _GroupName = value\n End Set\n End Property\n\n Private _GroupID As Integer\n Public Property GroupID() As Integer\n Get \n Return _GroupID\n End Get\n Set(ByVal value As Integer)\n _GroupID = value\n End Set\n End Property\n\nEnd Class\n</code></pre>\n" }, { "answer_id": 35395898, "author": "Ahmed Soliman", "author_id": 4334304, "author_profile": "https://Stackoverflow.com/users/4334304", "pm_score": 0, "selected": false, "text": "<p>this is an example with gridView which have 2 comboboxColumns and when a comboBoxColumns1 selected index changed then load comboBoxColumns2 with data from from two different columns from database .</p>\n\n<pre><code> private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)\n {\n if (dataGridView1.Rows[e.RowIndex].Cells[0].Value != null &amp;&amp; dataGridView1.CurrentCell.ColumnIndex == 0)\n {\n\n SqlConnection conn = new SqlConnection(\"data source=.;initial catalog=pharmacy;integrated security=true\");\n SqlCommand cmd = new SqlCommand(\"select [drugTypeParent],[drugTypeChild] from [drugs] where [drugName]='\" + dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString() + \"'\", conn);\n conn.Open();\n SqlDataReader dr = cmd.ExecuteReader();\n while (dr.Read())\n {\n\n object[] o = new object[] { dr[0].ToString(),dr[1].ToString() };\n DataGridViewComboBoxCell dgvcbc = (DataGridViewComboBoxCell)dataGridView1.Rows[e.RowIndex].Cells[1];\n\n dgvcbc.Items.Clear();\n foreach (object itemToAdd in o)\n {\n dgvcbc.Items.Add(itemToAdd);\n }\n }\n dr.Close();\n conn.Close();\n }\n }\n</code></pre>\n" }, { "answer_id": 37096974, "author": "jock mcspiffy", "author_id": 6305941, "author_profile": "https://Stackoverflow.com/users/6305941", "pm_score": -1, "selected": false, "text": "<pre><code> //Populate the Datatable with the Lookup lists\n private DataTable typeDataTable(DataGridView dataGridView, Lookup&lt;string, Element&gt; type_Lookup, Dictionary&lt;Element, string&gt; type_dictionary, string strNewStyle, string strOldStyle, string strID, string strCount)\n {\n int row = 0;\n\n DataTable dt = new DataTable();\n\n dt.Columns.Add(strOldStyle, typeof(string));\n dt.Columns.Add(strID, typeof(string));\n dt.Columns.Add(strCount, typeof(int));\n dt.Columns.Add(\"combobox\", typeof(DataGridViewComboBoxCell));\n\n\n\n //Add All Doc Types to ComboBoxes\n DataGridViewComboBoxCell CmBx = new DataGridViewComboBoxCell();\n CmBx.DataSource = new BindingSource(type_dictionary, null);\n CmBx.DisplayMember = \"Value\";\n CmBx.ValueMember = \"Key\";\n\n\n //Add Style Comboboxes\n DataGridViewComboBoxColumn Data_CmBx_Col = new DataGridViewComboBoxColumn();\n Data_CmBx_Col.HeaderText = strNewStyle;\n dataGridView.Columns.Add(addDataGrdViewComboBox(Data_CmBx_Col, type_dictionary));\n\n setCellComboBoxItems(dataGridView, 1, 3, CmBx);\n\n //Add style Rows\n foreach (IGrouping&lt;string, Element&gt; StyleGroup in type_Lookup)\n {\n row++;\n //Iterate through each group in the Igrouping\n //Add Style Rows\n dt.Rows.Add(StyleGroup.Key, row, StyleGroup.Count().ToString());\n\n\n }\n return dt;\n }\n\n\n\n\n private void setCellComboBoxItems(DataGridView dataGrid, int rowIndex, int colIndex, DataGridViewComboBoxCell CmBx)\n {\n DataGridViewComboBoxCell dgvcbc = (DataGridViewComboBoxCell)dataGrid.Rows[rowIndex].Cells[colIndex];\n // You might pass a boolean to determine whether to clear or not.\n dgvcbc.Items.Clear();\n foreach (DataGridViewComboBoxCell itemToAdd in CmBx.Items)\n {\n dgvcbc.Items.Add(itemToAdd);\n }\n</code></pre>\n" }, { "answer_id": 53238441, "author": "bh_earth0", "author_id": 3137362, "author_profile": "https://Stackoverflow.com/users/3137362", "pm_score": 0, "selected": false, "text": "<p>setting the comboboxcell right after setting datasource <strong>doesnt work for me</strong>. it has to be done after binding operations completed. i choosed CellBeginEdit </p>\n\n<p>example of empty dropdowns:</p>\n\n<pre><code>dgv1.datasource = datatable1;\ndgv1.columns.add ( \"cbxcol\" , typeof(string) );\n\n// different source for each comboboxcell in rows\nvar dict_rowInd_cbxDs = new Dictionary&lt;int, object&gt;();\ndict_rowInd_cbxDs[1] = new list&lt;string&gt;(){\"en\" , \"us\"};\ndict_rowInd_cbxDs[2] = new list&lt;string&gt;(){ \"car\", \"bike\"};\n\n// !!!!!! setting comboboxcell after creating doesnt work here\nforeach( row in dgv.Rows.asEnumerable() )\n{ \n var cell = res_tn.dgv.CurrentCell as DataGridViewComboBoxCell;\n cell.DataSource = dict_dgvRowI_cbxDs[res_tn.dgv.CurrentCell.RowIndex];\n\n}\n</code></pre>\n\n<p>working example:</p>\n\n<pre><code>dgv1.datasource = datatable1;\ndgv1.columns.add ( \"cbxcol\" , typeof(string) );\n\n// different source for each comboboxcell in rows\nvar dict_rowInd_cbxDs = new Dictionary&lt;int, object&gt;();\ndict_rowInd_cbxDs[1] = new list&lt;string&gt;(){\"en\" , \"us\"};\ndict_rowInd_cbxDs[2] = new list&lt;string&gt;(){ \"car\", \"bike\"};\n\n\n// cmboboxcell datasource Assingment Must be done after BindingComplete (not tested ) or cellbeginEdit (tested by me) \nres_tn.dgv.CellBeginEdit += (s1, e1) =&gt; {\n if (res_tn.dgv.CurrentCell is DataGridViewComboBoxCell) {\n if (dict_dgvRowI_cbxDs.ContainsKey(res_tn.dgv.CurrentCell.RowIndex)) \n {\n var cll = res_tn.dgv.CurrentCell as DataGridViewComboBoxCell;\n cll.DataSource = dict_dgvRowI_cbxDs[res_tn.dgv.CurrentCell.RowIndex];\n\n // required if it is list&lt;mycustomClass&gt;\n // cll.DisplayMember = \"ColName\";\n // cll.ValueMember = \"This\";\n }\n }\n\n};\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91745", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4653/" ]
I am building a table using the DataGridView where a user can select items from a dropdown in each cell. To simplify the problem, lets say i have 1 column. I am using the DataGridViewComboBoxColumn in the designer. I am trying to support having each row in that column have a different list of items to choose from. Is this possible?
Yes. This can be done using the DataGridViewComboBoxCell. Here is an example method to add the items to just one cell, rather than the whole column. ``` private void setCellComboBoxItems(DataGridView dataGrid, int rowIndex, int colIndex, object[] itemsToAdd) { DataGridViewComboBoxCell dgvcbc = (DataGridViewComboBoxCell) dataGrid.Rows[rowIndex].Cells[colIndex]; // You might pass a boolean to determine whether to clear or not. dgvcbc.Items.Clear(); foreach (object itemToAdd in itemsToAdd) { dgvcbc.Items.Add(itemToAdd); } } ```
91,747
<p>How can I set the background color of a specific item in a <em>System.Windows.Forms.ListBox</em>?</p> <p>I would like to be able to set multiple ones if possible.</p>
[ { "answer_id": 91758, "author": "Grad van Horck", "author_id": 12569, "author_profile": "https://Stackoverflow.com/users/12569", "pm_score": 7, "selected": true, "text": "<p>Probably the only way to accomplish that is to draw the items yourself.</p>\n<p>Set the <code>DrawMode</code> to <code>OwnerDrawFixed</code> and code something like this on the DrawItem event:</p>\n<pre><code>private void listBox_DrawItem(object sender, DrawItemEventArgs e)\n{\n e.DrawBackground();\n Graphics g = e.Graphics;\n\n g.FillRectangle(new SolidBrush(Color.Silver), e.Bounds);\n\n // Print text\n\n e.DrawFocusRectangle();\n}\n</code></pre>\n<p>The second option would be using a ListView, although they have an other way of implementations (not really data bound, but more flexible in way of columns).</p>\n" }, { "answer_id": 91770, "author": "Matthew Scharley", "author_id": 15537, "author_profile": "https://Stackoverflow.com/users/15537", "pm_score": 2, "selected": false, "text": "<pre><code>// Set the background to a predefined colour\nMyListBox.BackColor = Color.Red;\n// OR: Set parts of a color.\nMyListBox.BackColor.R = 255;\nMyListBox.BackColor.G = 0;\nMyListBox.BackColor.B = 0;\n</code></pre>\n<p>If what you mean by setting multiple background colors is setting a different background color for each item, this isn't possible with a ListBox, but it <em>is</em> with a ListView, with something like:</p>\n<pre><code>// Set the background of the first item in the list\nMyListView.Items[0].BackColor = Color.Red;\n</code></pre>\n" }, { "answer_id": 3709452, "author": "Shadow The Kid Wizard", "author_id": 447356, "author_profile": "https://Stackoverflow.com/users/447356", "pm_score": 6, "selected": false, "text": "<p>Thanks for the <a href=\"https://stackoverflow.com/a/91758/447356\">answer by Grad van Horck</a>. It guided me in the correct direction.</p>\n<p>To support text (not just background color), here is my fully working code:</p>\n<pre><code>//global brushes with ordinary/selected colors\nprivate SolidBrush reportsForegroundBrushSelected = new SolidBrush(Color.White);\nprivate SolidBrush reportsForegroundBrush = new SolidBrush(Color.Black);\nprivate SolidBrush reportsBackgroundBrushSelected = new SolidBrush(Color.FromKnownColor(KnownColor.Highlight));\nprivate SolidBrush reportsBackgroundBrush1 = new SolidBrush(Color.White);\nprivate SolidBrush reportsBackgroundBrush2 = new SolidBrush(Color.Gray);\n\n//custom method to draw the items, don't forget to set DrawMode of the ListBox to OwnerDrawFixed\nprivate void lbReports_DrawItem(object sender, DrawItemEventArgs e)\n{\n e.DrawBackground();\n bool selected = ((e.State &amp; DrawItemState.Selected) == DrawItemState.Selected);\n\n int index = e.Index;\n if (index &gt;= 0 &amp;&amp; index &lt; lbReports.Items.Count)\n {\n string text = lbReports.Items[index].ToString();\n Graphics g = e.Graphics;\n\n //background:\n SolidBrush backgroundBrush;\n if (selected)\n backgroundBrush = reportsBackgroundBrushSelected;\n else if ((index % 2) == 0)\n backgroundBrush = reportsBackgroundBrush1;\n else\n backgroundBrush = reportsBackgroundBrush2;\n g.FillRectangle(backgroundBrush, e.Bounds);\n\n //text:\n SolidBrush foregroundBrush = (selected) ? reportsForegroundBrushSelected : reportsForegroundBrush;\n g.DrawString(text, e.Font, foregroundBrush, lbReports.GetItemRectangle(index).Location);\n }\n\n e.DrawFocusRectangle();\n}\n</code></pre>\n<p>The above adds to the given code and will show the proper text plus highlight the selected item.</p>\n" }, { "answer_id": 41631585, "author": "Serdar Karaca", "author_id": 2920105, "author_profile": "https://Stackoverflow.com/users/2920105", "pm_score": -1, "selected": false, "text": "<pre><code>public MainForm()\n{\n InitializeComponent();\n this.listbox1.DrawItem += new DrawItemEventHandler(this.listbox1_DrawItem);\n}\n\nprivate void listbox1_DrawItem(object sender, System.Windows.Forms.DrawItemEventArgs e)\n{\n e.DrawBackground();\n Brush myBrush = Brushes.Black;\n var item = listbox1.Items[e.Index];\n if(e.Index % 2 == 0)\n {\n e.Graphics.FillRectangle(new SolidBrush(Color.Gold), e.Bounds);\n }\n e.Graphics.DrawString(((ListBox)sender).Items[e.Index].ToString(), \n e.Font, myBrush,e.Bounds, StringFormat.GenericDefault);\n e.DrawFocusRectangle();\n }\n}\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91747", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11137/" ]
How can I set the background color of a specific item in a *System.Windows.Forms.ListBox*? I would like to be able to set multiple ones if possible.
Probably the only way to accomplish that is to draw the items yourself. Set the `DrawMode` to `OwnerDrawFixed` and code something like this on the DrawItem event: ``` private void listBox_DrawItem(object sender, DrawItemEventArgs e) { e.DrawBackground(); Graphics g = e.Graphics; g.FillRectangle(new SolidBrush(Color.Silver), e.Bounds); // Print text e.DrawFocusRectangle(); } ``` The second option would be using a ListView, although they have an other way of implementations (not really data bound, but more flexible in way of columns).
91,766
<p>I have a DataGrid where each column has a SortExpression. I would like the sort expression to be the equivalent of "ORDER BY LEN(myField)".</p> <p>I have tried </p> <pre><code>SortExpression="LEN(myField)" </code></pre> <p>but this throws an exception as it is not valid syntax. Any ideas?</p>
[ { "answer_id": 91788, "author": "Biri", "author_id": 968, "author_profile": "https://Stackoverflow.com/users/968", "pm_score": 3, "selected": true, "text": "<p>What about returning the len by the query already, but don't show that column, only use it as your original column's sortexpression?</p>\n\n<p>I don't think that your idea is supported by default.</p>\n" }, { "answer_id": 91806, "author": "Ilya Kochetov", "author_id": 15329, "author_profile": "https://Stackoverflow.com/users/15329", "pm_score": 2, "selected": false, "text": "<p>Depending on your SQL flavor the following could work:</p>\n\n<pre><code>SELECT\n ColumnA as FieldA\n , ColumnB as FieldB\n , LEN(ColumnA) as FieldL\nFROM TableName\nORDER BY L\n</code></pre>\n\n<p>And then do</p>\n\n<pre><code>SortExpression=\"FieldL\"\n</code></pre>\n" }, { "answer_id": 91815, "author": "Skizz", "author_id": 1898, "author_profile": "https://Stackoverflow.com/users/1898", "pm_score": 0, "selected": false, "text": "<p>The <code>SortExpression</code> parameter specifies the name of the column to sort, followed by \"ASC\" or \"DESC\" to control the order.</p>\n\n<p>You could change the <code>DataType</code> property of the column to specifiy a user defined type whose comparer function compares string lengths. It won't be a trivial task.</p>\n" }, { "answer_id": 94077, "author": "Adam Vigh", "author_id": 1613872, "author_profile": "https://Stackoverflow.com/users/1613872", "pm_score": 0, "selected": false, "text": "<p>Using Linq, you could write your query like:</p>\n\n<pre><code>query.OrderBy(column =&gt; column.MyField.Length);\n</code></pre>\n" }, { "answer_id": 94107, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Hmmm. Had some time to test. I was able to get <strong>SortExpression=\"Description.Length\"</strong> to work. Is this 1.1, 2.0 or 3.5?</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15393/" ]
I have a DataGrid where each column has a SortExpression. I would like the sort expression to be the equivalent of "ORDER BY LEN(myField)". I have tried ``` SortExpression="LEN(myField)" ``` but this throws an exception as it is not valid syntax. Any ideas?
What about returning the len by the query already, but don't show that column, only use it as your original column's sortexpression? I don't think that your idea is supported by default.
91,778
<p>To create a new event handler on a control you can do this</p> <pre><code>c.Click += new EventHandler(mainFormButton_Click); </code></pre> <p>or this</p> <pre><code>c.Click += mainFormButton_Click; </code></pre> <p>and to remove an event handler you can do this</p> <pre><code>c.Click -= mainFormButton_Click; </code></pre> <p>But how do you remove all event handlers from an event?</p>
[ { "answer_id": 91803, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 6, "selected": false, "text": "<p>From <em><a href=\"http://bytes.com/forum/thread274921.html\" rel=\"noreferrer\">Removing All Event Handlers</a></em>:</p>\n\n<blockquote>\n <p>Directly no, in large part because you\n cannot simply set the event to null.</p>\n \n <p>Indirectly, you could make the actual\n event private and create a property\n around it that tracks all of the\n delegates being added/subtracted to\n it.</p>\n \n <p>Take the following:</p>\n\n<pre><code>List&lt;EventHandler&gt; delegates = new List&lt;EventHandler&gt;();\n\nprivate event EventHandler MyRealEvent;\n\npublic event EventHandler MyEvent\n{\n add\n {\n MyRealEvent += value;\n delegates.Add(value);\n }\n\n remove\n {\n MyRealEvent -= value;\n delegates.Remove(value);\n }\n}\n\npublic void RemoveAllEvents()\n{\n foreach(EventHandler eh in delegates)\n {\n MyRealEvent -= eh;\n }\n delegates.Clear();\n}\n</code></pre>\n</blockquote>\n" }, { "answer_id": 91820, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": 2, "selected": false, "text": "<p>If you <strong>reaallly</strong> have to do this... it'll take reflection and quite some time to do this. Event handlers are managed in an event-to-delegate-map inside a control. You would need to</p>\n\n<ul>\n<li>Reflect and obtain this map in the control instance.</li>\n<li>Iterate for each event, get the delegate\n\n<ul>\n<li>each delegate in turn could be a chained series of event handlers. So call obControl.RemoveHandler(event, handler)</li>\n</ul></li>\n</ul>\n\n<p>In short, a lot of work. It is possible in theory... I never tried something like this.</p>\n\n<p>See if you can have better control/discipline over the subscribe-unsubscribe phase for the control.</p>\n" }, { "answer_id": 91853, "author": "xsl", "author_id": 11387, "author_profile": "https://Stackoverflow.com/users/11387", "pm_score": 9, "selected": true, "text": "<p>I found a solution on the <a href=\"http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/576f69e7-55aa-4574-8d31-417422954689/\" rel=\"noreferrer\">MSDN forums</a>. The sample code below will remove all <code>Click</code> events from <code>button1</code>.</p>\n<pre><code>public partial class Form1 : Form\n{\n public Form1()\n {\n InitializeComponent();\n\n button1.Click += button1_Click;\n button1.Click += button1_Click2;\n button2.Click += button2_Click;\n }\n\n private void button1_Click(object sender, EventArgs e) =&gt; MessageBox.Show(&quot;Hello&quot;);\n private void button1_Click2(object sender, EventArgs e) =&gt; MessageBox.Show(&quot;World&quot;);\n private void button2_Click(object sender, EventArgs e) =&gt; RemoveClickEvent(button1);\n\n private void RemoveClickEvent(Button b)\n {\n FieldInfo f1 = typeof(Control).GetField(&quot;EventClick&quot;, \n BindingFlags.Static | BindingFlags.NonPublic);\n\n object obj = f1.GetValue(b);\n PropertyInfo pi = b.GetType().GetProperty(&quot;Events&quot;, \n BindingFlags.NonPublic | BindingFlags.Instance);\n\n EventHandlerList list = (EventHandlerList)pi.GetValue(b, null);\n list.RemoveHandler(obj, list[obj]);\n }\n}\n</code></pre>\n" }, { "answer_id": 1032221, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "<p>It doesn't do any harm to delete a non-existing event handler. So if you know what handlers there might be, you can simply delete all of them. I just had similar case. This may help in some cases.</p>\n\n<p>Like:</p>\n\n<pre><code>// Add handlers...\nif (something)\n{\n c.Click += DoesSomething;\n}\nelse\n{\n c.Click += DoesSomethingElse;\n}\n\n// Remove handlers...\nc.Click -= DoesSomething;\nc.Click -= DoesSomethingElse;\n</code></pre>\n" }, { "answer_id": 1597332, "author": "SwDevMan81", "author_id": 95573, "author_profile": "https://Stackoverflow.com/users/95573", "pm_score": 2, "selected": false, "text": "<p>I just found <em><a href=\"http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/c873d460-2f7d-41f6-8149-3055a9dd5e7a\" rel=\"nofollow noreferrer\">How to suspend events when setting a property of a WinForms control</a></em>. It will remove all events from a control:</p>\n\n<pre><code>namespace CMessWin05\n{\n public class EventSuppressor\n {\n Control _source;\n EventHandlerList _sourceEventHandlerList;\n FieldInfo _headFI;\n Dictionary&lt;object, Delegate[]&gt; _handlers;\n PropertyInfo _sourceEventsInfo;\n Type _eventHandlerListType;\n Type _sourceType;\n\n\n public EventSuppressor(Control control)\n {\n if (control == null)\n throw new ArgumentNullException(\"control\", \"An instance of a control must be provided.\");\n\n _source = control;\n _sourceType = _source.GetType();\n _sourceEventsInfo = _sourceType.GetProperty(\"Events\", BindingFlags.Instance | BindingFlags.NonPublic);\n _sourceEventHandlerList = (EventHandlerList)_sourceEventsInfo.GetValue(_source, null);\n _eventHandlerListType = _sourceEventHandlerList.GetType();\n _headFI = _eventHandlerListType.GetField(\"head\", BindingFlags.Instance | BindingFlags.NonPublic);\n }\n\n private void BuildList()\n {\n _handlers = new Dictionary&lt;object, Delegate[]&gt;();\n object head = _headFI.GetValue(_sourceEventHandlerList);\n if (head != null)\n {\n Type listEntryType = head.GetType();\n FieldInfo delegateFI = listEntryType.GetField(\"handler\", BindingFlags.Instance | BindingFlags.NonPublic);\n FieldInfo keyFI = listEntryType.GetField(\"key\", BindingFlags.Instance | BindingFlags.NonPublic);\n FieldInfo nextFI = listEntryType.GetField(\"next\", BindingFlags.Instance | BindingFlags.NonPublic);\n BuildListWalk(head, delegateFI, keyFI, nextFI);\n }\n }\n\n private void BuildListWalk(object entry, FieldInfo delegateFI, FieldInfo keyFI, FieldInfo nextFI)\n {\n if (entry != null)\n {\n Delegate dele = (Delegate)delegateFI.GetValue(entry);\n object key = keyFI.GetValue(entry);\n object next = nextFI.GetValue(entry);\n\n Delegate[] listeners = dele.GetInvocationList();\n if(listeners != null &amp;&amp; listeners.Length &gt; 0)\n _handlers.Add(key, listeners);\n\n if (next != null)\n {\n BuildListWalk(next, delegateFI, keyFI, nextFI);\n }\n }\n }\n\n public void Resume()\n {\n if (_handlers == null)\n throw new ApplicationException(\"Events have not been suppressed.\");\n\n foreach (KeyValuePair&lt;object, Delegate[]&gt; pair in _handlers)\n {\n for (int x = 0; x &lt; pair.Value.Length; x++)\n _sourceEventHandlerList.AddHandler(pair.Key, pair.Value[x]);\n }\n\n _handlers = null;\n }\n\n public void Suppress()\n {\n if (_handlers != null)\n throw new ApplicationException(\"Events are already being suppressed.\");\n\n BuildList();\n\n foreach (KeyValuePair&lt;object, Delegate[]&gt; pair in _handlers)\n {\n for (int x = pair.Value.Length - 1; x &gt;= 0; x--)\n _sourceEventHandlerList.RemoveHandler(pair.Key, pair.Value[x]);\n }\n }\n\n }\n}\n</code></pre>\n" }, { "answer_id": 2382433, "author": "Francine", "author_id": 286592, "author_profile": "https://Stackoverflow.com/users/286592", "pm_score": -1, "selected": false, "text": "<p>I found this answer and it almost fit my needs. Thanks to SwDevMan81 for the class. I have modified it to allow suppression and resumation of individual methods, and I thought I'd post it here.</p>\n\n<pre><code>// This class allows you to selectively suppress event handlers for controls. You instantiate\n// the suppressor object with the control, and after that you can use it to suppress all events\n// or a single event. If you try to suppress an event which has already been suppressed\n// it will be ignored. Same with resuming; you can resume all events which were suppressed,\n// or a single one. If you try to resume an un-suppressed event handler, it will be ignored.\n\n//cEventSuppressor _supButton1 = null;\n//private cEventSuppressor SupButton1 {\n// get {\n// if (_supButton1 == null) {\n// _supButton1 = new cEventSuppressor(this.button1);\n// }\n// return _supButton1;\n// }\n//}\n//private void button1_Click(object sender, EventArgs e) {\n// MessageBox.Show(\"Clicked!\");\n//}\n\n//private void button2_Click(object sender, EventArgs e) {\n// SupButton1.Suppress(\"button1_Click\");\n//}\n\n//private void button3_Click(object sender, EventArgs e) {\n// SupButton1.Resume(\"button1_Click\");\n//}\nusing System;\nusing System.Collections.Generic;\nusing System.Text;\n\nusing System.Reflection;\nusing System.Windows.Forms;\nusing System.ComponentModel;\n\nnamespace Crystal.Utilities {\n public class cEventSuppressor {\n Control _source;\n EventHandlerList _sourceEventHandlerList;\n FieldInfo _headFI;\n Dictionary&lt;object, Delegate[]&gt; suppressedHandlers = new Dictionary&lt;object, Delegate[]&gt;();\n PropertyInfo _sourceEventsInfo;\n Type _eventHandlerListType;\n Type _sourceType;\n\n public cEventSuppressor(Control control) {\n if (control == null)\n throw new ArgumentNullException(\"control\", \"An instance of a control must be provided.\");\n\n _source = control;\n _sourceType = _source.GetType();\n _sourceEventsInfo = _sourceType.GetProperty(\"Events\", BindingFlags.Instance | BindingFlags.NonPublic);\n _sourceEventHandlerList = (EventHandlerList)_sourceEventsInfo.GetValue(_source, null);\n _eventHandlerListType = _sourceEventHandlerList.GetType();\n _headFI = _eventHandlerListType.GetField(\"head\", BindingFlags.Instance | BindingFlags.NonPublic);\n }\n private Dictionary&lt;object, Delegate[]&gt; BuildList() {\n Dictionary&lt;object, Delegate[]&gt; retval = new Dictionary&lt;object, Delegate[]&gt;();\n object head = _headFI.GetValue(_sourceEventHandlerList);\n if (head != null) {\n Type listEntryType = head.GetType();\n FieldInfo delegateFI = listEntryType.GetField(\"handler\", BindingFlags.Instance | BindingFlags.NonPublic);\n FieldInfo keyFI = listEntryType.GetField(\"key\", BindingFlags.Instance | BindingFlags.NonPublic);\n FieldInfo nextFI = listEntryType.GetField(\"next\", BindingFlags.Instance | BindingFlags.NonPublic);\n retval = BuildListWalk(retval, head, delegateFI, keyFI, nextFI);\n }\n return retval;\n }\n\n private Dictionary&lt;object, Delegate[]&gt; BuildListWalk(Dictionary&lt;object, Delegate[]&gt; dict,\n object entry, FieldInfo delegateFI, FieldInfo keyFI, FieldInfo nextFI) {\n if (entry != null) {\n Delegate dele = (Delegate)delegateFI.GetValue(entry);\n object key = keyFI.GetValue(entry);\n object next = nextFI.GetValue(entry);\n\n if (dele != null) {\n Delegate[] listeners = dele.GetInvocationList();\n if (listeners != null &amp;&amp; listeners.Length &gt; 0) {\n dict.Add(key, listeners);\n }\n }\n if (next != null) {\n dict = BuildListWalk(dict, next, delegateFI, keyFI, nextFI);\n }\n }\n return dict;\n }\n public void Resume() {\n }\n public void Resume(string pMethodName) {\n //if (_handlers == null)\n // throw new ApplicationException(\"Events have not been suppressed.\");\n Dictionary&lt;object, Delegate[]&gt; toRemove = new Dictionary&lt;object, Delegate[]&gt;();\n\n // goes through all handlers which have been suppressed. If we are resuming,\n // all handlers, or if we find the matching handler, add it back to the\n // control's event handlers\n foreach (KeyValuePair&lt;object, Delegate[]&gt; pair in suppressedHandlers) {\n\n for (int x = 0; x &lt; pair.Value.Length; x++) {\n\n string methodName = pair.Value[x].Method.Name;\n if (pMethodName == null || methodName.Equals(pMethodName)) {\n _sourceEventHandlerList.AddHandler(pair.Key, pair.Value[x]);\n toRemove.Add(pair.Key, pair.Value);\n }\n }\n }\n // remove all un-suppressed handlers from the list of suppressed handlers\n foreach (KeyValuePair&lt;object, Delegate[]&gt; pair in toRemove) {\n for (int x = 0; x &lt; pair.Value.Length; x++) {\n suppressedHandlers.Remove(pair.Key);\n }\n }\n //_handlers = null;\n }\n public void Suppress() {\n Suppress(null);\n }\n public void Suppress(string pMethodName) {\n //if (_handlers != null)\n // throw new ApplicationException(\"Events are already being suppressed.\");\n\n Dictionary&lt;object, Delegate[]&gt; dict = BuildList();\n\n foreach (KeyValuePair&lt;object, Delegate[]&gt; pair in dict) {\n for (int x = pair.Value.Length - 1; x &gt;= 0; x--) {\n //MethodInfo mi = pair.Value[x].Method;\n //string s1 = mi.Name; // name of the method\n //object o = pair.Value[x].Target;\n // can use this to invoke method pair.Value[x].DynamicInvoke\n string methodName = pair.Value[x].Method.Name;\n\n if (pMethodName == null || methodName.Equals(pMethodName)) {\n _sourceEventHandlerList.RemoveHandler(pair.Key, pair.Value[x]);\n suppressedHandlers.Add(pair.Key, pair.Value);\n }\n }\n }\n }\n } \n}\n</code></pre>\n" }, { "answer_id": 4352051, "author": "Ivan Ferrer Villa", "author_id": 382515, "author_profile": "https://Stackoverflow.com/users/382515", "pm_score": 4, "selected": false, "text": "<p>I'm actually using this method and it works perfectly. I was 'inspired' by the code written by Aeonhack <a href=\"http://www.dreamincode.net/code/snippet5016.htm\" rel=\"nofollow noreferrer\">here</a>.</p>\n<pre class=\"lang-vb prettyprint-override\"><code>\n Public Event MyEvent()\n Protected Overrides Sub Dispose(ByVal disposing As Boolean)\n If MyEventEvent IsNot Nothing Then\n For Each d In MyEventEvent.GetInvocationList ' If this throws an exception, try using .ToArray\n RemoveHandler MyEvent, d\n Next\n End If\n End Sub\n</code></pre>\n<pre class=\"lang-csharp prettyprint-override\"><code> ~MyClass()\n {\n if (MyEventEvent != null)\n {\n foreach (var d in MyEventEvent.GetInvocationList())\n {\n MyEventEvent -= (MyEvent)d;\n }\n }\n\n }\n</code></pre>\n<p>The field MyEventEvent is hidden, but it does exist.</p>\n<p>Debugging, you can see how <code>d.target</code> is the object actually handling the event, and <code>d.method</code> its method. You only have to remove it.</p>\n<p>It works great. No more objects not being GC'ed because of the event handlers.</p>\n" }, { "answer_id": 5475424, "author": "Stephen Punak", "author_id": 682408, "author_profile": "https://Stackoverflow.com/users/682408", "pm_score": 8, "selected": false, "text": "<p>You guys are making this WAY too hard on yourselves. It's this easy:</p>\n\n<pre><code>void OnFormClosing(object sender, FormClosingEventArgs e)\n{\n foreach(Delegate d in FindClicked.GetInvocationList())\n {\n FindClicked -= (FindClickedHandler)d;\n }\n}\n</code></pre>\n" }, { "answer_id": 5536365, "author": "Anoop Muraleedharan", "author_id": 690767, "author_profile": "https://Stackoverflow.com/users/690767", "pm_score": 2, "selected": false, "text": "<p>This page helped me a lot. The code I got from here was meant to remove a click event from a button. I need to remove double click events from some panels and click events from some buttons. So I made a control extension, which will remove all event handlers for a certain event.</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Drawing;\nusing System.Windows.Forms;\nusing System.Reflection;\npublic static class EventExtension\n{\n public static void RemoveEvents&lt;T&gt;(this T target, string eventName) where T:Control\n {\n if (ReferenceEquals(target, null)) throw new NullReferenceException(\"Argument \\\"target\\\" may not be null.\");\n FieldInfo fieldInfo = typeof(Control).GetField(eventName, BindingFlags.Static | BindingFlags.NonPublic);\n if (ReferenceEquals(fieldInfo, null)) throw new ArgumentException(\n string.Concat(\"The control \", typeof(T).Name, \" does not have a property with the name \\\"\", eventName, \"\\\"\"), nameof(eventName));\n object eventInstance = fieldInfo.GetValue(target);\n PropertyInfo propInfo = typeof(T).GetProperty(\"Events\", BindingFlags.NonPublic | BindingFlags.Instance);\n EventHandlerList list = (EventHandlerList)propInfo.GetValue(target, null);\n list.RemoveHandler(eventInstance, list[eventInstance]);\n }\n}\n</code></pre>\n\n<p>Now, the usage of this extenstion.\nIf you need to remove click events from a button,</p>\n\n<pre><code>Button button = new Button();\nbutton.RemoveEvents(nameof(button.EventClick));\n</code></pre>\n\n<p>If you need to remove doubleclick events from a panel,</p>\n\n<pre><code>Panel panel = new Panel();\npanel.RemoveEvents(nameof(panel.EventDoubleClick));\n</code></pre>\n\n<p>I am not an expert in C#, so if there are any bugs please forgive me and kindly let me know about it.</p>\n" }, { "answer_id": 5754729, "author": "mmike", "author_id": 720423, "author_profile": "https://Stackoverflow.com/users/720423", "pm_score": 2, "selected": false, "text": "<p>Stephen has right. It is very easy:</p>\n\n<pre><code>public event EventHandler&lt;Cles_graph_doivent_etre_redessines&gt; les_graph_doivent_etre_redessines;\npublic void remove_event()\n{\n if (this.les_graph_doivent_etre_redessines != null)\n {\n foreach (EventHandler&lt;Cles_graph_doivent_etre_redessines&gt; F_les_graph_doivent_etre_redessines in this.les_graph_doivent_etre_redessines.GetInvocationList())\n {\n this.les_graph_doivent_etre_redessines -= F_les_graph_doivent_etre_redessines;\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 7899618, "author": "suso", "author_id": 567562, "author_profile": "https://Stackoverflow.com/users/567562", "pm_score": -1, "selected": false, "text": "<p>Well, here there's another solution to remove an asociated event (if you already have a method for handling the events for the control):</p>\n\n<pre><code>EventDescriptor ed = TypeDescriptor.GetEvents(this.button1).Find(\"MouseDown\",true); \nDelegate delegate = Delegate.CreateDelegate(typeof(EventHandler), this, \"button1_MouseDownClicked\");\nif(ed!=null) \n ed.RemoveEventHandler(this.button1, delegate);\n</code></pre>\n" }, { "answer_id": 8108103, "author": "LionSoft", "author_id": 301257, "author_profile": "https://Stackoverflow.com/users/301257", "pm_score": 6, "selected": false, "text": "<p>Accepted answer is not full. It doesn't work for events declared as {add; remove;}</p>\n\n<p>Here is working code:</p>\n\n<pre><code>public static void ClearEventInvocations(this object obj, string eventName)\n{\n var fi = obj.GetType().GetEventField(eventName);\n if (fi == null) return;\n fi.SetValue(obj, null);\n}\n\nprivate static FieldInfo GetEventField(this Type type, string eventName)\n{\n FieldInfo field = null;\n while (type != null)\n {\n /* Find events defined as field */\n field = type.GetField(eventName, BindingFlags.Static | BindingFlags.Instance | BindingFlags.NonPublic);\n if (field != null &amp;&amp; (field.FieldType == typeof(MulticastDelegate) || field.FieldType.IsSubclassOf(typeof(MulticastDelegate))))\n break;\n\n /* Find events defined as property { add; remove; } */\n field = type.GetField(\"EVENT_\" + eventName.ToUpper(), BindingFlags.Static | BindingFlags.Instance | BindingFlags.NonPublic);\n if (field != null)\n break;\n type = type.BaseType;\n }\n return field;\n}\n</code></pre>\n" }, { "answer_id": 11688939, "author": "Sergio Cabral", "author_id": 1396511, "author_profile": "https://Stackoverflow.com/users/1396511", "pm_score": 1, "selected": false, "text": "<p>Wow. I found this solution, but nothing worked like I wanted. But this is so good:</p>\n\n<pre><code>EventHandlerList listaEventos;\n\nprivate void btnDetach_Click(object sender, EventArgs e)\n{\n listaEventos = DetachEvents(comboBox1);\n}\n\nprivate void btnAttach_Click(object sender, EventArgs e)\n{\n AttachEvents(comboBox1, listaEventos);\n}\n\npublic EventHandlerList DetachEvents(Component obj)\n{\n object objNew = obj.GetType().GetConstructor(new Type[] { }).Invoke(new object[] { });\n PropertyInfo propEvents = obj.GetType().GetProperty(\"Events\", BindingFlags.NonPublic | BindingFlags.Instance);\n\n EventHandlerList eventHandlerList_obj = (EventHandlerList)propEvents.GetValue(obj, null);\n EventHandlerList eventHandlerList_objNew = (EventHandlerList)propEvents.GetValue(objNew, null);\n\n eventHandlerList_objNew.AddHandlers(eventHandlerList_obj);\n eventHandlerList_obj.Dispose();\n\n return eventHandlerList_objNew;\n}\n\npublic void AttachEvents(Component obj, EventHandlerList eventos)\n{\n PropertyInfo propEvents = obj.GetType().GetProperty(\"Events\", BindingFlags.NonPublic | BindingFlags.Instance);\n\n EventHandlerList eventHandlerList_obj = (EventHandlerList)propEvents.GetValue(obj, null);\n\n eventHandlerList_obj.AddHandlers(eventos);\n}\n</code></pre>\n" }, { "answer_id": 31114831, "author": "RenniePet", "author_id": 253938, "author_profile": "https://Stackoverflow.com/users/253938", "pm_score": -1, "selected": false, "text": "<p>This is not an answer to the OP, but I thought I'd post this here in case it can help others. </p>\n\n<pre><code> /// &lt;summary&gt;\n /// Method to remove a (single) SocketAsyncEventArgs.Completed event handler. This is \n /// partially based on information found here: http://stackoverflow.com/a/91853/253938\n /// \n /// But note that this may not be a good idea, being very .Net implementation-dependent. Note \n /// in particular use of \"m_Completed\" instead of \"Completed\".\n /// &lt;/summary&gt;\n private static void RemoveCompletedEventHandler(SocketAsyncEventArgs eventArgs)\n {\n FieldInfo fieldInfo = typeof(SocketAsyncEventArgs).GetField(\"m_Completed\", \n BindingFlags.Instance | BindingFlags.NonPublic);\n eventArgs.Completed -= (EventHandler&lt;SocketAsyncEventArgs&gt;)fieldInfo.GetValue(eventArgs);\n }\n</code></pre>\n" }, { "answer_id": 38506787, "author": "Vinicius Schneider", "author_id": 6605414, "author_profile": "https://Stackoverflow.com/users/6605414", "pm_score": 4, "selected": false, "text": "<p>I hated any complete solutions shown here, I did a mix and tested now, worked for any event handler:</p>\n\n<pre><code>public class MyMain()\n public void MyMethod() {\n AnotherClass.TheEventHandler += DoSomeThing;\n }\n\n private void DoSomething(object sender, EventArgs e) {\n Debug.WriteLine(\"I did something\");\n AnotherClass.ClearAllDelegatesOfTheEventHandler();\n }\n\n}\n\npublic static class AnotherClass {\n\n public static event EventHandler TheEventHandler;\n\n public static void ClearAllDelegatesOfTheEventHandler() {\n\n foreach (Delegate d in TheEventHandler.GetInvocationList())\n {\n TheEventHandler -= (EventHandler)d;\n }\n }\n}\n</code></pre>\n\n<p>Easy! Thanks for Stephen Punak.</p>\n\n<p>I used it because I use a generic local method to remove the delegates and the local method was called after different cases, when different delegates are setted.</p>\n" }, { "answer_id": 39537438, "author": "Jhonattan", "author_id": 2766725, "author_profile": "https://Stackoverflow.com/users/2766725", "pm_score": 0, "selected": false, "text": "<p>Sometimes we have to work with ThirdParty controls and we need to build these awkward solutions. Based in @Anoop Muraleedharan answer I created this solution with inference type and ToolStripItem support</p>\n\n<pre><code> public static void RemoveItemEvents&lt;T&gt;(this T target, string eventName) \n where T : ToolStripItem\n { \n RemoveObjectEvents&lt;T&gt;(target, eventName);\n }\n\n public static void RemoveControlEvents&lt;T&gt;(this T target, string eventName)\n where T : Control\n {\n RemoveObjectEvents&lt;T&gt;(target, eventName);\n }\n\n private static void RemoveObjectEvents&lt;T&gt;(T target, string Event) where T : class\n {\n var typeOfT = typeof(T);\n var fieldInfo = typeOfT.BaseType.GetField(\n Event, BindingFlags.Static | BindingFlags.NonPublic);\n var provertyValue = fieldInfo.GetValue(target);\n var propertyInfo = typeOfT.GetProperty(\n \"Events\", BindingFlags.NonPublic | BindingFlags.Instance);\n var eventHandlerList = (EventHandlerList)propertyInfo.GetValue(target, null);\n eventHandlerList.RemoveHandler(provertyValue, eventHandlerList[provertyValue]);\n }\n</code></pre>\n\n<p>And you can use it like this</p>\n\n<pre><code> var toolStripButton = new ToolStripButton();\n toolStripButton.RemoveItemEvents(\"EventClick\");\n\n var button = new Button();\n button.RemoveControlEvents(\"EventClick\");\n</code></pre>\n" }, { "answer_id": 60286642, "author": "Anatoliy", "author_id": 1847209, "author_profile": "https://Stackoverflow.com/users/1847209", "pm_score": 0, "selected": false, "text": "<p>removes all handlers for button:\n save.RemoveEvents(); </p>\n\n<pre><code>public static class EventExtension\n{\n public static void RemoveEvents&lt;T&gt;(this T target) where T : Control\n {\n var propInfo = typeof(T).GetProperty(\"Events\", BindingFlags.NonPublic | BindingFlags.Instance);\n var list = (EventHandlerList)propInfo.GetValue(target, null);\n list.Dispose();\n }\n}\n</code></pre>\n" }, { "answer_id": 66956934, "author": "Vassili", "author_id": 6741458, "author_profile": "https://Stackoverflow.com/users/6741458", "pm_score": 1, "selected": false, "text": "<p>A bit late to the party, but I used this link that worked perfectly well for me:\n<a href=\"https://www.codeproject.com/Articles/103542/Removing-Event-Handlers-using-Reflection\" rel=\"nofollow noreferrer\">https://www.codeproject.com/Articles/103542/Removing-Event-Handlers-using-Reflection</a></p>\n<p>The beauty of this code is that it works for all, WFP, Forms, Xamarin Forms. I used it for Xamarin. Note that you need this way of using Reflection only if you don't own this event (e.g. a library code that crashes on some event that you don't care about).</p>\n<p>Here is my slightly modified code:</p>\n<pre><code> static Dictionary&lt;Type, List&lt;FieldInfo&gt;&gt; dicEventFieldInfos = new Dictionary&lt;Type, List&lt;FieldInfo&gt;&gt;();\n\n static BindingFlags AllBindings\n {\n get { return BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static; }\n }\n\n static void BuildEventFields(Type t, List&lt;FieldInfo&gt; lst)\n {\n foreach (EventInfo ei in t.GetEvents(AllBindings))\n {\n Type dt = ei.DeclaringType;\n FieldInfo fi = dt.GetField(ei.Name, AllBindings);\n if (fi != null)\n lst.Add(fi);\n }\n }\n static List&lt;FieldInfo&gt; GetTypeEventFields(Type t)\n {\n if (dicEventFieldInfos.ContainsKey(t))\n return dicEventFieldInfos[t];\n\n List&lt;FieldInfo&gt; lst = new List&lt;FieldInfo&gt;();\n BuildEventFields(t, lst);\n dicEventFieldInfos.Add(t, lst);\n return lst;\n }\n static EventHandlerList GetStaticEventHandlerList(Type t, object obj)\n {\n MethodInfo mi = t.GetMethod(&quot;get_Events&quot;, AllBindings);\n return (EventHandlerList)mi.Invoke(obj, new object[] { });\n }\n public static void RemoveEventHandler(object obj, string EventName = &quot;&quot;)\n {\n if (obj == null)\n return;\n\n Type t = obj.GetType();\n List&lt;FieldInfo&gt; event_fields = GetTypeEventFields(t);\n EventHandlerList static_event_handlers = null;\n\n foreach (FieldInfo fi in event_fields)\n {\n if (EventName != &quot;&quot; &amp;&amp; string.Compare(EventName, fi.Name, true) != 0)\n continue;\n var eventName = fi.Name;\n // After hours and hours of research and trial and error, it turns out that\n // STATIC Events have to be treated differently from INSTANCE Events...\n if (fi.IsStatic)\n {\n // STATIC EVENT\n if (static_event_handlers == null)\n static_event_handlers = GetStaticEventHandlerList(t, obj);\n\n object idx = fi.GetValue(obj);\n Delegate eh = static_event_handlers[idx];\n if (eh == null)\n continue;\n\n Delegate[] dels = eh.GetInvocationList();\n if (dels == null)\n continue;\n\n EventInfo ei = t.GetEvent(eventName, AllBindings);\n foreach (Delegate del in dels)\n ei.RemoveEventHandler(obj, del);\n }\n else\n {\n // INSTANCE EVENT\n EventInfo ei = t.GetEvent(eventName, AllBindings);\n if (ei != null)\n {\n object val = fi.GetValue(obj);\n Delegate mdel = (val as Delegate);\n if (mdel != null)\n {\n foreach (Delegate del in mdel.GetInvocationList())\n {\n ei.RemoveEventHandler(obj, del);\n }\n }\n }\n }\n }\n }\n\n\n</code></pre>\n<p>Example usage: RemoveEventHandler(obj, &quot;Focused&quot;);</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91778", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7297/" ]
To create a new event handler on a control you can do this ``` c.Click += new EventHandler(mainFormButton_Click); ``` or this ``` c.Click += mainFormButton_Click; ``` and to remove an event handler you can do this ``` c.Click -= mainFormButton_Click; ``` But how do you remove all event handlers from an event?
I found a solution on the [MSDN forums](http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/576f69e7-55aa-4574-8d31-417422954689/). The sample code below will remove all `Click` events from `button1`. ``` public partial class Form1 : Form { public Form1() { InitializeComponent(); button1.Click += button1_Click; button1.Click += button1_Click2; button2.Click += button2_Click; } private void button1_Click(object sender, EventArgs e) => MessageBox.Show("Hello"); private void button1_Click2(object sender, EventArgs e) => MessageBox.Show("World"); private void button2_Click(object sender, EventArgs e) => RemoveClickEvent(button1); private void RemoveClickEvent(Button b) { FieldInfo f1 = typeof(Control).GetField("EventClick", BindingFlags.Static | BindingFlags.NonPublic); object obj = f1.GetValue(b); PropertyInfo pi = b.GetType().GetProperty("Events", BindingFlags.NonPublic | BindingFlags.Instance); EventHandlerList list = (EventHandlerList)pi.GetValue(b, null); list.RemoveHandler(obj, list[obj]); } } ```
91,784
<p>I have a table with say 3 columns. There's no primary key so there can be duplicate rows. I need to just keep one and delete the others. Any idea how to do this is Sql Server?</p>
[ { "answer_id": 91792, "author": "Ian Nelson", "author_id": 2084, "author_profile": "https://Stackoverflow.com/users/2084", "pm_score": 3, "selected": false, "text": "<p>Add an identity column to act as a surrogate primary key, and use this to identify two of the three rows to be deleted.</p>\n\n<p>I would consider leaving the identity column in place afterwards, or if this is some kind of link table, create a compound primary key on the other columns.</p>\n" }, { "answer_id": 91794, "author": "Manrico Corazzi", "author_id": 4690, "author_profile": "https://Stackoverflow.com/users/4690", "pm_score": 6, "selected": true, "text": "<p>I'd SELECT DISTINCT the rows and throw them into a temporary table, then drop the source table and copy back the data from the temp.\n<strong>EDIT:</strong> now with code snippet!</p>\n\n<pre><code>INSERT INTO TABLE_2 \nSELECT DISTINCT * FROM TABLE_1\nGO\nDELETE FROM TABLE_1\nGO\nINSERT INTO TABLE_1\nSELECT * FROM TABLE_2\nGO\n</code></pre>\n" }, { "answer_id": 91796, "author": "Ilya Kochetov", "author_id": 15329, "author_profile": "https://Stackoverflow.com/users/15329", "pm_score": 2, "selected": false, "text": "<p>This is a tough situation to be in. Without knowing your particular situation (table size etc) I think that your best shot is to add an identity column, populate it and then delete according to it. You may remove the column later but I would suggest that you should keep it as it is really a good thing to have in the table</p>\n" }, { "answer_id": 91980, "author": "Martin", "author_id": 11357, "author_profile": "https://Stackoverflow.com/users/11357", "pm_score": 3, "selected": false, "text": "<p>The following example works as well when your PK is just a subset of all table columns.</p>\n\n<p>(Note: I like the approach with inserting another surrogate id column more. But maybe this solution comes handy as well.)</p>\n\n<p>First find the duplicate rows: </p>\n\n<pre><code>SELECT col1, col2, count(*)\nFROM t1\nGROUP BY col1, col2\nHAVING count(*) &gt; 1\n</code></pre>\n\n<p>If there are only few, you can delete them manually:</p>\n\n<pre><code>set rowcount 1\ndelete from t1\nwhere col1=1 and col2=1\n</code></pre>\n\n<p>The value of \"rowcount\" should be n-1 times the number of duplicates. In this example there are 2 dulpicates, therefore rowcount is 1. If you get several duplicate rows, you have to do this for every unique primary key.</p>\n\n<p>If you have many duplicates, then copy every key once into anoher table:</p>\n\n<pre><code>SELECT col1, col2, col3=count(*)\nINTO holdkey\nFROM t1\nGROUP BY col1, col2\nHAVING count(*) &gt; 1\n</code></pre>\n\n<p>Then copy the keys, but eliminate the duplicates.</p>\n\n<pre><code>SELECT DISTINCT t1.*\nINTO holddups\nFROM t1, holdkey\nWHERE t1.col1 = holdkey.col1\nAND t1.col2 = holdkey.col2\n</code></pre>\n\n<p>In your keys you have now unique keys. Check if you don't get any result:</p>\n\n<pre><code>SELECT col1, col2, count(*)\nFROM holddups\nGROUP BY col1, col2\n</code></pre>\n\n<p>Delete the duplicates from the original table:</p>\n\n<pre><code>DELETE t1\nFROM t1, holdkey\nWHERE t1.col1 = holdkey.col1\nAND t1.col2 = holdkey.col2\n</code></pre>\n\n<p>Insert the original rows:</p>\n\n<pre><code>INSERT t1 SELECT * FROM holddups\n</code></pre>\n\n<p>btw and for completeness: In Oracle there is a hidden field you could use (rowid):</p>\n\n<pre><code>DELETE FROM our_table\nWHERE rowid not in\n(SELECT MIN(rowid)\nFROM our_table\nGROUP BY column1, column2, column3... ;\n</code></pre>\n\n<p>see: <a href=\"http://support.microsoft.com/kb/139444\" rel=\"nofollow noreferrer\">Microsoft Knowledge Site</a></p>\n" }, { "answer_id": 92206, "author": "Aaron", "author_id": 7659, "author_profile": "https://Stackoverflow.com/users/7659", "pm_score": 0, "selected": false, "text": "<p>After you clean up the current mess you could add a primary key that includes all the fields in the table. that will keep you from getting into the mess again.\nOf course this solution could very well break existing code. That will have to be handled as well.</p>\n" }, { "answer_id": 92232, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": -1, "selected": false, "text": "<p>I'm not sure if this works with DELETE statements, but this is a way to find duplicate rows:</p>\n\n<pre><code> SELECT *\n FROM myTable t1, myTable t2\n WHERE t1.field = t2.field AND t1.id &gt; t2.id\n</code></pre>\n\n<p>I'm not sure if you can just change the \"SELECT\" to a \"DELETE\" <em>(someone wanna let me know?)</em>, but even if you can't, you could just make it into a subquery.</p>\n" }, { "answer_id": 93021, "author": "Seibar", "author_id": 357, "author_profile": "https://Stackoverflow.com/users/357", "pm_score": 2, "selected": false, "text": "<p>Here's the method I used <a href=\"https://stackoverflow.com/questions/18932/sql-how-can-i-remove-duplicate-rows\">when I asked this question</a> -</p>\n\n<pre><code>DELETE MyTable \nFROM MyTable\nLEFT OUTER JOIN (\n SELECT MIN(RowId) as RowId, Col1, Col2, Col3 \n FROM MyTable \n GROUP BY Col1, Col2, Col3\n) as KeepRows ON\n MyTable.RowId = KeepRows.RowId\nWHERE\n KeepRows.RowId IS NULL\n</code></pre>\n" }, { "answer_id": 93030, "author": "Seibar", "author_id": 357, "author_profile": "https://Stackoverflow.com/users/357", "pm_score": 0, "selected": false, "text": "<p>Can you add a primary key identity field to the table?</p>\n" }, { "answer_id": 93493, "author": "Mike McAllister", "author_id": 16247, "author_profile": "https://Stackoverflow.com/users/16247", "pm_score": 0, "selected": false, "text": "<p>Manrico Corazzi - I specialize in Oracle, not MS SQL, so you'll have to tell me if this is possible as a performance boost:-</p>\n\n<ol>\n<li>Leave the same as your first step - insert distinct values into TABLE2 from TABLE1.</li>\n<li>Drop TABLE1. (Drop should be faster than delete I assume, much as truncate is faster than delete).</li>\n<li>Rename TABLE2 as TABLE1 (saves you time, as you're renaming an object rather than copying data from one table to another).</li>\n</ol>\n" }, { "answer_id": 94915, "author": "Dave Jackson", "author_id": 12328, "author_profile": "https://Stackoverflow.com/users/12328", "pm_score": 0, "selected": false, "text": "<p>Here's another way, with test data</p>\n\n<pre><code>create table #table1 (colWithDupes1 int, colWithDupes2 int)\ninsert into #table1\n(colWithDupes1, colWithDupes2)\nSelect 1, 2 union all\nSelect 1, 2 union all\nSelect 2, 2 union all\nSelect 3, 4 union all\nSelect 3, 4 union all\nSelect 3, 4 union all\nSelect 4, 2 union all\nSelect 4, 2 \n\n\nselect * from #table1\n\nset rowcount 1\nselect 1\n\nwhile @@rowcount &gt; 0\ndelete #table1 where 1 &lt; (select count(*) from #table1 a2 \n where #table1.colWithDupes1 = a2.colWithDupes1\nand #table1.colWithDupes2 = a2.colWithDupes2\n)\n\nset rowcount 0\n\nselect * from #table1\n</code></pre>\n" }, { "answer_id": 100117, "author": "Jonas Lincoln", "author_id": 17436, "author_profile": "https://Stackoverflow.com/users/17436", "pm_score": 2, "selected": false, "text": "<p>This is a way to do it with Common Table Expressions, CTE. It involves no loops, no new columns or anything and won't cause any unwanted triggers to fire (due to deletes+inserts). </p>\n\n<p>Inspired by <a href=\"http://www.databasejournal.com/features/mssql/article.php/3572301\" rel=\"nofollow noreferrer\">this article</a>.</p>\n\n<pre><code>CREATE TABLE #temp (i INT)\n\nINSERT INTO #temp VALUES (1)\nINSERT INTO #temp VALUES (1)\nINSERT INTO #temp VALUES (2)\nINSERT INTO #temp VALUES (3)\nINSERT INTO #temp VALUES (3)\nINSERT INTO #temp VALUES (4)\n\nSELECT * FROM #temp\n\n;\nWITH [#temp+rowid] AS\n(SELECT ROW_NUMBER() OVER (ORDER BY i ASC) AS ROWID, * FROM #temp)\nDELETE FROM [#temp+rowid] WHERE rowid IN \n(SELECT MIN(rowid) FROM [#temp+rowid] GROUP BY i HAVING COUNT(*) &gt; 1)\n\nSELECT * FROM #temp\n\nDROP TABLE #temp \n</code></pre>\n" }, { "answer_id": 101985, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>How about:</p>\n\n<pre><code>select distinct * into #t from duplicates_tbl\n\ntruncate duplicates_tbl\n\ninsert duplicates_tbl select * from #t\n\ndrop table #t\n</code></pre>\n" }, { "answer_id": 603732, "author": "Brann", "author_id": 47341, "author_profile": "https://Stackoverflow.com/users/47341", "pm_score": 0, "selected": false, "text": "<p>What about this solution :</p>\n\n<p>First you execute the following query : </p>\n\n<pre><code> select 'set rowcount ' + convert(varchar,COUNT(*)-1) + ' delete from MyTable where field=''' + field +'''' + ' set rowcount 0' from mytable group by field having COUNT(*)&gt;1\n</code></pre>\n\n<p>And then you just have to execute the returned result set</p>\n\n<pre><code>set rowcount 3 delete from Mytable where field='foo' set rowcount 0\n....\n....\nset rowcount 5 delete from Mytable where field='bar' set rowcount 0\n</code></pre>\n\n<p>I've handled the case when you've got only one column, but it's pretty easy to adapt the same approach tomore than one column. Let me know if you want me to post the code.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91784", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1688440/" ]
I have a table with say 3 columns. There's no primary key so there can be duplicate rows. I need to just keep one and delete the others. Any idea how to do this is Sql Server?
I'd SELECT DISTINCT the rows and throw them into a temporary table, then drop the source table and copy back the data from the temp. **EDIT:** now with code snippet! ``` INSERT INTO TABLE_2 SELECT DISTINCT * FROM TABLE_1 GO DELETE FROM TABLE_1 GO INSERT INTO TABLE_1 SELECT * FROM TABLE_2 GO ```
91,800
<p>I'm using a FullTextSqlQuery in SharePoint 2007 (MOSS) and need to order the results by two columns:</p> <pre><code>SELECT WorkId FROM SCOPE() ORDER BY Author ASC, Rank DESC </code></pre> <p>However it seems that only the first column from ORDER BY is taken into account when returning results. In this case the results are ordered correctly by Author, but not by Rank. If I change the order the results will be ordered by Rank, but not by Author.</p> <p>I had to resort to my own sorting of the results, which I don't like very much. Has anybody a solution to this?</p> <p><strong>Edit</strong>: Unfortunately it also doesn't accept expressions in the ORDER BY clause (SharePoint throws an exception). My guess is that even if the query looks like legitimate SQL it is parsed somehow before being served to the SQL server.</p> <p>I tried to catch the query with SQL Profiler, but to no avail.</p> <p><strong>Edit 2</strong>: In the end I used ordering by a single column (Author in my case, since it's the most important) and did the second ordering in code on the TOP N of the results. Works good enough for the project, but leaves a bad feeling of kludgy code.</p>
[ { "answer_id": 93524, "author": "Adam Hawkes", "author_id": 6703, "author_profile": "https://Stackoverflow.com/users/6703", "pm_score": 0, "selected": false, "text": "<p>I have no experience in SharePoint, but if it is the case where only one ORDER BY clause is being honored I would change it to an expression rather than a column. Assuming \"Rank\" is a numeric column with a maximum value of 10 the following may work:</p>\n\n<pre><code>SELECT WorkId FROM SCOPE() ORDER BY AUTHOR + (10 - Rank) ASC\n</code></pre>\n" }, { "answer_id": 154435, "author": "Cruiser", "author_id": 16971, "author_profile": "https://Stackoverflow.com/users/16971", "pm_score": 1, "selected": false, "text": "<p>Rank is a special column in MOSS FullTextSqlQuery that give a numeric value to the rank of each result. That value will be different for each query, and is <em>relative</em> to the other results for that particular query. Because of this rank should have a unique value for each result, and sorting by rank then author would be the same as just sorting by rank. I would try sorting on another column instead of rank to see if results come back as you expect, if so your trouble could be related to the way MOSS is ranking the results, which will vary for each unique query.</p>\n\n<p>Also you are right, the query looks like SQL, but it is not the query actually passed to the SQL server, it is special Microsoft Enterprise Search SQL Query syntax.</p>\n" }, { "answer_id": 496660, "author": "mchestnut", "author_id": 60752, "author_profile": "https://Stackoverflow.com/users/60752", "pm_score": 1, "selected": false, "text": "<p>I, too, am experiencing the same problem with FullTextSqlQuery and MOSS 2007 where only the first column in a multi-column \"ORDER BY\" is respected.</p>\n\n<p>I entered this topic in the MSDN Forums for SharePoint Search, but have not received any replies:</p>\n\n<p><a href=\"http://social.msdn.microsoft.com/Forums/en-US/sharepointsearch/thread/489b4f29-4155-4c3b-b493-b2fad687ee56\" rel=\"nofollow noreferrer\">http://social.msdn.microsoft.com/Forums/en-US/sharepointsearch/thread/489b4f29-4155-4c3b-b493-b2fad687ee56</a></p>\n" }, { "answer_id": 820025, "author": "mchestnut", "author_id": 60752, "author_profile": "https://Stackoverflow.com/users/60752", "pm_score": 3, "selected": true, "text": "<p>Microsoft <em>finally</em> posted a knowledge base article about this issue.</p>\n\n<p>\"When using RANK in the ORDER BY clause of a SharePoint Search query, no other properties should be used\"</p>\n\n<p><a href=\"http://support.microsoft.com/kb/970830\" rel=\"nofollow noreferrer\">http://support.microsoft.com/kb/970830</a></p>\n\n<p>Symptom: When using RANK in the ORDER BY clause of a SharePoint Search query only the first ORDER BY column is used in the results. </p>\n\n<p>Cause: RANK is a special property that is ranked in the full text index and hence cannot be used with other managed properties. </p>\n\n<p>Resolution: Do not use multiple properties in conjunction with the RANK property. </p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91800", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15682/" ]
I'm using a FullTextSqlQuery in SharePoint 2007 (MOSS) and need to order the results by two columns: ``` SELECT WorkId FROM SCOPE() ORDER BY Author ASC, Rank DESC ``` However it seems that only the first column from ORDER BY is taken into account when returning results. In this case the results are ordered correctly by Author, but not by Rank. If I change the order the results will be ordered by Rank, but not by Author. I had to resort to my own sorting of the results, which I don't like very much. Has anybody a solution to this? **Edit**: Unfortunately it also doesn't accept expressions in the ORDER BY clause (SharePoint throws an exception). My guess is that even if the query looks like legitimate SQL it is parsed somehow before being served to the SQL server. I tried to catch the query with SQL Profiler, but to no avail. **Edit 2**: In the end I used ordering by a single column (Author in my case, since it's the most important) and did the second ordering in code on the TOP N of the results. Works good enough for the project, but leaves a bad feeling of kludgy code.
Microsoft *finally* posted a knowledge base article about this issue. "When using RANK in the ORDER BY clause of a SharePoint Search query, no other properties should be used" <http://support.microsoft.com/kb/970830> Symptom: When using RANK in the ORDER BY clause of a SharePoint Search query only the first ORDER BY column is used in the results. Cause: RANK is a special property that is ranked in the full text index and hence cannot be used with other managed properties. Resolution: Do not use multiple properties in conjunction with the RANK property.
91,810
<p>Working with python interactively, it's sometimes necessary to display a result which is some arbitrarily complex data structure (like lists with embedded lists, etc.) The default way to display them is just one massive linear dump which just wraps over and over and you have to parse carefully to read it.</p> <p>Is there something that will take any python object and display it in a more rational manner. e.g.</p> <pre><code>[0, 1, [a, b, c], 2, 3, 4] </code></pre> <p>instead of:</p> <pre><code>[0, 1, [a, b, c], 2, 3, 4] </code></pre> <p>I know that's not a very good example, but I think you get the idea.</p>
[ { "answer_id": 91818, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 6, "selected": true, "text": "<pre><code>from pprint import pprint\na = [0, 1, ['a', 'b', 'c'], 2, 3, 4]\npprint(a)\n</code></pre>\n\n<p>Note that for a short list like my example, pprint will in fact print it all on one line. However, for more complex structures it does a pretty good job of pretty printing data.</p>\n" }, { "answer_id": 91972, "author": "Gregg Lind", "author_id": 15842, "author_profile": "https://Stackoverflow.com/users/15842", "pm_score": 2, "selected": false, "text": "<p>Another good option is to use <a href=\"http://ipython.scipy.org/moin/\" rel=\"nofollow noreferrer\">IPython</a>, which is an interactive environment with a lot of extra features, including automatic pretty printing, tab-completion of methods, easy shell access, and a lot more. It's also very easy to install. </p>\n\n<p><a href=\"http://ipython.scipy.org/doc/manual/html/interactive/tutorial.html\" rel=\"nofollow noreferrer\">IPython tutorial</a></p>\n" }, { "answer_id": 92260, "author": "rjmunro", "author_id": 3408, "author_profile": "https://Stackoverflow.com/users/3408", "pm_score": 4, "selected": false, "text": "<p>Somtimes <a href=\"http://pyyaml.org/\" rel=\"noreferrer\">YAML</a> can be good for this.</p>\n\n<pre><code>import yaml\na = [0, 1, ['a', 'b', 'c'], 2, 3, 4]\nprint yaml.dump(a)\n</code></pre>\n\n<p>Produces:</p>\n\n<pre><code>- 0\n- 1\n- [a, b, c]\n- 2\n- 3\n- 4\n</code></pre>\n" }, { "answer_id": 93312, "author": "AdamKG", "author_id": 16361, "author_profile": "https://Stackoverflow.com/users/16361", "pm_score": 3, "selected": false, "text": "<p>In addition to <code>pprint.pprint</code>, <code>pprint.pformat</code> is really useful for making readable <code>__repr__</code>s. My complex <code>__repr__</code>s usually look like so:</p>\n\n<pre><code>def __repr__(self):\n from pprint import pformat\n\n return \"&lt;ClassName %s&gt;\" % pformat({\"attrs\":self.attrs,\n \"that_i\":self.that_i,\n \"care_about\":self.care_about})\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4086/" ]
Working with python interactively, it's sometimes necessary to display a result which is some arbitrarily complex data structure (like lists with embedded lists, etc.) The default way to display them is just one massive linear dump which just wraps over and over and you have to parse carefully to read it. Is there something that will take any python object and display it in a more rational manner. e.g. ``` [0, 1, [a, b, c], 2, 3, 4] ``` instead of: ``` [0, 1, [a, b, c], 2, 3, 4] ``` I know that's not a very good example, but I think you get the idea.
``` from pprint import pprint a = [0, 1, ['a', 'b', 'c'], 2, 3, 4] pprint(a) ``` Note that for a short list like my example, pprint will in fact print it all on one line. However, for more complex structures it does a pretty good job of pretty printing data.
91,817
<p>I discovered that you can start your variable name with a '@' character in C#. In my C# project I was using a web service (I added a web reference to my project) that was written in Java. One of the interface objects defined in the WSDL had a member variable with the name "params". Obviously this is a reserved word in C# so you can't have a class with a member variable with the name "params". The proxy object that was generated contained a property that looked like this:</p> <pre><code>public ArrayList @params { get { return this.paramsField; } set { this.paramsField = value; } } </code></pre> <p>I searched through the VS 2008 c# documentation but couldn't find anything about it. Also searching Google didn't give me any useful answers. So what is the exact meaning or use of the '@' character in a variable/property name?</p>
[ { "answer_id": 91822, "author": "rslite", "author_id": 15682, "author_profile": "https://Stackoverflow.com/users/15682", "pm_score": 6, "selected": false, "text": "<p>It just lets you use a reserved word as a variable name. Not recommended IMHO (except in cases like you have).</p>\n" }, { "answer_id": 91829, "author": "Mark Embling", "author_id": 6844, "author_profile": "https://Stackoverflow.com/users/6844", "pm_score": 3, "selected": false, "text": "<p>It simply allows you to use reserved words as variable names. I wanted a var called <code>event</code> the other day. I was going to go with <code>_event</code> instead, but my colleague reminded me that I could just call it <code>@event</code> instead.</p>\n" }, { "answer_id": 91888, "author": "Tomer Gabel", "author_id": 11558, "author_profile": "https://Stackoverflow.com/users/11558", "pm_score": 5, "selected": false, "text": "<p>In C# the at (@) character is used to denote literals that explicitly do not adhere to the relevant rules in the language spec.</p>\n\n<p>Specifically, it can be used for variable names that clash with reserved keywords (e.g. you can't use params but you can use @params instead, same with out/ref/any other keyword in the language specification). Additionally it can be used for unescaped string literals; this is particularly relevant with path constants, e.g. instead of <code>path = \"c:\\\\temp\\\\somefile.txt\"</code> you can write <code>path = @\"c:\\temp\\somefile.txt\"</code>. It's also really useful for regular expressions.</p>\n" }, { "answer_id": 92045, "author": "Atif Aziz", "author_id": 6682, "author_profile": "https://Stackoverflow.com/users/6682", "pm_score": 9, "selected": true, "text": "<p>Straight from the <a href=\"https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/\" rel=\"noreferrer\">C# Language Specification</a>, <a href=\"https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/lexical-structure#identifiers\" rel=\"noreferrer\">Identifiers (C#)</a>\n:</p>\n\n<blockquote>\n <p>The prefix \"@\" enables the use of\n keywords as identifiers, which is\n useful when interfacing with other\n programming languages. The character @\n is not actually part of the\n identifier, so the identifier might be\n seen in other languages as a normal\n identifier, without the prefix. An\n identifier with an @ prefix is called\n a verbatim identifier.</p>\n</blockquote>\n" }, { "answer_id": 580748, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>If we use a keyword as the name for an identifier, we get a compiler error “identifier expected, ‘Identifier Name’ is a keyword”\nTo overcome this error, prefix the identifier with “@”. Such identifiers are verbatim identifiers.\nThe character @ is not actually part of the identifier, so the identifier might be seen in other languages as a normal identifier, without the prefix</p>\n" }, { "answer_id": 14893191, "author": "Colonel Panic", "author_id": 284795, "author_profile": "https://Stackoverflow.com/users/284795", "pm_score": 4, "selected": false, "text": "<p>Unlike Perl's sigils, an <code>@</code> prefix before a variable name in C# has no meaning. If <code>x</code> is a variable, <code>@x</code> is another name for the same variable.</p>\n\n<pre><code>&gt; string x = \"abc\";\n&gt; Object.ReferenceEquals(x, @x).Dump();\nTrue\n</code></pre>\n\n<p>But the <code>@</code> prefix does have a <em>use</em>, as you've discovered - you can use it to clarify variables names that C# would otherwise reject as illegal. </p>\n\n<pre><code>&gt; string string;\nIdentifier expected; 'string' is a keyword\n\n&gt; string @string;\n</code></pre>\n" }, { "answer_id": 20358051, "author": "BartoszKP", "author_id": 2642204, "author_profile": "https://Stackoverflow.com/users/2642204", "pm_score": 2, "selected": false, "text": "<p>Another use case are extension methods. The first, special parameter can be distinguished to denote its real meaning with <code>@this</code> name. An example:</p>\n\n<pre><code>public static TValue GetValueOrDefault&lt;TKey, TValue&gt;(\n this IDictionary&lt;TKey, TValue&gt; @this,\n TKey key,\n TValue defaultValue)\n {\n if ([email protected](key))\n {\n return defaultValue;\n }\n\n return @this[key];\n }\n</code></pre>\n" }, { "answer_id": 21798798, "author": "Mina Gabriel", "author_id": 1410185, "author_profile": "https://Stackoverflow.com/users/1410185", "pm_score": 1, "selected": false, "text": "<p>You can use it to use the reserved keywords as variable name like </p>\n\n<pre><code> int @int = 3; \n</code></pre>\n\n<p>the compiler will ignores the <code>@</code> and compile the variable as <code>int</code> </p>\n\n<p>it is not a common practice to use thought </p>\n" }, { "answer_id": 22838275, "author": "Umar Abbas", "author_id": 1482460, "author_profile": "https://Stackoverflow.com/users/1482460", "pm_score": 4, "selected": false, "text": "<p>The <code>@</code> symbol allows you to use reserved keywords for variable name. like <code>@int</code>, <code>@string</code>, <code>@double</code> etc.</p>\n\n<p>For example:</p>\n\n<pre><code>string @public = \"Reserved Keyword used for me and its fine\";\n</code></pre>\n\n<p>The above code works fine, but below will not work:</p>\n\n<pre><code>string public = \"This will not compile\";\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91817", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13287/" ]
I discovered that you can start your variable name with a '@' character in C#. In my C# project I was using a web service (I added a web reference to my project) that was written in Java. One of the interface objects defined in the WSDL had a member variable with the name "params". Obviously this is a reserved word in C# so you can't have a class with a member variable with the name "params". The proxy object that was generated contained a property that looked like this: ``` public ArrayList @params { get { return this.paramsField; } set { this.paramsField = value; } } ``` I searched through the VS 2008 c# documentation but couldn't find anything about it. Also searching Google didn't give me any useful answers. So what is the exact meaning or use of the '@' character in a variable/property name?
Straight from the [C# Language Specification](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/), [Identifiers (C#)](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/lexical-structure#identifiers) : > > The prefix "@" enables the use of > keywords as identifiers, which is > useful when interfacing with other > programming languages. The character @ > is not actually part of the > identifier, so the identifier might be > seen in other languages as a normal > identifier, without the prefix. An > identifier with an @ prefix is called > a verbatim identifier. > > >
91,821
<p>I have a model class:</p> <pre><code>class Person(db.Model): first_name = db.StringProperty(required=True) last_name = db.StringProperty(required=True) </code></pre> <p>I have an instance of this class in <code>p</code>, and string <code>s</code> contains the value <code>'first_name'</code>. I would like to do something like:</p> <pre><code>print p[s] </code></pre> <p>and </p> <pre><code>p[s] = new_value </code></pre> <p>Both of which result in a <code>TypeError</code>.</p> <p>Does anybody know how I can achieve what I would like?</p>
[ { "answer_id": 91859, "author": "Jim", "author_id": 8427, "author_profile": "https://Stackoverflow.com/users/8427", "pm_score": 1, "selected": false, "text": "<pre><code>getattr(p, s)\nsetattr(p, s, new_value)\n</code></pre>\n" }, { "answer_id": 91911, "author": "Jim", "author_id": 8427, "author_profile": "https://Stackoverflow.com/users/8427", "pm_score": 1, "selected": false, "text": "<p>Try:</p>\n\n<pre><code>p.model_properties()[s].get_value_for_datastore(p)\n</code></pre>\n\n<p>See <a href=\"http://code.google.com/appengine/docs/datastore/propertyclass.html#Property_get_value_for_datastore\" rel=\"nofollow noreferrer\">the documentation</a>.</p>\n" }, { "answer_id": 91970, "author": "Antti Rasinen", "author_id": 8570, "author_profile": "https://Stackoverflow.com/users/8570", "pm_score": 3, "selected": false, "text": "<p>If the model class is sufficiently intelligent, it should recognize the standard Python ways of doing this.</p>\n\n<p>Try:</p>\n\n<pre><code>getattr(p, s)\nsetattr(p, s, new_value)\n</code></pre>\n\n<p>There is also hasattr available.</p>\n" }, { "answer_id": 97760, "author": "David Sykes", "author_id": 3154, "author_profile": "https://Stackoverflow.com/users/3154", "pm_score": 2, "selected": false, "text": "<p>With much thanks to Jim, the exact solution I was looking for is:</p>\n\n<pre><code>p.properties()[s].get_value_for_datastore(p)\n</code></pre>\n\n<p>To all the other respondents, thank you for your help. I also would have expected the Model class to implement the python standard way of doing this, but for whatever reason, it doesn't.</p>\n" }, { "answer_id": 169899, "author": "JJ.", "author_id": 9106, "author_profile": "https://Stackoverflow.com/users/9106", "pm_score": -1, "selected": false, "text": "<p>p.first_name = \"New first name\"\np.put()</p>\n\n<p>or p = Person(first_name = \"Firsty\",\n last_name = \"Lasty\" )\np.put()</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91821", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3154/" ]
I have a model class: ``` class Person(db.Model): first_name = db.StringProperty(required=True) last_name = db.StringProperty(required=True) ``` I have an instance of this class in `p`, and string `s` contains the value `'first_name'`. I would like to do something like: ``` print p[s] ``` and ``` p[s] = new_value ``` Both of which result in a `TypeError`. Does anybody know how I can achieve what I would like?
If the model class is sufficiently intelligent, it should recognize the standard Python ways of doing this. Try: ``` getattr(p, s) setattr(p, s, new_value) ``` There is also hasattr available.
91,826
<p>Is there a version of FitNesse that works on Delphi 2006/2007/2009?</p> <p>If so where can I find It?</p> <p>Are there any other programs like FitNesse that work on Delphi 2006?</p>
[ { "answer_id": 91859, "author": "Jim", "author_id": 8427, "author_profile": "https://Stackoverflow.com/users/8427", "pm_score": 1, "selected": false, "text": "<pre><code>getattr(p, s)\nsetattr(p, s, new_value)\n</code></pre>\n" }, { "answer_id": 91911, "author": "Jim", "author_id": 8427, "author_profile": "https://Stackoverflow.com/users/8427", "pm_score": 1, "selected": false, "text": "<p>Try:</p>\n\n<pre><code>p.model_properties()[s].get_value_for_datastore(p)\n</code></pre>\n\n<p>See <a href=\"http://code.google.com/appengine/docs/datastore/propertyclass.html#Property_get_value_for_datastore\" rel=\"nofollow noreferrer\">the documentation</a>.</p>\n" }, { "answer_id": 91970, "author": "Antti Rasinen", "author_id": 8570, "author_profile": "https://Stackoverflow.com/users/8570", "pm_score": 3, "selected": false, "text": "<p>If the model class is sufficiently intelligent, it should recognize the standard Python ways of doing this.</p>\n\n<p>Try:</p>\n\n<pre><code>getattr(p, s)\nsetattr(p, s, new_value)\n</code></pre>\n\n<p>There is also hasattr available.</p>\n" }, { "answer_id": 97760, "author": "David Sykes", "author_id": 3154, "author_profile": "https://Stackoverflow.com/users/3154", "pm_score": 2, "selected": false, "text": "<p>With much thanks to Jim, the exact solution I was looking for is:</p>\n\n<pre><code>p.properties()[s].get_value_for_datastore(p)\n</code></pre>\n\n<p>To all the other respondents, thank you for your help. I also would have expected the Model class to implement the python standard way of doing this, but for whatever reason, it doesn't.</p>\n" }, { "answer_id": 169899, "author": "JJ.", "author_id": 9106, "author_profile": "https://Stackoverflow.com/users/9106", "pm_score": -1, "selected": false, "text": "<p>p.first_name = \"New first name\"\np.put()</p>\n\n<p>or p = Person(first_name = \"Firsty\",\n last_name = \"Lasty\" )\np.put()</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91826", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17560/" ]
Is there a version of FitNesse that works on Delphi 2006/2007/2009? If so where can I find It? Are there any other programs like FitNesse that work on Delphi 2006?
If the model class is sufficiently intelligent, it should recognize the standard Python ways of doing this. Try: ``` getattr(p, s) setattr(p, s, new_value) ``` There is also hasattr available.
91,831
<p>Say I have the following web.config:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;configuration&gt; &lt;system.web&gt; &lt;authentication mode="Windows"&gt;&lt;/authentication&gt; &lt;/system.web&gt; &lt;/configuration&gt; </code></pre> <p>Using ASP.NET C#, how can I detect the Mode value of the Authentication tag?</p>
[ { "answer_id": 91836, "author": "redsquare", "author_id": 6440, "author_profile": "https://Stackoverflow.com/users/6440", "pm_score": 3, "selected": true, "text": "<p>Try <code>Context.User.Identity.AuthenticationType</code></p>\n\n<p>Go for PB's answer folks</p>\n" }, { "answer_id": 91842, "author": "Paul van Brenk", "author_id": 1837197, "author_profile": "https://Stackoverflow.com/users/1837197", "pm_score": 5, "selected": false, "text": "<p>The mode property from the authenticationsection: <a href=\"http://msdn.microsoft.com/en-us/library/system.web.configuration.authenticationsection.mode(VS.80).aspx\" rel=\"noreferrer\">AuthenticationSection.Mode Property (System.Web.Configuration)</a>. And you can even modify it.</p>\n\n<pre><code>// Get the current Mode property.\nAuthenticationMode currentMode = \n authenticationSection.Mode;\n\n// Set the Mode property to Windows.\nauthenticationSection.Mode = \n AuthenticationMode.Windows;\n</code></pre>\n\n<p>This article describes <a href=\"http://msdn.microsoft.com/en-us/library/system.web.configuration.authenticationsection(VS.80).aspx\" rel=\"noreferrer\">how to get a reference to the AuthenticationSection</a>.</p>\n" }, { "answer_id": 91898, "author": "timvw", "author_id": 15267, "author_profile": "https://Stackoverflow.com/users/15267", "pm_score": -1, "selected": false, "text": "<p>use an xpath query //configuration/system.web/authentication[mode] ?</p>\n\n<pre><code>protected void Page_Load(object sender, EventArgs e)\n{\n XmlDocument config = new XmlDocument();\n config.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);\n XmlNode node = config.SelectSingleNode(\"//configuration/system.web/authentication\");\n this.Label1.Text = node.Attributes[\"mode\"].Value;\n}\n</code></pre>\n" }, { "answer_id": 7054094, "author": "bkaid", "author_id": 265570, "author_profile": "https://Stackoverflow.com/users/265570", "pm_score": 4, "selected": false, "text": "<p>Import the <code>System.Web.Configuration</code> namespace and do something like:</p>\n\n<pre><code>var configuration = WebConfigurationManager.OpenWebConfiguration(\"/\");\nvar authenticationSection = (AuthenticationSection)configuration.GetSection(\"system.web/authentication\");\nif (authenticationSection.Mode == AuthenticationMode.Forms)\n{\n //do something\n}\n</code></pre>\n" }, { "answer_id": 39698844, "author": "clD", "author_id": 1533273, "author_profile": "https://Stackoverflow.com/users/1533273", "pm_score": 3, "selected": false, "text": "<p>You can also get the authentication mode by using the static <a href=\"https://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager(v=vs.110).aspx\" rel=\"nofollow noreferrer\"><code>ConfigurationManager</code></a> class to get the section and then the enum <code>AuthenticationMode</code>.</p>\n\n<pre><code>AuthenticationMode authMode = ((AuthenticationSection) ConfigurationManager.GetSection(\"system.web/authentication\")).Mode;\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/questions/698157/whats-the-difference-between-the-webconfigurationmanager-and-the-configurationm\">The difference between WebConfigurationManager and ConfigurationManager</a></p>\n\n<hr>\n\n<p>If you want to retrieve the name of the constant in the specified enumeration you can do this by using the <code>Enum.GetName(Type, Object)</code> method</p>\n\n<pre><code>Enum.GetName(typeof(AuthenticationMode), authMode); // e.g. \"Windows\"\n</code></pre>\n" }, { "answer_id": 69190778, "author": "SZL", "author_id": 2278037, "author_profile": "https://Stackoverflow.com/users/2278037", "pm_score": 0, "selected": false, "text": "<p>In ASP.Net Core you can use this:</p>\n<pre><code>public Startup(IHostingEnvironment env, IConfiguration config)\n{\n var enabledAuthTypes = config[&quot;IIS_HTTPAUTH&quot;].Split(';').Where(l =&gt; !String.IsNullOrWhiteSpace(l)).ToList();\n}\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91831", "https://Stackoverflow.com", "https://Stackoverflow.com/users/383/" ]
Say I have the following web.config: ``` <?xml version="1.0" encoding="utf-8"?> <configuration> <system.web> <authentication mode="Windows"></authentication> </system.web> </configuration> ``` Using ASP.NET C#, how can I detect the Mode value of the Authentication tag?
Try `Context.User.Identity.AuthenticationType` Go for PB's answer folks
91,856
<p>Would the following SQL remove also the index - or does it have to be removed separately?</p> <pre><code>CREATE TABLE #Tbl (field int) CREATE NONCLUSTERED INDEX idx ON #Tbl (field) DROP TABLE #Tbl </code></pre>
[ { "answer_id": 91863, "author": "Nick Craver", "author_id": 13249, "author_profile": "https://Stackoverflow.com/users/13249", "pm_score": 3, "selected": false, "text": "<p>It will be removed automatically, as there is nothing left to index. Think of it as a child object in this respect.</p>\n" }, { "answer_id": 91879, "author": "sdkpoly", "author_id": 15640, "author_profile": "https://Stackoverflow.com/users/15640", "pm_score": 6, "selected": true, "text": "<p>Yes they are. You can search in MSSQL help for CREATE INDEX article it is said there:</p>\n\n<blockquote>\n <p>\"Indexes can be created on a temporary\n table. When the table is dropped or\n the session ends, all indexes and\n triggers are dropped.\"</p>\n</blockquote>\n" }, { "answer_id": 91883, "author": "James Boother", "author_id": 16030, "author_profile": "https://Stackoverflow.com/users/16030", "pm_score": 2, "selected": false, "text": "<p>The drop table will remove the index. Drop Index takes the index name and the table name. </p>\n\n<p>In this case would be DROP INDEX idc ON #tbl</p>\n\n<p>which can be called if you want to drop the index but leave the table.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2133/" ]
Would the following SQL remove also the index - or does it have to be removed separately? ``` CREATE TABLE #Tbl (field int) CREATE NONCLUSTERED INDEX idx ON #Tbl (field) DROP TABLE #Tbl ```
Yes they are. You can search in MSSQL help for CREATE INDEX article it is said there: > > "Indexes can be created on a temporary > table. When the table is dropped or > the session ends, all indexes and > triggers are dropped." > > >
91,899
<p>I'm using grep to generate a list of files I need to move:</p> <pre><code>grep -L -r 'Subject: \[SPAM\]' . </code></pre> <p>How can I pass this list to the mv command and move the files somewhere else?</p>
[ { "answer_id": 91901, "author": "Confusion", "author_id": 16784, "author_profile": "https://Stackoverflow.com/users/16784", "pm_score": -1, "selected": false, "text": "<p>You can pass the result to the next command by using\ngrep ... | xargs mv {} destination</p>\n\n<p>Check man xargs for more info.</p>\n" }, { "answer_id": 91954, "author": "e-satis", "author_id": 9951, "author_profile": "https://Stackoverflow.com/users/9951", "pm_score": 1, "selected": false, "text": "<p>There are several ways but here is a slow but failsafe one :</p>\n\n<pre><code>IFS=$'\\n'; # set the field separator to line break\nfor $mail in $(grep -L -r 'Subject: \\[SPAM\\]' .); do mv \"$mail\" your_dir; done;\nIFS=' '; # restore FS\n</code></pre>\n" }, { "answer_id": 91965, "author": "daveb", "author_id": 11858, "author_profile": "https://Stackoverflow.com/users/11858", "pm_score": 7, "selected": true, "text": "<p>If you want to find and move files that do not match your pattern (move files that don't contain <code>'Subject \\[SPAM\\]'</code> in this example) use:</p>\n<pre><code>grep -L -Z -r 'Subject: \\[SPAM\\]' . | xargs -0 -I{} mv {} DIR\n</code></pre>\n<p>The -Z means output with zeros (\\0) after the filenames (so spaces are not used as delimeters).</p>\n<pre><code>xargs -0\n</code></pre>\n<p>means interpret \\0 to be delimiters.</p>\n<p>The -L means find files that do not match the pattern. Replace <code>-L</code> with <code>-l</code> if you want to move files that match your pattern.</p>\n<p>Then</p>\n<pre><code>-I{} mv {} DIR\n</code></pre>\n<p>means replace <code>{}</code> with the filenames, so you get <code>mv filenames DIR</code>.</p>\n" }, { "answer_id": 92007, "author": "Tobias Kunze", "author_id": 6070, "author_profile": "https://Stackoverflow.com/users/6070", "pm_score": 5, "selected": false, "text": "<p>This alternative works where xargs is not availabe:</p>\n\n<pre><code>grep -L -r 'Subject: \\[SPAM\\]' . | while read f; do mv \"$f\" out; done\n</code></pre>\n" }, { "answer_id": 2945731, "author": "Brad Vokey", "author_id": 354860, "author_profile": "https://Stackoverflow.com/users/354860", "pm_score": 4, "selected": false, "text": "<p>This is what I use in Fedora Core 12:</p>\n\n<pre><code>grep -l 'Subject: \\[SPAM\\]' | xargs -I '{}' mv '{}' DIR\n</code></pre>\n" }, { "answer_id": 9275611, "author": "Ritz", "author_id": 1208880, "author_profile": "https://Stackoverflow.com/users/1208880", "pm_score": 2, "selected": false, "text": "<p>Maybe this will work:</p>\n\n<pre><code>mv $(grep -l 'Subject: \\[SPAM\\]' | awk -F ':' '{print $1}') your_file\n</code></pre>\n" }, { "answer_id": 25688793, "author": "Mike Castro Demaria", "author_id": 902279, "author_profile": "https://Stackoverflow.com/users/902279", "pm_score": 0, "selected": false, "text": "<p>Work perfect fo me : </p>\n\n<ul>\n<li><p>move files who contain the text withe the word MYSTRINGTOSEARCH to directory MYDIR.</p>\n\n<p>find . -type f -exec grep -il 'MYSTRINGTOSEARCH' {} \\; -exec mv {} MYDIR/ \\;</p></li>\n</ul>\n\n<p>I hope this helps</p>\n" }, { "answer_id": 29429932, "author": "vladkras", "author_id": 1713660, "author_profile": "https://Stackoverflow.com/users/1713660", "pm_score": 3, "selected": false, "text": "<p>This is what helped me:</p>\n\n<p><code>grep -lir 'spam' ./ | xargs mv -t ../spam</code></p>\n\n<p>Of course, I was already in required folder (that's why <code>./</code>) and moved them to neighboring folder. But you can change them to any paths.</p>\n\n<p>I don't know why accepted answer didn't work. Also I didn't have spaces and special characters in filenames - maybe this will not work.</p>\n\n<p>Stolen here: <a href=\"https://unix.stackexchange.com/a/56906\">Grep command to find files containing text string and move them</a></p>\n" }, { "answer_id": 32498852, "author": "Loukan ElKadi", "author_id": 5320562, "author_profile": "https://Stackoverflow.com/users/5320562", "pm_score": 2, "selected": false, "text": "<pre><code>mv `grep -L -r 'Subject: \\[SPAM\\]' .` &lt;directory_path&gt;\n</code></pre>\n\n<p>Assuming that the grep you wrote returns the files paths you're expecting.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91899", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17582/" ]
I'm using grep to generate a list of files I need to move: ``` grep -L -r 'Subject: \[SPAM\]' . ``` How can I pass this list to the mv command and move the files somewhere else?
If you want to find and move files that do not match your pattern (move files that don't contain `'Subject \[SPAM\]'` in this example) use: ``` grep -L -Z -r 'Subject: \[SPAM\]' . | xargs -0 -I{} mv {} DIR ``` The -Z means output with zeros (\0) after the filenames (so spaces are not used as delimeters). ``` xargs -0 ``` means interpret \0 to be delimiters. The -L means find files that do not match the pattern. Replace `-L` with `-l` if you want to move files that match your pattern. Then ``` -I{} mv {} DIR ``` means replace `{}` with the filenames, so you get `mv filenames DIR`.
91,905
<p>I want to add a mailto link on our web page. I want to add a urgent priority to this mail.</p>
[ { "answer_id": 91921, "author": "Robit", "author_id": 17026, "author_profile": "https://Stackoverflow.com/users/17026", "pm_score": 4, "selected": true, "text": "<p>mailto links just doesn't support this feature , sorry.</p>\n\n<p>however, you could use a specific subject and filter it in your inbox</p>\n\n<pre><code>&lt;a href=\"mailto:[email protected]?subject=Urgent\"&gt;Send a email&lt;/a&gt; \n</code></pre>\n" }, { "answer_id": 91936, "author": "Amir Arad", "author_id": 11813, "author_profile": "https://Stackoverflow.com/users/11813", "pm_score": 1, "selected": false, "text": "<p>I guess if such a feature exist it's browser-specific.</p>\n\n<p><a href=\"http://www.w3.org/TR/WD-html40-970917/htmlweb.html\" rel=\"nofollow noreferrer\">from w3's website:</a></p>\n\n<blockquote>\n <p>User agents may support MAILTO URL\n extensions that are not yet Internet\n standards (e.g., appending subject\n information to a URL with the syntax\n \"?Subject=my%20subject\" where any\n space characters are replaced by\n \"%20\"). Some user agents also support\n \"?Cc=email-address\".</p>\n</blockquote>\n" }, { "answer_id": 91948, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>It can't be done.</p>\n" }, { "answer_id": 91974, "author": "Garth Kidd", "author_id": 5700, "author_profile": "https://Stackoverflow.com/users/5700", "pm_score": 2, "selected": false, "text": "<p>You can get your priority, but probably not that way. </p>\n\n<p>Most mail clients honor <code>subject=</code> and <code>body=</code> in the query string of a <code>mailto:</code> link. Some mail clients treat multiple <code>body=</code> attributes as different lines; others only use the last <code>body</code>. Getting to your point, though: <strong>I don't think most clients will let you set priority</strong>, and it only takes <em>one</em> client that won't do it to make your system unreliable. </p>\n\n<p>The easiest approach is to <strong>use mail filters to set priority on inbound mail</strong>. The filters should set the priority based on the subject lines, which you <em>can</em> reliably control. </p>\n\n<p>If your mail system's filters can't set priority, try sorting to different mail folders. </p>\n" }, { "answer_id": 92201, "author": "ceejayoz", "author_id": 1902010, "author_profile": "https://Stackoverflow.com/users/1902010", "pm_score": 2, "selected": false, "text": "<p>You can't do this with a mailto: link, but you could create a server-side contact form that sends the e-mail out with the proper headers.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91905", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17584/" ]
I want to add a mailto link on our web page. I want to add a urgent priority to this mail.
mailto links just doesn't support this feature , sorry. however, you could use a specific subject and filter it in your inbox ``` <a href="mailto:[email protected]?subject=Urgent">Send a email</a> ```
91,932
<p>How does it work, what is it used for and when should one use it?</p>
[ { "answer_id": 91961, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 3, "selected": false, "text": "<p>Directly from the <a href=\"http://en.wikipedia.org/wiki/Strategy_pattern\" rel=\"nofollow noreferrer\">Strategy Pattern Wikipedia article</a>:</p>\n\n<blockquote>\n <p>The strategy pattern is useful for situations where it is necessary to dynamically swap the algorithms used in an application. The strategy pattern is intended to provide a means to define a family of algorithms, encapsulate each one as an object, and make them interchangeable. The strategy pattern lets the algorithms vary independently from clients that use them.</p>\n</blockquote>\n" }, { "answer_id": 92108, "author": "e-satis", "author_id": 9951, "author_profile": "https://Stackoverflow.com/users/9951", "pm_score": 7, "selected": true, "text": "<p>Let's explain the strategy pattern the easy way:</p>\n\n<p>You have a class <code>Car()</code> with a method <code>run()</code>, so you use it this way in a pseudo language:</p>\n\n<pre><code>mycar = new Car()\nmycar.run()\n</code></pre>\n\n<p>Now, you may want to change the <code>run()</code> behavior on the fly, while the program is executing. For example, you might want to simulate a motor failure or the use of a \"boost\" button in a video game.</p>\n\n<p>There are several ways to do this simulation: using conditional statements and a flag variable is one way. The strategy pattern is another: it delegates the behavior of the <code>run()</code> method to another class:</p>\n\n<pre><code>Class Car()\n{\n this.motor = new Motor(this) \n\n // passing \"this\" is important for the motor so it knows what it is running\n\n method run()\n {\n this.motor.run()\n }\n\n method changeMotor(motor)\n {\n this.motor = motor \n }\n\n}\n</code></pre>\n\n<p>If you want to change the car's behavior, you can just change the motor. (Easier in a program than in real life, right? ;-) )</p>\n\n<p>It's very useful if you have a lot of complex states: you can change and maintain them much more easily.</p>\n" }, { "answer_id": 95008, "author": "Jorge Córdoba", "author_id": 2695, "author_profile": "https://Stackoverflow.com/users/2695", "pm_score": 5, "selected": false, "text": "<h2>Problem</h2>\n\n<p>The strategy pattern is used to solve problems that might (or is foreseen they might) be implemented or solved by different <strong>strategies</strong> and that possess a clearly defined interface for such cases. Each strategy is perfectly valid on its own with some of the strategies being preferable in certain situations that allow the application to switch between them during runtime.</p>\n\n<h2>Code Example</h2>\n\n<pre class=\"lang-cs prettyprint-override\"><code>namespace StrategyPatterns\n{\n // Interface definition for a Sort algorithm\n public interface ISort\n {\n void Sort(List&lt;string&gt; list)\n }\n\n // QuickSort implementation\n public class CQuickSorter : ISort\n {\n void Sort(List&lt;string&gt; list)\n {\n // Here will be the actual implementation\n }\n }\n\n // BubbleSort implementation\n public class CBubbleSort : ISort\n {\n void Sort(List&lt;string&gt; list)\n {\n // The actual implementation of the sort\n }\n }\n\n // MergeSort implementation\n public class CMergeSort : ISort\n {\n void Sort(List&lt;string&gt; list)\n {\n // Again the real implementation comes here\n }\n }\n\n public class Context\n {\n private ISort sorter;\n\n public Context(ISort sorter)\n {\n // We pass to the context the strategy to use\n this.sorter = sorter;\n }\n\n public ISort Sorter\n {\n get{return sorter;)\n }\n }\n\n public class MainClass\n {\n static void Main()\n {\n List&lt;string&gt; myList = new List&lt;string&gt;();\n\n myList.Add(\"Hello world\");\n myList.Add(\"Another item\");\n myList.Add(\"Item item\");\n\n Context cn = new Context(new CQuickSorter());\n // Sort using the QuickSort strategy\n cn.Sorter.Sort(myList);\n myList.Add(\"This one goes for the mergesort\");\n cn = new Context(new CMergeSort());\n // Sort using the merge sort strategy\n cn.Sorter.Sort(myList);\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 171647, "author": "Andrew Swan", "author_id": 10433, "author_profile": "https://Stackoverflow.com/users/10433", "pm_score": 3, "selected": false, "text": "<p>A closely related pattern is the Delegate pattern; in both cases, some of the work is passed to some other component. If I understand correctly, the difference between these patterns is this (and please correct me if I'm wrong):</p>\n\n<ul>\n<li><p>In the <strong>Delegate</strong> pattern, the delegate is instantiated by the enclosing (delegating) class; this allows for code reuse by composition rather than inheritance. The enclosing class may be aware of the delegate's concrete type, e.g. if it invokes its constructor itself (as opposed to using a factory).</p></li>\n<li><p>In the <strong>Strategy</strong> pattern, the component that executes the strategy is a dependency provided to the enclosing (using) component via its constructor or a setter (according to your religion). The using component is totally unaware of what strategy is in use; the strategy is always invoked via an interface.</p></li>\n</ul>\n\n<p>Anyone know any other differences?</p>\n" }, { "answer_id": 171656, "author": "I GIVE CRAP ANSWERS", "author_id": 25083, "author_profile": "https://Stackoverflow.com/users/25083", "pm_score": 3, "selected": false, "text": "<p>To add to the already magnificient answers: The strategy pattern has a strong similarity to passing a function (or functions) to another function. In the strategy this is done by wrapping said function in an object followed by passing the object. Some languages can pass functions directly, so they don't need the pattern at all. But other languages can't pass functions, but <i>can</i> pass objects; the pattern then applies.</p>\n\n<p>Especially in Java-like languages, you will find that the type zoo of the language is pretty small and that your only way to extend it is by creating objects. Hence most solutions to problems is to come up with a pattern; a way to compose objects to achieve a specific goal. Languages with richer type zoos often have simpler ways of going about the problems -- but richer types also means you have to spend more time learning the type system. Languages with dynamic typing discipline often gets a sneaky way around the problem as well.</p>\n" }, { "answer_id": 16725536, "author": "Supermalf", "author_id": 2359285, "author_profile": "https://Stackoverflow.com/users/2359285", "pm_score": 5, "selected": false, "text": "<ul>\n<li>What is a Strategy? A strategy is a plan of action designed to achieve a specific goal;</li>\n<li>“Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.” (Gang of Four);</li>\n<li>Specifies a set of classes, each representing a potential behaviour. Switching between those classes changes the application behaviour. (the Strategy);</li>\n<li>This behaviour can be selected at runtime (using polymorphism) or design time;</li>\n<li>Capture the abstraction in an interface, bury implementation details in derived classes;</li>\n</ul>\n\n<p><img src=\"https://i.stack.imgur.com/cvV4W.png\" alt=\"enter image description here\"></p>\n\n<ul>\n<li>An alternative to the Strategy is to change the application behaviour by using conditional logic. (BAD);</li>\n<li><p>Using this pattern makes it easier to add or remove specific behaviour, without having to recode and retest, all or parts of the application;</p></li>\n<li><p>Good uses:</p>\n\n<ul>\n<li>When we have a set of similar algorithms and its need to switch between them in different parts of the application. With Strategy Pattern is possible to avoid ifs and ease maintenance;</li>\n<li>When we want to add new methods to superclass that don’t necessarily make sense to every subclass. Instead of using an interface in a traditional way, adding the new method, we use an instance variable that is a subclass of the new Functionality interface. This is known as Composition : Instead of inheriting an ability through inheritance the class is composed with Objects with the right ability;</li>\n</ul></li>\n</ul>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2695/" ]
How does it work, what is it used for and when should one use it?
Let's explain the strategy pattern the easy way: You have a class `Car()` with a method `run()`, so you use it this way in a pseudo language: ``` mycar = new Car() mycar.run() ``` Now, you may want to change the `run()` behavior on the fly, while the program is executing. For example, you might want to simulate a motor failure or the use of a "boost" button in a video game. There are several ways to do this simulation: using conditional statements and a flag variable is one way. The strategy pattern is another: it delegates the behavior of the `run()` method to another class: ``` Class Car() { this.motor = new Motor(this) // passing "this" is important for the motor so it knows what it is running method run() { this.motor.run() } method changeMotor(motor) { this.motor = motor } } ``` If you want to change the car's behavior, you can just change the motor. (Easier in a program than in real life, right? ;-) ) It's very useful if you have a lot of complex states: you can change and maintain them much more easily.
91,933
<p>I've been working on a project where I need to iterate through a collection of data and remove entries where the "primary key" is duplicated. I have tried using a</p> <pre><code>List&lt;int&gt; </code></pre> <p>and </p> <pre><code>Dictionary&lt;int, bool&gt; </code></pre> <p>With the dictionary I found slightly better performance, even though I never need the Boolean tagged with each entry. My expectation is that this is because a List allows for indexed access and a Dictionary does not. What I was wondering is, is there a better solution to this problem. I do not need to access the entries again, I only need to track what "primary keys" I have seen and make sure I only perform addition work on entries that have a new primary key. I'm using C# and .NET 2.0. And I have no control over fixing the input data to remove the duplicates from the source (unfortunately!). And so you can have a feel for scaling, overall I'm checking for duplicates about 1,000,000 times in the application, but in subsets of no more than about 64,000 that need to be unique.</p>
[ { "answer_id": 91951, "author": "leppie", "author_id": 15541, "author_profile": "https://Stackoverflow.com/users/15541", "pm_score": 3, "selected": true, "text": "<p>They have added the HashSet class in .NET 3.5. But I guess it will be on par with the Dictionary. If you have less than say a 100 elements a List will probably perform better.</p>\n" }, { "answer_id": 91979, "author": "Jorge Córdoba", "author_id": 2695, "author_profile": "https://Stackoverflow.com/users/2695", "pm_score": 0, "selected": false, "text": "<p>I don't really get what you are asking.</p>\n\n<p>Firstly is just the opposite of what you say. The dictionary has indexed access (is a hash table) while de List hasn't.</p>\n\n<p>If you already have the data in a dictionary then all keys are unique, there can be no duplicates.</p>\n\n<p>I susspect you have the data stored in another data type and you're storing it into the dictionary. If that's the case the inserting the data will work with two dictionarys.</p>\n\n<pre><code>foreach (int key in keys)\n{\n if (!MyDataDict.ContainsKey(key))\n {\n if (!MyDuplicatesDict.ContainsKey(key))\n MyDuplicatesDict.Add(key);\n }\n else\n MyDataDict.Add(key); \n}\n</code></pre>\n" }, { "answer_id": 91993, "author": "Nils Pipenbrinck", "author_id": 15955, "author_profile": "https://Stackoverflow.com/users/15955", "pm_score": 1, "selected": false, "text": "<p><strong>Edit: Nevermind my comment. I thought you're talking about C++. I have no idea if my post is relevant in the C# world..</strong></p>\n\n<p>A hash-table could be a tad faster. Binary trees (that's what used in the dictionary) tend to be relative slow because of the way the memory gets accessed. This is especially true if your tree becomes very large.</p>\n\n<p>However, before you change your data-structure, have you tried to use a custom pool allocator for your dictionary? I bet the time is not spent traversing the tree itself but in the millions of allocations and deallocations the dictionary will do for you.</p>\n\n<p>You may see a factor 10 speed-boost just plugging a simple pool allocator into the dictionary template. Afaik boost has a component that can be directly used.</p>\n\n<p>Another option: If you know only 64.000 entries in your integers exist you can write those to a file and create a perfect hash function for it. That way you can just use the hash function to map your integers into the 0 to 64.000 range and index a bit-array.</p>\n\n<p>Probably the fastest way, but less flexible. You have to redo your perfect hash function (can be done automatically) each time your set of integers changes.</p>\n" }, { "answer_id": 92016, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 0, "selected": false, "text": "<p>If you are checking for uniqueness of integers, and the range of integers is constrained enough then you could just use an array. </p>\n\n<p>For better packing you could implement a bitmap data structure (basically an array, but each int in the array represents 32 ints in the key space by using 1 bit per key). That way if you maximum number is 1,000,000 you only need ~30.5KB of memory for the data structure.</p>\n\n<p>Performs of a bitmap would be O(1) (per check) which is hard to beat.</p>\n" }, { "answer_id": 92056, "author": "rjzii", "author_id": 1185, "author_profile": "https://Stackoverflow.com/users/1185", "pm_score": 0, "selected": false, "text": "<p>There was a question awhile back on <a href=\"https://stackoverflow.com/questions/9673/remove-duplicates-from-array#9763\">removing duplicates from an array</a>. For the purpose of the question performance wasn't much of a consideration, but you might want to take a look at the answers as they might give you some ideas. Also, I might be off base here, but if you are trying to remove duplicates from the array then a LINQ command like <a href=\"http://msdn.microsoft.com/en-us/library/system.linq.enumerable.distinct.aspx\" rel=\"nofollow noreferrer\">Enumerable.Distinct</a> might give you better performance than something that you write yourself. As it turns out there is a way to get <a href=\"http://weblogs.asp.net/fmarguerie/archive/2007/09/05/linq-support-on-net-2-0.aspx\" rel=\"nofollow noreferrer\">LINQ working on .NET 2.0</a> so this might be a route worth investigating.</p>\n" }, { "answer_id": 94269, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>If you're going to use a List, use the BinarySearch:</p>\n\n<pre><code> // initailize to a size if you know your set size\nList&lt;int&gt; FoundKeys = new List&lt;int&gt;( 64000 );\nDictionary&lt;int,int&gt; FoundDuplicates = new Dictionary&lt;int,int&gt;();\n\nforeach ( int Key in MyKeys )\n{\n // this is an O(log N) operation\n int index = FoundKeys.BinarySearch( Key );\n if ( index &lt; 0 ) \n {\n // if the Key is not in our list, \n // index is the two's compliment of the next value that is in the list\n // i.e. the position it should occupy, and we maintain sorted-ness!\n FoundKeys.Insert( ~index, Key );\n }\n else \n {\n if ( DuplicateKeys.ContainsKey( Key ) )\n {\n DuplicateKeys[Key]++;\n }\n else\n {\n DuplicateKeys.Add( Key, 1 );\n }\n } \n} \n</code></pre>\n\n<p>You can also use this for any type for which you can define an IComparer by using an overload: BinarySearch( T item, IComparer&lt; T > );</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91933", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4660/" ]
I've been working on a project where I need to iterate through a collection of data and remove entries where the "primary key" is duplicated. I have tried using a ``` List<int> ``` and ``` Dictionary<int, bool> ``` With the dictionary I found slightly better performance, even though I never need the Boolean tagged with each entry. My expectation is that this is because a List allows for indexed access and a Dictionary does not. What I was wondering is, is there a better solution to this problem. I do not need to access the entries again, I only need to track what "primary keys" I have seen and make sure I only perform addition work on entries that have a new primary key. I'm using C# and .NET 2.0. And I have no control over fixing the input data to remove the duplicates from the source (unfortunately!). And so you can have a feel for scaling, overall I'm checking for duplicates about 1,000,000 times in the application, but in subsets of no more than about 64,000 that need to be unique.
They have added the HashSet class in .NET 3.5. But I guess it will be on par with the Dictionary. If you have less than say a 100 elements a List will probably perform better.
91,957
<p>How do I use groovy to search+replace in XML?</p> <p>I need something as short/easy as possible, since I'll be giving this code to the testers for their SoapUI scripting.</p> <p>More specifically, how do I turn:</p> <pre><code>&lt;root&gt;&lt;data&gt;&lt;/data&gt;&lt;/root&gt; </code></pre> <p>into:</p> <pre><code>&lt;root&gt;&lt;data&gt;value&lt;/data&gt;&lt;/root&gt; </code></pre>
[ { "answer_id": 91976, "author": "Bob Dizzle", "author_id": 9581, "author_profile": "https://Stackoverflow.com/users/9581", "pm_score": -1, "selected": false, "text": "<p>check this:\n<a href=\"http://today.java.net/pub/a/today/2004/08/12/groovyxml.html?page=2\" rel=\"nofollow noreferrer\">http://today.java.net/pub/a/today/2004/08/12/groovyxml.html?page=2</a></p>\n" }, { "answer_id": 92419, "author": "s3v1", "author_id": 17554, "author_profile": "https://Stackoverflow.com/users/17554", "pm_score": 1, "selected": false, "text": "<p>After some frenzied coding i saw the light and did like this</p>\n\n<pre><code>import org.custommonkey.xmlunit.Diff\nimport org.custommonkey.xmlunit.XMLUnit\n\ndef input = '''&lt;root&gt;&lt;data&gt;&lt;/data&gt;&lt;/root&gt;'''\ndef expectedResult = '''&lt;root&gt;&lt;data&gt;value&lt;/data&gt;&lt;/root&gt;'''\n\ndef xml = new XmlParser().parseText(input)\n\ndef p = xml.'**'.data\np.each{it.value=\"value\"}\n\ndef writer = new StringWriter()\nnew XmlNodePrinter(new PrintWriter(writer)).print(xml)\ndef result = writer.toString()\n\nXMLUnit.setIgnoreWhitespace(true)\ndef xmlDiff = new Diff(result, expectedResult)\nassert xmlDiff.identical()\n</code></pre>\n\n<p></p>\n\n<p>Unfortunately this will not preserve the comments and metadata etc, from the original xml document, so i'll have to find another way</p>\n" }, { "answer_id": 100796, "author": "Lukáš Rampa", "author_id": 10560, "author_profile": "https://Stackoverflow.com/users/10560", "pm_score": 0, "selected": false, "text": "<p>Three \"official\" groovy ways of updating XML are described on page <a href=\"http://groovy.codehaus.org/Processing+XML\" rel=\"nofollow noreferrer\">http://groovy.codehaus.org/Processing+XML</a>, section \"Updating XML\".</p>\n\n<p>Of that three it seems only DOMCategory way preserves XML comments etc.</p>\n" }, { "answer_id": 101567, "author": "s3v1", "author_id": 17554, "author_profile": "https://Stackoverflow.com/users/17554", "pm_score": 1, "selected": false, "text": "<p>I did some some testing with DOMCategory and it's almost working. I can make the replace happen, but some infopath related comments disappear. I'm using a method like this:</p>\n\n<pre><code>def rtv = { xml, tag, value -&gt;\n def doc = DOMBuilder.parse(new StringReader(xml))\n def root = doc.documentElement\n use(DOMCategory) { root.'**'.\"$tag\".each{it.value=value} }\n return DOMUtil.serialize(root) \n}\n</code></pre>\n\n<p>on a source like this:</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\n&lt;?mso-infoPathSolution name=\"urn:schemas-microsoft-com:office:infopath:FA_Ansoegning:http---ementor-dk-application-2007-06-22-\" href=\"manifest.xsf\" solutionVersion=\"1.0.0.14\" productVersion=\"12.0.0\" PIVersion=\"1.0.0.0\" ?&gt;\n&lt;?mso-application progid=\"InfoPath.Document\" versionProgid=\"InfoPath.Document.2\"?&gt;\n&lt;application:FA_Ansoegning xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\nxmlns:application=\"http://corp.dk/application/2007/06/22/\"\nxmlns:xd=\"http://schemas.microsoft.com/office/infopath/2003\"\nxmlns:my=\"http://schemas.microsoft.com/office/infopath/2003/myXSD/200 8-04-14T14:31:48\"&gt;\n &lt;Mobiltlf&gt;&lt;/Mobiltlf&gt;\n &lt;E-mail-adresse&gt;&lt;/E-mail-adresse&gt;\n&lt;/application:FA_Ansoegning&gt;\n</code></pre>\n\n<p>The only thing missing from the result are the &lt;?mso- lines from the result. Anyone with an idea for that?</p>\n" }, { "answer_id": 113942, "author": "GerG", "author_id": 17249, "author_profile": "https://Stackoverflow.com/users/17249", "pm_score": 0, "selected": false, "text": "<p>To me the actual copy &amp; search &amp; replace seems like the perfect job for an XSLT stylesheet. In an XSLT you have no problem at all to just copy everything (including the items you're having problems with) and simply insert your data where it is required. You can pass the specific value of your data in via an XSL parameter or you can dynamically modify the stylesheet itself (if you include as a string in your Groovy program). Calling this XSLT to transform your document(s) from within Groovy is very simple.</p>\n\n<p>I quickly cobbled the following Groovy script together (but I have no doubts it can be written even more simple/compact):</p>\n\n<pre><code>import javax.xml.transform.TransformerFactory\nimport javax.xml.transform.stream.StreamResult\nimport javax.xml.transform.stream.StreamSource\n\ndef xml = \"\"\"\n&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\n&lt;?mso-infoPathSolution name=\"urn:schemas-microsoft-com:office:infopath:FA_Ansoegning:http---ementor-dk-application-2007-06-22-\" href=\"manifest.xsf\" solutionVersion=\"1.0.0.14\" productVersion=\"12.0.0\" PIVersion=\"1.0.0.0\" ?&gt;\n&lt;?mso-application progid=\"InfoPath.Document\" versionProgid=\"InfoPath.Document.2\"?&gt;\n&lt;application:FA_Ansoegning xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\nxmlns:application=\"http://ementor.dk/application/2007/06/22/\"\nxmlns:xd=\"http://schemas.microsoft.com/office/infopath/2003\"\nxmlns:my=\"http://schemas.microsoft.com/office/infopath/2003/myXSD/200 8-04-14T14:31:48\"&gt;\n &lt;Mobiltlf&gt;&lt;/Mobiltlf&gt;\n &lt;E-mail-adresse&gt;&lt;/E-mail-adresse&gt;\n&lt;/application:FA_Ansoegning&gt;\n\"\"\".trim()\n\ndef xslt = \"\"\"\n&lt;xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" version=\"1.0\"&gt;\n &lt;xsl:param name=\"mobil\" select=\"'***dummy***'\"/&gt;\n &lt;xsl:param name=\"email\" select=\"'***dummy***'\"/&gt;\n\n &lt;xsl:template match=\"@*|node()\"&gt;\n &lt;xsl:copy&gt;\n &lt;xsl:apply-templates select=\"@*|node()\"/&gt;\n &lt;/xsl:copy&gt;\n &lt;/xsl:template&gt;\n\n &lt;xsl:template match=\"Mobiltlf\"&gt;\n &lt;xsl:copy&gt;\n &lt;xsl:value-of select=\"\\$mobil\"/&gt;\n &lt;/xsl:copy&gt;\n &lt;/xsl:template&gt;\n\n &lt;xsl:template match=\"E-mail-adresse\"&gt;\n &lt;xsl:copy&gt;\n &lt;xsl:value-of select=\"\\$email\"/&gt;\n &lt;/xsl:copy&gt;\n &lt;/xsl:template&gt;\n&lt;/xsl:stylesheet&gt;\n\"\"\".trim()\n\ndef factory = TransformerFactory.newInstance()\ndef transformer = factory.newTransformer(new StreamSource(new StringReader(xslt)))\n\ntransformer.setParameter('mobil', '1234567890')\ntransformer.setParameter('email', '[email protected]')\n\ntransformer.transform(new StreamSource(new StringReader(xml)), new StreamResult(System.out))\n</code></pre>\n\n<p>Running this script produces:</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;&lt;?mso-infoPathSolution name=\"urn:schemas-microsoft-com:office:infopath:FA_Ansoegning:http---ementor-dk-application-2007-06-22-\" href=\"manifest.xsf\" solutionVersion=\"1.0.0.14\" productVersion=\"12.0.0\" PIVersion=\"1.0.0.0\" ?&gt;\n&lt;?mso-application progid=\"InfoPath.Document\" versionProgid=\"InfoPath.Document.2\"?&gt;\n&lt;application:FA_Ansoegning xmlns:application=\"http://ementor.dk/application/2007/06/22/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xd=\"http://schemas.microsoft.com/office/infopath/2003\" xmlns:my=\"http://schemas.microsoft.com/office/infopath/2003/myXSD/200 8-04-14T14:31:48\"&gt;\n &lt;Mobiltlf&gt;1234567890&lt;/Mobiltlf&gt;\n &lt;E-mail-adresse&gt;[email protected]&lt;/E-mail-adresse&gt;\n&lt;/application:FA_Ansoegning&gt;\n</code></pre>\n" }, { "answer_id": 115192, "author": "s3v1", "author_id": 17554, "author_profile": "https://Stackoverflow.com/users/17554", "pm_score": 1, "selected": false, "text": "<p>That's the best answer so far and it gives the right result, so I'm going to accept the answer :) \nHowever, it's a little too large for me. I think i had better explain that the alternative is:</p>\n\n<pre><code>xml.replace(\"&lt;Mobiltlf&gt;&lt;/Mobiltlf&gt;\", &lt;Mobiltlf&gt;32165487&lt;/Mobiltlf&gt;\")\n</code></pre>\n\n<p>But that's not very xml'y so I thought i'd look for an alternative. Also, I can't be sure that the first tag is empty all the time.</p>\n" }, { "answer_id": 119650, "author": "GerG", "author_id": 17249, "author_profile": "https://Stackoverflow.com/users/17249", "pm_score": 3, "selected": true, "text": "<p>Some of the stuff you can do with an XSLT you can also do with some form of 'search &amp; replace'. It all depends on how complex your problem is and how 'generic' you want to implement the solution. To make your own example slightly more generic:</p>\n\n<pre><code>xml.replaceFirst(\"&lt;Mobiltlf&gt;[^&lt;]*&lt;/Mobiltlf&gt;\", '&lt;Mobiltlf&gt;32165487&lt;/Mobiltlf&gt;')\n</code></pre>\n\n<p>The solution you choose is up to you. In my own experience (for very simple problems) using simple string lookups is faster than using regular expressions which is again faster than using a fullblown XSLT transformation (makes sense actually).</p>\n" }, { "answer_id": 120013, "author": "s3v1", "author_id": 17554, "author_profile": "https://Stackoverflow.com/users/17554", "pm_score": 0, "selected": false, "text": "<p>Brilliant! Thank you very much for you assistance :)</p>\n\n<p>That solves my problem in a much cleaner and easier way. It's ended up looking like this:</p>\n\n<pre><code>def rtv = { xmlSource, tagName, newValue -&gt;\n regex = \"&lt;$tagName&gt;[^&lt;]*&lt;/$tagName&gt;\"\n replacement = \"&lt;$tagName&gt;${newValue}&lt;/$tagName&gt;\"\n xmlSource = xmlSource.replaceAll(regex, replacement)\n return xmlSource\n}\n\ninput = rtv( input, \"Mobiltlf\", \"32165487\" )\ninput = rtv( input, \"E-mail-adresse\", \"[email protected]\" )\nprintln input\n</code></pre>\n\n<p>Since I'm giving this to our testers for use in their testing tool SoapUI, I've tried to \"wrap\" it, to make it easier for them to copy and paste.</p>\n\n<p>This is good enough for my purpose, but it would be perfect if we could add one more \"twist\"</p>\n\n<p>Let's say the input had this in it...</p>\n\n<pre><code>&lt;Mobiltlf type=\"national\" anotherattribute=\"value\"&gt;&lt;/Mobiltlf&gt;\n</code></pre>\n\n<p>...and we wanted to retain thos two attributes even though we replaced the value. Is there a way to use regexp for that too?</p>\n" }, { "answer_id": 125591, "author": "GerG", "author_id": 17249, "author_profile": "https://Stackoverflow.com/users/17249", "pm_score": 1, "selected": false, "text": "<p>To retain the attributes just modify your little program like this (I've included a sample source to test it):</p>\n\n<pre><code>def input = \"\"\"\n&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\n&lt;?mso-infoPathSolution name=\"urn:schemas-microsoft-com:office:infopath:FA_Ansoegning:http---ementor-dk-application-2007-06-22-\" href=\"manifest.xsf\" solutionVersion=\"1.0.0.14\" productVersion=\"12.0.0\" PIVersion=\"1.0.0.0\" ?&gt;\n&lt;?mso-application progid=\"InfoPath.Document\" versionProgid=\"InfoPath.Document.2\"?&gt;\n&lt;application:FA_Ansoegning xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\nxmlns:application=\"http://ementor.dk/application/2007/06/22/\"\nxmlns:xd=\"http://schemas.microsoft.com/office/infopath/2003\"\nxmlns:my=\"http://schemas.microsoft.com/office/infopath/2003/myXSD/200 8-04-14T14:31:48\"&gt;\n &lt;Mobiltlf type=\"national\" anotherattribute=\"value\"&gt;&lt;/Mobiltlf&gt;\n &lt;E-mail-adresse attr=\"whatever\"&gt;&lt;/E-mail-adresse&gt;\n&lt;/application:FA_Ansoegning&gt;\n\"\"\".trim()\n\ndef rtv = { xmlSource, tagName, newValue -&gt;\n regex = \"(&lt;$tagName[^&gt;]*&gt;)([^&lt;]*)(&lt;/$tagName&gt;)\"\n replacement = \"\\$1${newValue}\\$3\"\n xmlSource = xmlSource.replaceAll(regex, replacement)\n return xmlSource\n}\n\ninput = rtv( input, \"Mobiltlf\", \"32165487\" )\ninput = rtv( input, \"E-mail-adresse\", \"[email protected]\" )\nprintln input\n</code></pre>\n\n<p>Running this script produces:</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\n&lt;?mso-infoPathSolution name=\"urn:schemas-microsoft-com:office:infopath:FA_Ansoegning:http---ementor-dk-application-2007-06-22-\" href=\"manifest.xsf\" solutionVersion=\"1.0.0.14\" productVersion=\"12.0.0\" PIVersion=\"1.0.0.0\" ?&gt;\n&lt;?mso-application progid=\"InfoPath.Document\" versionProgid=\"InfoPath.Document.2\"?&gt;\n&lt;application:FA_Ansoegning xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\nxmlns:application=\"http://ementor.dk/application/2007/06/22/\"\nxmlns:xd=\"http://schemas.microsoft.com/office/infopath/2003\"\nxmlns:my=\"http://schemas.microsoft.com/office/infopath/2003/myXSD/200 8-04-14T14:31:48\"&gt;\n &lt;Mobiltlf type=\"national\" anotherattribute=\"value\"&gt;32165487&lt;/Mobiltlf&gt;\n &lt;E-mail-adresse attr=\"whatever\"&gt;[email protected]&lt;/E-mail-adresse&gt;\n&lt;/application:FA_Ansoegning&gt;\n</code></pre>\n\n<p>Note that the matching regexp now contains 3 capturing groups: (1) the start tag (including attributes), (2) whatever is the 'old' content of your tag and (3) the end tag. The replacement string refers to these captured groups via the $i syntax (with backslashes to escape them in the GString). Just a tip: regular expressions are very powerful animals, it's really worthwile to become familiar with them ;-) .</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91957", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17554/" ]
How do I use groovy to search+replace in XML? I need something as short/easy as possible, since I'll be giving this code to the testers for their SoapUI scripting. More specifically, how do I turn: ``` <root><data></data></root> ``` into: ``` <root><data>value</data></root> ```
Some of the stuff you can do with an XSLT you can also do with some form of 'search & replace'. It all depends on how complex your problem is and how 'generic' you want to implement the solution. To make your own example slightly more generic: ``` xml.replaceFirst("<Mobiltlf>[^<]*</Mobiltlf>", '<Mobiltlf>32165487</Mobiltlf>') ``` The solution you choose is up to you. In my own experience (for very simple problems) using simple string lookups is faster than using regular expressions which is again faster than using a fullblown XSLT transformation (makes sense actually).
91,981
<p>Is there a way to mock object construction using JMock in Java? </p> <p>For example, if I have a method as such:</p> <pre class="lang-java prettyprint-override"><code>public Object createObject(String objectType) { if(objectType.equals("Integer") { return new Integer(); } else if (objectType.equals("String") { return new String(); } } </code></pre> <p>...is there a way to mock out the expectation of the object construction in a test method? </p> <p>I'd like to be able to place expectations that certain constructors are being called, rather than having an extra bit of code to check the type (as it won't always be as convoluted and simple as my example).</p> <p>So instead of:</p> <pre class="lang-java prettyprint-override"><code>assertTrue(a.createObject() instanceof Integer); </code></pre> <p>I could have an expectation of the certain constructor being called. Just to make it a bit cleaner, and express what is actually being tested in a more readable way.</p> <p>Please excuse the simple example, the actual problem I'm working on is a bit more complicated, but having the expectation would simplify it.</p> <hr> <p>For a bit more background:</p> <p>I have a simple factory method, which creates wrapper objects. The objects being wrapped can require parameters which are difficult to obtain in a test class (it's pre-existing code), so it is difficult to construct them.</p> <p>Perhaps closer to what I'm actually looking for is: is there a way to mock an entire class (using CGLib) in one fell swoop, without specifying every method to stub out? </p> <p>So the mock is being wrapped in a constructor, so obviously methods can be called on it, is JMock capable of dynamically mocking out each method? </p> <p>My guess is no, as that would be pretty complicated. But knowing I'm barking up the wrong tree is valuable too :-)</p>
[ { "answer_id": 92064, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": -1, "selected": false, "text": "<p>I hope there is none. \nMocks are supposed to mock interfaces, which have no constructors... just methods. </p>\n\n<p>Something seems to be amiss in your approach to testing here. Any reason why you need to test that explicit constructors are being called ?<br>\nAsserting the type of returned object seems okay for testing factory implementations. Treat createObject as a blackbox.. examine what it returns but dont micromanage how it does it. No one likes that :)</p>\n\n<p><strong>Update on the Update:</strong> Ouch! Desperate measures for desperate times eh? I'd be surprised if JMock allows that... as I said it works on interfaces.. not concrete types. \nSo </p>\n\n<ul>\n<li>Either try and expend some effort on getting those pesky input objects 'instantiable' under the test harness. Go Bottom up in your approach.</li>\n<li>If that is infeasible, manually test it out with breakpoints (I know it sucks). Then stick a \"Touch it at your own risk\" comment in a visible zone in the source file and move ahead. Fight another day.</li>\n</ul>\n" }, { "answer_id": 92085, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 4, "selected": true, "text": "<p>The only thing I can think of is to have the create method on at factory object, which you would than mock. </p>\n\n<p>But in terms of mocking a constructor call, no. Mock objects presuppose the existence of the object, whereas a constructor presuppose that the object doesn't exist. At least in java where allocation and initialization happen together. </p>\n" }, { "answer_id": 92139, "author": "Rene Saarsoo", "author_id": 15982, "author_profile": "https://Stackoverflow.com/users/15982", "pm_score": 0, "selected": false, "text": "<p>Are you familiar with <a href=\"http://en.wikipedia.org/wiki/Dependency_injection\" rel=\"nofollow noreferrer\">Dependency Injection</a>?</p>\n\n<p>If no, then you ceartanly would benefit from learning about that concept. I guess the good-old <a href=\"http://www.martinfowler.com/articles/injection.html\" rel=\"nofollow noreferrer\">Inversion of Control Containers and the Dependency Injection pattern</a> by Martin Fowler will serve as a good introduction.</p>\n\n<p>With Dependency Injection (DI), you would have a DI container object, that is able to create all kinds of classes for you. Then your object would make use of the DI container to instanciate classes and you would mock the DI container to test that the class creates instances of expected classes.</p>\n" }, { "answer_id": 92285, "author": "Javaxpert", "author_id": 15241, "author_profile": "https://Stackoverflow.com/users/15241", "pm_score": 0, "selected": false, "text": "<p>Dependency Injection or Inversion of Control.</p>\n\n<p>Alternatively, use the Abstract Factory design pattern for all the objects that you create. When you are in Unit Test mode, inject an Testing Factory which will tell you what are you creating, then include the assertion code in the Testing Factory to check the results (inversion of control).</p>\n\n<p>To leave your code as clean as possible create an internal protected interface, implement the interface (your factory) with the production code as an internal class. Add a static variable type of your interface initialized to your default factory. Add static setter for the factory and you are done.</p>\n\n<p>In your test code (must be in the same package, otherwise the internal interface must be public), create an anonymous or internal class with the assertion code and the test code. Then in your test, initialize the target class, assign (inject) the test factory, and run the methods of your target class.</p>\n" }, { "answer_id": 92718, "author": "Grundlefleck", "author_id": 4120, "author_profile": "https://Stackoverflow.com/users/4120", "pm_score": 1, "selected": false, "text": "<p>Alas, I think I'm guilty of asking the wrong question.</p>\n\n<p>The simple factory I was trying to test looked something like:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public Wrapper wrapObject(Object toWrap) {\n if(toWrap instanceof ClassA) {\n return new Wrapper((ClassA) toWrap);\n } else if (toWrap instanceof ClassB) {\n return new Wrapper((ClassB) toWrap);\n } // etc\n\n else {\n return null;\n }\n}\n</code></pre>\n\n<p>I was asking the question how to find if \"new ClassAWrapper( )\" was called because the object toWrap was hard to obtain in an isolated test. And the wrapper (if it can even be called that) is kind of weird as it uses the same class to wrap different objects, just uses different constructors[1]. I suspect that if I had asked the question a bit better, I would have quickly received the answer:</p>\n\n<p>\"You should mock Object toWrap to match the instances you're testing for in different test methods, and inspect the resulting Wrapper object to find the correct type is returned... and hope you're lucky enough that you don't have to mock out the world to create the different instances ;-)\"</p>\n\n<p>I now have an okay solution to the immediate problem, thanks! </p>\n\n<p>[1] opening up the question of whether this should be refactored is well out of the scope of my current problem :-)</p>\n" }, { "answer_id": 93829, "author": "Kris Pruden", "author_id": 16977, "author_profile": "https://Stackoverflow.com/users/16977", "pm_score": 2, "selected": false, "text": "<p>jmockit can do this.</p>\n\n<p>See my answer in <a href=\"https://stackoverflow.com/questions/22697#93675\">https://stackoverflow.com/questions/22697#93675</a></p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91981", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4120/" ]
Is there a way to mock object construction using JMock in Java? For example, if I have a method as such: ```java public Object createObject(String objectType) { if(objectType.equals("Integer") { return new Integer(); } else if (objectType.equals("String") { return new String(); } } ``` ...is there a way to mock out the expectation of the object construction in a test method? I'd like to be able to place expectations that certain constructors are being called, rather than having an extra bit of code to check the type (as it won't always be as convoluted and simple as my example). So instead of: ```java assertTrue(a.createObject() instanceof Integer); ``` I could have an expectation of the certain constructor being called. Just to make it a bit cleaner, and express what is actually being tested in a more readable way. Please excuse the simple example, the actual problem I'm working on is a bit more complicated, but having the expectation would simplify it. --- For a bit more background: I have a simple factory method, which creates wrapper objects. The objects being wrapped can require parameters which are difficult to obtain in a test class (it's pre-existing code), so it is difficult to construct them. Perhaps closer to what I'm actually looking for is: is there a way to mock an entire class (using CGLib) in one fell swoop, without specifying every method to stub out? So the mock is being wrapped in a constructor, so obviously methods can be called on it, is JMock capable of dynamically mocking out each method? My guess is no, as that would be pretty complicated. But knowing I'm barking up the wrong tree is valuable too :-)
The only thing I can think of is to have the create method on at factory object, which you would than mock. But in terms of mocking a constructor call, no. Mock objects presuppose the existence of the object, whereas a constructor presuppose that the object doesn't exist. At least in java where allocation and initialization happen together.
91,986
<p>I've got the following SQL:</p> <pre><code>select * from transaction_log where stoptime like '%2008%' </code></pre> <p>How do I write this in LINQ to SQL syntax?</p>
[ { "answer_id": 92009, "author": "Nick Craver", "author_id": 13249, "author_profile": "https://Stackoverflow.com/users/13249", "pm_score": 6, "selected": true, "text": "<p>If you want to use the literal method, it's like this:</p>\n\n<pre><code>var query = from l in transaction_log\n where SqlMethods.Like(l.stoptime, \"%2008%\")\n select l;\n</code></pre>\n\n<p>Another option is:</p>\n\n<pre><code>var query = from l in transaction_log\n where l.stoptime.Contains(\"2008\")\n select l;\n</code></pre>\n\n<p>If it's a DateTime:</p>\n\n<pre><code>var query = from l in transaction_log\n where l.stoptime.Year = 2008\n select l;\n</code></pre>\n\n<p>That method is in the <strong>System.Data.Linq.SqlClient</strong> namespace</p>\n" }, { "answer_id": 92010, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<pre><code>from x in context.Table where x.Contains(\"2008\") select x\n</code></pre>\n" }, { "answer_id": 92034, "author": "ChRoss", "author_id": 10802, "author_profile": "https://Stackoverflow.com/users/10802", "pm_score": 1, "selected": false, "text": "<p>If stoptime data type is string, you can use .Contains() function, and also .StartsWith() and .EndsWith().</p>\n" }, { "answer_id": 92202, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>If you use the contains to method then you are doing a LIKE '%somestring%'. If you use a startswith method then it is the same as 'somestring%'. Finally, endswith is the same as using '%somestring'.</p>\n\n<p>To summarize, contains will find any pattern in the string but startswith and endswith will help you find matches at the beginning and end of the word.</p>\n" }, { "answer_id": 92227, "author": "MADMap", "author_id": 17558, "author_profile": "https://Stackoverflow.com/users/17558", "pm_score": 0, "selected": false, "text": "<p>The really interesting point is, that .NET creates queries like \"Select * from table where name like '%test%'\" when you use \"from x in context.Table where x.Contains(\"test\") select x\" which is quite impressing</p>\n" }, { "answer_id": 94576, "author": "Scott Marlowe", "author_id": 1683, "author_profile": "https://Stackoverflow.com/users/1683", "pm_score": 0, "selected": false, "text": "<p>Thanks--good answers.</p>\n\n<p>This is, in fact, a DateTime type; I had to typecast \"stoptime\" as:</p>\n\n<pre><code>var query = from p in dbTransSummary.Transaction_Logs\n where ( (DateTime) p.StopTime).Year == dtRollUpDate.Year\n select\n</code></pre>\n\n<p>Minor point. It works great!</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91986", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1683/" ]
I've got the following SQL: ``` select * from transaction_log where stoptime like '%2008%' ``` How do I write this in LINQ to SQL syntax?
If you want to use the literal method, it's like this: ``` var query = from l in transaction_log where SqlMethods.Like(l.stoptime, "%2008%") select l; ``` Another option is: ``` var query = from l in transaction_log where l.stoptime.Contains("2008") select l; ``` If it's a DateTime: ``` var query = from l in transaction_log where l.stoptime.Year = 2008 select l; ``` That method is in the **System.Data.Linq.SqlClient** namespace
91,994
<p>This is probably a silly question, but curiosity has gotten the better of me. I've been seeing code lately that seems to "reverse" the order of expressions for relational operators e.g.:</p> <pre><code>if (0 == someVariable) </code></pre> <p>As opposed to what I normally see/write:</p> <pre><code>if (someVariable == 0) </code></pre> <p>To me, the second method seems more readable and intuitive, so I'm wondering if there's some reason I'm seeing the first method? Logically, both statements evaluate to the same result, so is it just a matter of personal preference how they're written?</p>
[ { "answer_id": 91997, "author": "William Keller", "author_id": 17095, "author_profile": "https://Stackoverflow.com/users/17095", "pm_score": 2, "selected": false, "text": "<p>Order does not matter, however, the former implies that it\ns the zero you're checking. Convention dictates the use of hte latter.</p>\n" }, { "answer_id": 92003, "author": "user7116", "author_id": 7116, "author_profile": "https://Stackoverflow.com/users/7116", "pm_score": 1, "selected": false, "text": "<p>The first method exists as a way to remind yourself not to do assignments in an IF statement, which could have disasterous consequences in some languages (C/C++). In C# you'll only get bitten by this if you're setting booleans.</p>\n\n<p>Potentially fatal C code:</p>\n\n<pre><code>if (succeeded = TRUE)\n{\n // I could be in trouble here if 'succeeded' was FALSE\n}\n</code></pre>\n\n<p>In C/C++, any variable is susceptible to this problem of VAR = CONSTANT when you intended VAR == CONSTANT. So, it is often the custom to reorder your IF statement to receive a compile error if you flub this up:</p>\n\n<pre><code>if (TRUE = succeeded)\n{\n // This will fail to compile, and I'll fix my mistake\n}\n</code></pre>\n\n<p>In C# only booleans are susceptible to this, as only boolean expressions are valid in an if statement.</p>\n\n<pre><code>if (myInteger = 9)\n{\n // this will fail to compile\n}\n</code></pre>\n\n<p>So, in the C# world it isn't necessary to adopt the CONSTANT == VAR style, unless you're comfortable with doing so.</p>\n" }, { "answer_id": 92005, "author": "James Boother", "author_id": 16030, "author_profile": "https://Stackoverflow.com/users/16030", "pm_score": 4, "selected": true, "text": "<p>I understand that this is personal preference. Although by putting the variable second you can ensure that you don't accidentally assign the constant to the variable which used to concearn c developers. This is probably why you are seeing it in c# as developers switch language.</p>\n" }, { "answer_id": 92014, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 1, "selected": false, "text": "<p>The latter format is a left-over from C-syntax, where, if you inadvertently left out one of the equals-signs, it did an assignment, instead of a comparison.</p>\n\n<p>However, you can of course not assign to a numeric literal, so if you wrote it like the second example, you would get a compiler error, and not a bug.</p>\n\n<p>In C#, however, you cannot inadvertently do this, so it doesn't really matter.</p>\n" }, { "answer_id": 92021, "author": "pdc", "author_id": 8925, "author_profile": "https://Stackoverflow.com/users/8925", "pm_score": 2, "selected": false, "text": "<p>The main reason in C and C++ is that it is easy to type</p>\n\n<pre><code>if (someVariable = 0) {\n ...\n}\n</code></pre>\n\n<p>which always fails and also sets <code>someVariable</code> to 0.</p>\n\n<p>I personally prefer the variable-first style because it reads more naturally, and just hope I don't forget to use <code>==</code> not <code>=</code>.</p>\n\n<p>Many C and C++ compilers will issue a warning if you assign a constant inside an <code>if</code>.\nJava and C# avoid this problem by forbidding non-boolean expressions in <code>if</code> clauses.\nPython avoids this problem by making assignments a statement, not an expression.</p>\n" }, { "answer_id": 92240, "author": "marijne", "author_id": 7038, "author_profile": "https://Stackoverflow.com/users/7038", "pm_score": 1, "selected": false, "text": "<p>In addition to equality I often come across code like</p>\n\n<pre><code>if (0 &gt; number)\n</code></pre>\n\n<p>or</p>\n\n<pre><code>if (NULL != pointer)\n</code></pre>\n\n<p>where there isn't even any danger of making a mistake in C/C++! It's one of those situations where a well-intentioned teaching technique has turned into a plain bad habit.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91994", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9324/" ]
This is probably a silly question, but curiosity has gotten the better of me. I've been seeing code lately that seems to "reverse" the order of expressions for relational operators e.g.: ``` if (0 == someVariable) ``` As opposed to what I normally see/write: ``` if (someVariable == 0) ``` To me, the second method seems more readable and intuitive, so I'm wondering if there's some reason I'm seeing the first method? Logically, both statements evaluate to the same result, so is it just a matter of personal preference how they're written?
I understand that this is personal preference. Although by putting the variable second you can ensure that you don't accidentally assign the constant to the variable which used to concearn c developers. This is probably why you are seeing it in c# as developers switch language.
92,008
<p>How do I programmatically set the record pointer in a C# DataGridView? </p> <p>I've tried "DataGridView.Rows[DesiredRowIndex].Selected=true;", and that does not work. All it does is highlight that row within the grid; it doesn not move the record pointer to that row.</p>
[ { "answer_id": 92105, "author": "Wolfwyrd", "author_id": 15570, "author_profile": "https://Stackoverflow.com/users/15570", "pm_score": 3, "selected": true, "text": "<p>To change the active row for the datagrid you need to set the current cell property of the datagrid to a non-hidden non-disabled, non-header cell on the row that you have selected. You'd do this like:</p>\n\n<pre><code>dataGridView1.CurrentCell = this.dataGridView1[YourColumn,YourRow];\n</code></pre>\n\n<p>Making sure that the cell matches the above criteria. Further information can be found at:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/yc4fsbf5.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/yc4fsbf5.aspx</a></p>\n" }, { "answer_id": 12528343, "author": "Ashar Nawaz", "author_id": 1688470, "author_profile": "https://Stackoverflow.com/users/1688470", "pm_score": 1, "selected": false, "text": "<p>Try setting the focus of the <code>DataGrid</code> first . Some thing like this</p>\n\n<pre><code>dataGridView1.Focus();\ndataGridView1.CurrentCell = this.dataGridView1[YourColumn,YourRow];\n</code></pre>\n\n<p>This worked in my case, hope it helps you as well</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/92008", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7148/" ]
How do I programmatically set the record pointer in a C# DataGridView? I've tried "DataGridView.Rows[DesiredRowIndex].Selected=true;", and that does not work. All it does is highlight that row within the grid; it doesn not move the record pointer to that row.
To change the active row for the datagrid you need to set the current cell property of the datagrid to a non-hidden non-disabled, non-header cell on the row that you have selected. You'd do this like: ``` dataGridView1.CurrentCell = this.dataGridView1[YourColumn,YourRow]; ``` Making sure that the cell matches the above criteria. Further information can be found at: <http://msdn.microsoft.com/en-us/library/yc4fsbf5.aspx>
92,027
<p>For a registration form I have something simple like:</p> <pre><code> &lt;tr:panelLabelAndMessage label="Zip/City" showRequired="true"&gt; &lt;tr:inputText id="zip" value="#{data['registration'].zipCode}" contentStyle="width:36px" simple="true" required="true" /&gt; &lt;tr:inputText id="city" value="#{data['registration'].city}" contentStyle="width:133px" simple="true" required="true" /&gt; &lt;/tr:panelLabelAndMessage&gt; &lt;tr:message for="zip" /&gt; &lt;tr:message for="city" /&gt; </code></pre> <p>When including the last two lines, I get two messages on validation error. When ommiting last to lines, a javascript alert shows up, which is not what I want. </p> <p>Is there a solution to show only one validation failed message somehow?</p> <p>Thanks a lot!</p>
[ { "answer_id": 107817, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I know this won't be ideal, but if you remove the <code>panelLabelAndMessage</code> tag and just use the label attribute on the <code>inputText</code> tag that should remove the extra error message. </p>\n" }, { "answer_id": 108130, "author": "GHad", "author_id": 11705, "author_profile": "https://Stackoverflow.com/users/11705", "pm_score": 1, "selected": false, "text": "<p>Problem is, the fields must layout horizontally. It's a no-go to put ZIP field and city not next to each other in one line. At least for me.</p>\n\n<p>A co-worker has pointed me to set a faclets variable inside the first tr:message and to put a rendered attribute at the second one that reacts on this variable. Havn't got the time to try nor found the right command for setting a varable yet. Will post results as soon as possible.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/92027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11705/" ]
For a registration form I have something simple like: ``` <tr:panelLabelAndMessage label="Zip/City" showRequired="true"> <tr:inputText id="zip" value="#{data['registration'].zipCode}" contentStyle="width:36px" simple="true" required="true" /> <tr:inputText id="city" value="#{data['registration'].city}" contentStyle="width:133px" simple="true" required="true" /> </tr:panelLabelAndMessage> <tr:message for="zip" /> <tr:message for="city" /> ``` When including the last two lines, I get two messages on validation error. When ommiting last to lines, a javascript alert shows up, which is not what I want. Is there a solution to show only one validation failed message somehow? Thanks a lot!
Problem is, the fields must layout horizontally. It's a no-go to put ZIP field and city not next to each other in one line. At least for me. A co-worker has pointed me to set a faclets variable inside the first tr:message and to put a rendered attribute at the second one that reacts on this variable. Havn't got the time to try nor found the right command for setting a varable yet. Will post results as soon as possible.
92,035
<p>I have a datagridview with a DataGridViewComboboxColumn column with 3 values:</p> <p>"Small", "Medium", "Large"</p> <p>I get back the users default which in this case is "Medium"</p> <p>I want to show a dropdown cell in the datagridview but default the value to "Medium". i would do this in a regular combobox by doing selected index or just stting the Text property of a combo box.</p>
[ { "answer_id": 92186, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Are you retrieving the user data and attempting to set values in the DataGridView manually, or have you actually bound the DataGridVew to a data source? Because if you've bound the grid to a data source, you should just need to set the DataPropertyName on the column to be the string name of the object Property:</p>\n\n<pre><code>[DataGridViewComboboxColumnName].DataPropertyName = \"PropertyNameToBindTo\";\n</code></pre>\n\n<p>Or do you mean you want it to default to Medium for a new row?</p>\n" }, { "answer_id": 712960, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": true, "text": "<p>When you get into the datagridview it is probably best to get into databinding. This will take care of all of the selected index stuff you are talking about.</p>\n\n<p>However, if you want to get in there by yourself, </p>\n\n<pre><code>DataGridView.Rows[rowindex].Cells[columnindex].Value \n</code></pre>\n\n<p>will let you get and set the value associated to the DataGridViewComboBoxColumn. Just make sure you supply the correct rowindex and columnindex along with setting the value to the correct type (the same type as the ValueMember property of the DataGridViewComboBoxColumn).</p>\n" }, { "answer_id": 3590320, "author": "Sandeep Pathak", "author_id": 422437, "author_profile": "https://Stackoverflow.com/users/422437", "pm_score": 0, "selected": false, "text": "<p>Do accomplish this task you should do something like this:-</p>\n\n<pre><code> this.dataGridViewStudentInformation.Columns[ColumnIndex].DataPropertyName = dataGridViewStudentInformation.Columns[2].Name ; //Set the ColumnName to which you want to bind. \n</code></pre>\n\n<p>And set the default value in Database as Medium.</p>\n" }, { "answer_id": 20755543, "author": "user2866884", "author_id": 2866884, "author_profile": "https://Stackoverflow.com/users/2866884", "pm_score": 2, "selected": false, "text": "<pre><code>DataGridViewComboBoxColumn ColumnPage = new DataGridViewComboBoxColumn();\nColumnPage.DefaultCellStyle.NullValue = \"Medium\";\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/92035", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4653/" ]
I have a datagridview with a DataGridViewComboboxColumn column with 3 values: "Small", "Medium", "Large" I get back the users default which in this case is "Medium" I want to show a dropdown cell in the datagridview but default the value to "Medium". i would do this in a regular combobox by doing selected index or just stting the Text property of a combo box.
When you get into the datagridview it is probably best to get into databinding. This will take care of all of the selected index stuff you are talking about. However, if you want to get in there by yourself, ``` DataGridView.Rows[rowindex].Cells[columnindex].Value ``` will let you get and set the value associated to the DataGridViewComboBoxColumn. Just make sure you supply the correct rowindex and columnindex along with setting the value to the correct type (the same type as the ValueMember property of the DataGridViewComboBoxColumn).
92,043
<p>I've tried the tools listed <a href="http://wiki.postgresql.org/wiki/Converting_from_other_Databases_to_PostgreSQL" rel="noreferrer">here</a>, some with more success than others, but none gave me valid postgres syntax I could use (tinyint errors etc.)</p>
[ { "answer_id": 92077, "author": "Dana the Sane", "author_id": 2567, "author_profile": "https://Stackoverflow.com/users/2567", "pm_score": 0, "selected": false, "text": "<p>Have a look at <a href=\"http://pgfoundry.org/\" rel=\"nofollow noreferrer\">PG Foundry</a>, extra utilities for Postgres tend to live there. I believe that the tool you're looking for does exist though.</p>\n" }, { "answer_id": 92158, "author": "Ilya Kochetov", "author_id": 15329, "author_profile": "https://Stackoverflow.com/users/15329", "pm_score": -1, "selected": false, "text": "<p>you will most likely never get a tool for such task which would do all of your job for you. be prepared to do some refactoring work yourself.</p>\n" }, { "answer_id": 93010, "author": "Arthur Thomas", "author_id": 14009, "author_profile": "https://Stackoverflow.com/users/14009", "pm_score": 0, "selected": false, "text": "<p>There is one piece of pay software listed on this postgresql page:\n<a href=\"http://www.postgresql.org/download/products/1\" rel=\"nofollow noreferrer\">http://www.postgresql.org/download/products/1</a></p>\n\n<p>and this is on pgFoundry:\n<a href=\"http://pgfoundry.org/projects/mysql2pgsql/\" rel=\"nofollow noreferrer\">http://pgfoundry.org/projects/mysql2pgsql/</a></p>\n" }, { "answer_id": 106760, "author": "vog", "author_id": 19163, "author_profile": "https://Stackoverflow.com/users/19163", "pm_score": 5, "selected": true, "text": "<p>There's a <code>mysqldump</code> option which makes it output PostgreSQL code:</p>\n<pre>\nmysqldump --compatible=postgresql ...\n</pre>\n<p>But that doesn't work too well.</p>\n<p>Instead, please see the <a href=\"https://github.com/maxlapshin/mysql2postgres\" rel=\"nofollow noreferrer\">mysql-to-postgres</a> tool as <a href=\"https://stackoverflow.com/a/15670452/19163\">described in Linus Oleander's answer</a>.</p>\n" }, { "answer_id": 15670452, "author": "Linus Oleander", "author_id": 560073, "author_profile": "https://Stackoverflow.com/users/560073", "pm_score": 2, "selected": false, "text": "<p>After some time on Google I found <a href=\"http://ruby.zigzo.com/2011/12/03/migrating-data-from-mysql-to-postgresql/\" rel=\"nofollow\">this post</a>.</p>\n\n<ol>\n<li>Install the <a href=\"https://github.com/maxlapshin/mysql2postgres\" rel=\"nofollow\">mysql2psql</a> gem using <code>[sudo] gem install mysql2psql</code>.</li>\n<li>Create a config file by running <code>mysql2psql</code>. You'll see an error but a <code>mysql2psql.yml</code> file should have been created.</li>\n<li>Edit <code>mysql2psql.yml</code></li>\n<li>Run <code>mysql2psql</code> again to migrate you data.</li>\n</ol>\n\n<p>Tip: Set <code>force_truncate</code> to <code>true</code> in your <code>mysql2psql.yml</code> config file if you want the postgresql database to be cleared before migrating your data.</p>\n" }, { "answer_id": 18580569, "author": "Michał Powaga", "author_id": 1027198, "author_profile": "https://Stackoverflow.com/users/1027198", "pm_score": 1, "selected": false, "text": "<p>I've used <a href=\"https://github.com/philipsoutham/py-mysql2pgsql\" rel=\"nofollow\">py-mysql2pgsql</a>. After installation it needs only simple configuration file in yml format (source, destination), e.g.:</p>\n\n<pre><code># if a socket is specified we will use that\n# if tcp is chosen you can use compression\nmysql:\n hostname: localhost\n port: 3306\n socket: /tmp/mysql.sock\n username: mysql2psql\n password:\n database: mysql2psql_test\n compress: false\ndestination:\n # if file is given, output goes to file, else postgres\n file:\n postgres:\n hostname: localhost\n port: 5432\n username: mysql2psql\n password:\n database: mysql2psql_test\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>&gt; py-mysql2pgsql -h\nusage: py-mysql2pgsql [-h] [-v] [-f FILE]\n\nTool for migrating/converting data from mysql to postgresql.\n\noptional arguments:\n -h, --help show this help message and exit\n -v, --verbose Show progress of data migration.\n -f FILE, --file FILE Location of configuration file (default:\n mysql2pgsql.yml). If none exists at that path,\n one will be created for you.\n</code></pre>\n\n<p>More on its home page <a href=\"https://github.com/philipsoutham/py-mysql2pgsql\" rel=\"nofollow\">https://github.com/philipsoutham/py-mysql2pgsql</a>.</p>\n" }, { "answer_id": 46362080, "author": "Cees Timmerman", "author_id": 819417, "author_profile": "https://Stackoverflow.com/users/819417", "pm_score": 0, "selected": false, "text": "<p><a href=\"https://en.wikibooks.org/wiki/Converting_MySQL_to_PostgreSQL\" rel=\"nofollow noreferrer\">This page</a> lists the syntax differences, but a simple working query converter i haven't found yet. Using an <a href=\"https://en.wikipedia.org/wiki/Object-relational_mapping\" rel=\"nofollow noreferrer\">ORM</a> package instead of raw SQL could prevent these issues.</p>\n\n<p>I'm currently hacking up a converter for a legacy codebase:</p>\n\n<pre><code>function mysql2pgsql($mysql){\n return preg_replace(\"/limit (\\d+), *(\\d+)/i\", \"limit $1 offset $2\", preg_replace(\"/as '([^']+)'/i\", 'as \"$1\"', $mysql)); // Note: limit needs order\n}\n</code></pre>\n\n<p>For <code>CREATE</code> statements, <a href=\"http://www.sqlines.com/online\" rel=\"nofollow noreferrer\">SQLines</a> converts most of them online. I still had to edit the mysqldump afterwards, though: </p>\n\n<pre><code>\"mediumtext\" -&gt; \"text\", \"^LOCK.*\" -&gt; \"\", \"^UNLOCK.*\" -&gt; \"\", \"`\" -&gt; '\"', \"'\" -&gt; \"''\" in 'data', \"0000-00-00\" -&gt; \"2000-01-01\", deduplicate constraint names, \" CHARACTER SET utf8 \" -&gt; \" \".\n\"int(10)\" -&gt; \"int\" was missed in the last table, so pass that part of the mysqldump through http://www.sqlines.com/online again.\n</code></pre>\n" }, { "answer_id": 47132273, "author": "R.Sehdev", "author_id": 3919627, "author_profile": "https://Stackoverflow.com/users/3919627", "pm_score": 4, "selected": false, "text": "<p>Try this one , it works like charm !!</p>\n\n<pre><code>http://www.sqlines.com/online\n</code></pre>\n" }, { "answer_id": 67422858, "author": "Paul Rougieux", "author_id": 2641825, "author_profile": "https://Stackoverflow.com/users/2641825", "pm_score": 2, "selected": false, "text": "<p>Install <a href=\"https://github.com/dimitri/pgloader\" rel=\"nofollow noreferrer\">pgloader</a> on Debian (or Ubuntu):</p>\n<pre><code>sudo apt install pgloader\n</code></pre>\n<p>Login as the postgres user and create a database</p>\n<pre><code>sudo su postgres\ncreatedb -O user db_migrated\n</code></pre>\n<p>Transfer data from the mysql database to postgresql</p>\n<pre><code>pgloader mysql://user@localhost/db postgresql:///db_migrated\n</code></pre>\n<p>Check also <a href=\"https://tapoueh.org/blog/2014/05/why-is-pgloader-so-much-faster/\" rel=\"nofollow noreferrer\">Dimitri Fontaine's rewrite of pgloader from python to common lisp</a> so that he could implement real threading.</p>\n<h1>Installation on other platforms</h1>\n<ul>\n<li><p><a href=\"https://github.com/dimitri/pgloader/issues/1017#issuecomment-566469443\" rel=\"nofollow noreferrer\">To install pgloader on Windows</a>, you can use the Windows Subsystem for Linux.</p>\n</li>\n<li><p><a href=\"https://github.com/dimitri/pgloader#building-from-sources-on-macos\" rel=\"nofollow noreferrer\">To install pgloader on Mac</a>, you can use: <code>brew install --HEAD pgloader</code>.</p>\n</li>\n</ul>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/92043", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4196/" ]
I've tried the tools listed [here](http://wiki.postgresql.org/wiki/Converting_from_other_Databases_to_PostgreSQL), some with more success than others, but none gave me valid postgres syntax I could use (tinyint errors etc.)
There's a `mysqldump` option which makes it output PostgreSQL code: ``` mysqldump --compatible=postgresql ... ``` But that doesn't work too well. Instead, please see the [mysql-to-postgres](https://github.com/maxlapshin/mysql2postgres) tool as [described in Linus Oleander's answer](https://stackoverflow.com/a/15670452/19163).
92,076
<p>I'm writing some xlst file which I want to use under linux and Windows. In this file I use node-set function which declared in different namespaces for MSXML and xsltproc ("urn:schemas-microsoft-com:xslt" and "<a href="http://exslt.org/common" rel="nofollow noreferrer">http://exslt.org/common</a>" respectively). Is there any platform independent way of using node-set?</p>
[ { "answer_id": 92119, "author": "Ben", "author_id": 15480, "author_profile": "https://Stackoverflow.com/users/15480", "pm_score": 1, "selected": false, "text": "<p>Firefox 3 implements node-set (as part of the EXSLT 2.0 namespace improvements) in it's client-side XSLT processing.</p>\n\n<p>Maybe not quite the answer you were looking for - but it could be, depending on the context of your problem. ;-)</p>\n" }, { "answer_id": 92511, "author": "James Sulak", "author_id": 207, "author_profile": "https://Stackoverflow.com/users/207", "pm_score": 3, "selected": false, "text": "<p>You can use the function function-available() to determine which function you should use:</p>\n\n<pre><code>&lt;xsl:choose&gt;\n &lt;xsl:when test=\"function-available('exslt:node-set')\"&gt;\n &lt;xsl:apply-templates select=\"exslt:node-set($nodelist)\" /&gt;\n &lt;/xsl:when&gt;\n &lt;xsl:when test=\"function-available('msxsl:node-set')\"&gt;\n &lt;xsl:apply-templates select=\"msxsl:node-set($nodelist)\" /&gt;\n &lt;/xsl:when&gt;\n &lt;!-- etc --&gt;\n&lt;/xsl:choose&gt;\n</code></pre>\n\n<p>You can even wrap this logic in a named template and call it with the nodeset as a parameter.</p>\n" }, { "answer_id": 97424, "author": "ykaganovich", "author_id": 10026, "author_profile": "https://Stackoverflow.com/users/10026", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://www.exslt.org\" rel=\"nofollow noreferrer\">Exslt</a> is \"supposed to be\" a platform-independent set of xslt extensions, but only so far as various xslt processors choose to implement them.</p>\n\n<p>There's <a href=\"http://www.tkachenko.com/blog/archives/000559.html\" rel=\"nofollow noreferrer\">some evidence</a> that MSXML actually does support exsl:node-set(), but I don't know for sure.</p>\n\n<p>There is an <a href=\"http://www.xml.com/pub/a/2003/08/06/exslt.html\" rel=\"nofollow noreferrer\">old article</a> discussing <a href=\"http://fxsl.sourceforge.net/\" rel=\"nofollow noreferrer\">an implementation</a> of exslt on top of MSXML.</p>\n\n<p>Otherwise, I think function-available() is your friend :)</p>\n" }, { "answer_id": 100537, "author": "Lukáš Rampa", "author_id": 10560, "author_profile": "https://Stackoverflow.com/users/10560", "pm_score": 0, "selected": false, "text": "<p>If there is not a particular reason to use msxml implementation of node-set on windows you coul use exslt one everywhere, by including the implemenation downloaded from <a href=\"http://exslt.org\" rel=\"nofollow noreferrer\">http://exslt.org</a> with your stylesheet, <a href=\"http://exslt.org/howto.html\" rel=\"nofollow noreferrer\">exslt howto</a> describes the needed steps. You can use either \"Extension namespaces\" way or \"Named templates\" way.</p>\n" }, { "answer_id": 329989, "author": "Dimitre Novatchev", "author_id": 36305, "author_profile": "https://Stackoverflow.com/users/36305", "pm_score": 3, "selected": false, "text": "<p><strong>Yes, there is a good and universal solution</strong>.</p>\n\n<p><a href=\"http://exslt.org/\" rel=\"noreferrer\"><strong>EXSLT</strong></a>'s function <a href=\"http://exslt.org/exsl/functions/node-set/index.html\" rel=\"noreferrer\"><strong>common:node-set()</strong></a> can be implemented as an inline Javascript function and is thus available with any browser that supports Javascript (practically all major browsers without exception).</p>\n\n<p>This technique was first discovered by <a href=\"http://greenbytes.de/tech/webdav/\" rel=\"noreferrer\"><strong>Julian Reschke</strong></a> and after he published it on the <a href=\"http://www.biglist.com/lists/xsl-list/archives/\" rel=\"noreferrer\"><strong>xsl-list</strong></a>, was publicized by <a href=\"http://dpcarlisle.blogspot.com/\" rel=\"noreferrer\"><strong>David Carlisle</strong></a>. On the <a href=\"http://dpcarlisle.blogspot.com/2007/05/exslt-node-set-function.html\" rel=\"noreferrer\"><strong>blog of David Carlisle</strong></a> there is also a link to a test page that shows if the common:node-set() function thus implemented works with the browser of your choice.</p>\n\n<p>To summarize:</p>\n\n<ol>\n<li>First go <a href=\"http://dpcarlisle.blogspot.com/2007/05/exslt-node-set-function.html\" rel=\"noreferrer\"><strong>here</strong></a> and read the explanation.</li>\n<li>Then try the test page. In particular, verify that it works with IE (that means with MSXML)</li>\n<li>Finally, use the code.</li>\n</ol>\n\n<p>Do enjoy!</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/92076", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17569/" ]
I'm writing some xlst file which I want to use under linux and Windows. In this file I use node-set function which declared in different namespaces for MSXML and xsltproc ("urn:schemas-microsoft-com:xslt" and "<http://exslt.org/common>" respectively). Is there any platform independent way of using node-set?
You can use the function function-available() to determine which function you should use: ``` <xsl:choose> <xsl:when test="function-available('exslt:node-set')"> <xsl:apply-templates select="exslt:node-set($nodelist)" /> </xsl:when> <xsl:when test="function-available('msxsl:node-set')"> <xsl:apply-templates select="msxsl:node-set($nodelist)" /> </xsl:when> <!-- etc --> </xsl:choose> ``` You can even wrap this logic in a named template and call it with the nodeset as a parameter.
92,082
<p>How can I add a column with a default value to an existing table in <a href="http://en.wikipedia.org/wiki/Microsoft_SQL_Server#Genesis" rel="noreferrer">SQL Server 2000</a> / <a href="http://en.wikipedia.org/wiki/Microsoft_SQL_Server#SQL_Server_2005" rel="noreferrer">SQL Server 2005</a>?</p>
[ { "answer_id": 92092, "author": "Benjamin Autin", "author_id": 1440933, "author_profile": "https://Stackoverflow.com/users/1440933", "pm_score": 6, "selected": false, "text": "<pre><code>ALTER TABLE ADD ColumnName {Column_Type} Constraint\n</code></pre>\n\n<p>The MSDN article <em><a href=\"http://msdn.microsoft.com/en-us/library/ms190273.aspx\" rel=\"noreferrer\">ALTER TABLE (Transact-SQL)</a></em> has all of the alter table syntax.</p>\n" }, { "answer_id": 92101, "author": "dbugger", "author_id": 15754, "author_profile": "https://Stackoverflow.com/users/15754", "pm_score": 10, "selected": false, "text": "<pre><code>ALTER TABLE Protocols\nADD ProtocolTypeID int NOT NULL DEFAULT(1)\nGO\n</code></pre>\n\n<p>The inclusion of the <strong>DEFAULT</strong> fills the column in <strong>existing</strong> rows with the default value, so the NOT NULL constraint is not violated. </p>\n" }, { "answer_id": 92123, "author": "James Boother", "author_id": 16030, "author_profile": "https://Stackoverflow.com/users/16030", "pm_score": 13, "selected": true, "text": "<h2>Syntax:</h2>\n\n<pre><code>ALTER TABLE {TABLENAME} \nADD {COLUMNNAME} {TYPE} {NULL|NOT NULL} \nCONSTRAINT {CONSTRAINT_NAME} DEFAULT {DEFAULT_VALUE}\nWITH VALUES\n</code></pre>\n\n<h2>Example:</h2>\n\n<pre><code>ALTER TABLE SomeTable\n ADD SomeCol Bit NULL --Or NOT NULL.\n CONSTRAINT D_SomeTable_SomeCol --When Omitted a Default-Constraint Name is autogenerated.\n DEFAULT (0)--Optional Default-Constraint.\nWITH VALUES --Add if Column is Nullable and you want the Default Value for Existing Records.\n</code></pre>\n\n<h2>Notes:</h2>\n\n<p><strong>Optional Constraint Name:</strong><br />\nIf you leave out <code>CONSTRAINT D_SomeTable_SomeCol</code> then SQL Server will autogenerate<br />\n&nbsp; &nbsp; a Default-Contraint with a funny Name like: <code>DF__SomeTa__SomeC__4FB7FEF6</code><br /></p>\n\n<p><strong>Optional With-Values Statement:</strong><br />\nThe <code>WITH VALUES</code> is only needed when your Column is Nullable<br />\n&nbsp; &nbsp; and you want the Default Value used for Existing Records.<br />\nIf your Column is <code>NOT NULL</code>, then it will automatically use the Default Value<br />\n&nbsp; &nbsp; for all Existing Records, whether you specify <code>WITH VALUES</code> or not.</p>\n\n<p><strong>How Inserts work with a Default-Constraint:</strong><br />\nIf you insert a Record into <code>SomeTable</code> and do <strong><em>not</em></strong> Specify <code>SomeCol</code>'s value, then it will Default to <code>0</code>.<br />\nIf you insert a Record <strong><em>and</em></strong> Specify <code>SomeCol</code>'s value as <code>NULL</code> (and your column allows nulls),<br />\n&nbsp; &nbsp; then the Default-Constraint will <strong><em>not</em></strong> be used and <code>NULL</code> will be inserted as the Value.<br /></p>\n\n<p>Notes were based on everyone's great feedback below.<br />\nSpecial Thanks to:<br />\n&nbsp; &nbsp; @Yatrix, @WalterStabosz, @YahooSerious, and @StackMan for their Comments.</p>\n" }, { "answer_id": 92166, "author": "ddc0660", "author_id": 16027, "author_profile": "https://Stackoverflow.com/users/16027", "pm_score": 7, "selected": false, "text": "<pre><code>ALTER TABLE &lt;table name&gt; \nADD &lt;new column name&gt; &lt;data type&gt; NOT NULL\nGO\nALTER TABLE &lt;table name&gt; \nADD CONSTRAINT &lt;constraint name&gt; DEFAULT &lt;default value&gt; FOR &lt;new column name&gt;\nGO\n</code></pre>\n" }, { "answer_id": 128056, "author": "jalbert", "author_id": 1360388, "author_profile": "https://Stackoverflow.com/users/1360388", "pm_score": 7, "selected": false, "text": "<p>Beware when the column you are adding has a <code>NOT NULL</code> constraint, yet does not have a <code>DEFAULT</code> constraint (value). The <code>ALTER TABLE</code> statement will fail in that case if the table has any rows in it. The solution is to either remove the <code>NOT NULL</code> constraint from the new column, or provide a <code>DEFAULT</code> constraint for it.</p>\n" }, { "answer_id": 4401381, "author": "JerryOL", "author_id": 7964, "author_profile": "https://Stackoverflow.com/users/7964", "pm_score": 7, "selected": false, "text": "<p>Use:</p>\n\n<pre><code>-- Add a column with a default DateTime \n-- to capture when each record is added.\n\nALTER TABLE myTableName \nADD RecordAddedDate SMALLDATETIME NULL DEFAULT (GETDATE()) \nGO \n</code></pre>\n" }, { "answer_id": 5639381, "author": "phunk_munkie", "author_id": 704595, "author_profile": "https://Stackoverflow.com/users/704595", "pm_score": 8, "selected": false, "text": "<p>When adding a <em>nullable column</em>, <code>WITH VALUES</code> will ensure that the specific DEFAULT value is applied to existing rows:</p>\n\n<pre><code>ALTER TABLE table\nADD column BIT -- Demonstration with NULL-able column added\nCONSTRAINT Constraint_name DEFAULT 0 WITH VALUES\n</code></pre>\n" }, { "answer_id": 8285284, "author": "gngolakia", "author_id": 1050111, "author_profile": "https://Stackoverflow.com/users/1050111", "pm_score": 6, "selected": false, "text": "<p>You can do the thing with T-SQL in the following way.</p>\n\n<pre><code> ALTER TABLE {TABLENAME}\n ADD {COLUMNNAME} {TYPE} {NULL|NOT NULL}\n CONSTRAINT {CONSTRAINT_NAME} DEFAULT {DEFAULT_VALUE}\n</code></pre>\n\n<p>As well as you can use <a href=\"http://en.wikipedia.org/wiki/SQL_Server_Management_Studio\" rel=\"noreferrer\">SQL Server Management Studio</a> also by right clicking table in the Design menu, setting the default value to table.</p>\n\n<p>And furthermore, if you want to add the same column (if it does not exists) to all tables in database, then use:</p>\n\n<pre><code> USE AdventureWorks;\n EXEC sp_msforeachtable\n'PRINT ''ALTER TABLE ? ADD Date_Created DATETIME DEFAULT GETDATE();''' ;\n</code></pre>\n" }, { "answer_id": 8334988, "author": "Jack", "author_id": 1074505, "author_profile": "https://Stackoverflow.com/users/1074505", "pm_score": 6, "selected": false, "text": "<p>In SQL Server 2008-R2, I go to the design mode - in a test database - and add my two columns using the designer and made the settings with the GUI, and then the infamous <kbd>Right-Click</kbd> gives the option \"<strong><em>Generate Change Script</em></strong>\"!</p>\n\n<p>Bang up pops a little window with, you guessed it, the properly formatted guaranteed-to-work change script. Hit the easy button.</p>\n" }, { "answer_id": 8640716, "author": "giá vàng", "author_id": 1013886, "author_profile": "https://Stackoverflow.com/users/1013886", "pm_score": 6, "selected": false, "text": "<p>Use:</p>\n\n<pre><code>ALTER TABLE {TABLENAME} \nADD {COLUMNNAME} {TYPE} {NULL|NOT NULL} \nCONSTRAINT {CONSTRAINT_NAME} DEFAULT {DEFAULT_VALUE}\n</code></pre>\n\n<p>Reference: <a href=\"https://msdn.microsoft.com/en-us/library/ms190273.aspx\" rel=\"noreferrer\">ALTER TABLE (Transact-SQL)</a> (MSDN)</p>\n" }, { "answer_id": 10756580, "author": "adeel41", "author_id": 189738, "author_profile": "https://Stackoverflow.com/users/189738", "pm_score": 7, "selected": false, "text": "<p>The most basic version with two lines only</p>\n\n<pre><code>ALTER TABLE MyTable\nADD MyNewColumn INT NOT NULL DEFAULT 0\n</code></pre>\n" }, { "answer_id": 10843628, "author": "Christo", "author_id": 214747, "author_profile": "https://Stackoverflow.com/users/214747", "pm_score": 6, "selected": false, "text": "<p>Alternatively, you can add a default without having to explicitly name the constraint:</p>\n\n<pre><code>ALTER TABLE [schema].[tablename] ADD DEFAULT ((0)) FOR [columnname]\n</code></pre>\n\n<p>If you have an issue with existing default constraints when creating this constraint then they can be removed by:</p>\n\n<pre><code>alter table [schema].[tablename] drop constraint [constraintname]\n</code></pre>\n" }, { "answer_id": 11813717, "author": "Evan V", "author_id": 1441037, "author_profile": "https://Stackoverflow.com/users/1441037", "pm_score": 7, "selected": false, "text": "<pre><code>ALTER TABLE MYTABLE ADD MYNEWCOLUMN VARCHAR(200) DEFAULT 'SNUGGLES'\n</code></pre>\n" }, { "answer_id": 22199380, "author": "andy", "author_id": 3224712, "author_profile": "https://Stackoverflow.com/users/3224712", "pm_score": 5, "selected": false, "text": "<p>Example:</p>\n\n<pre><code>ALTER TABLE [Employees] ADD Seniority int not null default 0 GO\n</code></pre>\n" }, { "answer_id": 24333598, "author": "Catto", "author_id": 17877, "author_profile": "https://Stackoverflow.com/users/17877", "pm_score": 6, "selected": false, "text": "<p>To add a column to an existing database table with a default value, we can use:</p>\n\n<pre><code>ALTER TABLE [dbo.table_name]\n ADD [Column_Name] BIT NOT NULL\nDefault ( 0 )\n</code></pre>\n\n<p>Here is another way to add a column to an existing database table with a default value.</p>\n\n<p>A much more thorough SQL script to add a column with a default value is below including checking if the column exists before adding it also checkin the constraint and dropping it if there is one. This script also names the constraint so we can have a nice naming convention (I like DF_) and if not SQL will give us a constraint with a name which has a randomly generated number; so it's nice to be able to name the constraint too.</p>\n\n<pre><code>-------------------------------------------------------------------------\n-- Drop COLUMN\n-- Name of Column: Column_EmployeeName\n-- Name of Table: table_Emplyee\n--------------------------------------------------------------------------\nIF EXISTS (\n SELECT 1\n FROM INFORMATION_SCHEMA.COLUMNS\n WHERE TABLE_NAME = 'table_Emplyee'\n AND COLUMN_NAME = 'Column_EmployeeName'\n )\n BEGIN\n\n IF EXISTS ( SELECT 1\n FROM sys.default_constraints\n WHERE object_id = OBJECT_ID('[dbo].[DF_table_Emplyee_Column_EmployeeName]')\n AND parent_object_id = OBJECT_ID('[dbo].[table_Emplyee]')\n )\n BEGIN\n ------ DROP Contraint\n\n ALTER TABLE [dbo].[table_Emplyee] DROP CONSTRAINT [DF_table_Emplyee_Column_EmployeeName]\n PRINT '[DF_table_Emplyee_Column_EmployeeName] was dropped'\n END\n -- ----- DROP Column -----------------------------------------------------------------\n ALTER TABLE [dbo].table_Emplyee\n DROP COLUMN Column_EmployeeName\n PRINT 'Column Column_EmployeeName in images table was dropped'\n END\n\n--------------------------------------------------------------------------\n-- ADD COLUMN Column_EmployeeName IN table_Emplyee table\n--------------------------------------------------------------------------\nIF NOT EXISTS (\n SELECT 1\n FROM INFORMATION_SCHEMA.COLUMNS\n WHERE TABLE_NAME = 'table_Emplyee'\n AND COLUMN_NAME = 'Column_EmployeeName'\n )\n BEGIN\n ----- ADD Column &amp; Contraint\n ALTER TABLE dbo.table_Emplyee\n ADD Column_EmployeeName BIT NOT NULL\n CONSTRAINT [DF_table_Emplyee_Column_EmployeeName] DEFAULT (0)\n PRINT 'Column [DF_table_Emplyee_Column_EmployeeName] in table_Emplyee table was Added'\n PRINT 'Contraint [DF_table_Emplyee_Column_EmployeeName] was Added'\n END\n\nGO\n</code></pre>\n\n<p>These are two ways to add a column to an existing database table with a default value.</p>\n" }, { "answer_id": 25600651, "author": "Jakir Hossain", "author_id": 3260960, "author_profile": "https://Stackoverflow.com/users/3260960", "pm_score": 4, "selected": false, "text": "<p>Try this</p>\n\n<pre><code>ALTER TABLE Product\nADD ProductID INT NOT NULL DEFAULT(1)\nGO\n</code></pre>\n" }, { "answer_id": 26367963, "author": "Gabriel L.", "author_id": 2826885, "author_profile": "https://Stackoverflow.com/users/2826885", "pm_score": 7, "selected": false, "text": "<p>If you want to add multiple columns you can do it this way for example:</p>\n\n<pre><code>ALTER TABLE YourTable\n ADD Column1 INT NOT NULL DEFAULT 0,\n Column2 INT NOT NULL DEFAULT 1,\n Column3 VARCHAR(50) DEFAULT 'Hello'\nGO\n</code></pre>\n" }, { "answer_id": 27127950, "author": "Mohit Tamrakar", "author_id": 3414238, "author_profile": "https://Stackoverflow.com/users/3414238", "pm_score": 5, "selected": false, "text": "<p>Example:</p>\n\n<pre><code>ALTER TABLE tes \nADD ssd NUMBER DEFAULT '0';\n</code></pre>\n" }, { "answer_id": 30847241, "author": "Naveen Desosha", "author_id": 1914998, "author_profile": "https://Stackoverflow.com/users/1914998", "pm_score": 4, "selected": false, "text": "<p>SQL Server + Alter Table + Add Column + Default Value uniqueidentifier </p>\n\n<pre><code>ALTER TABLE Product \nADD ReferenceID uniqueidentifier not null \ndefault (cast(cast(0 as binary) as uniqueidentifier))\n</code></pre>\n" }, { "answer_id": 34131674, "author": "Chanukya", "author_id": 5093602, "author_profile": "https://Stackoverflow.com/users/5093602", "pm_score": 3, "selected": false, "text": "<p>SQL Server + Alter Table + Add Column + Default Value uniqueidentifier...</p>\n\n<pre><code>ALTER TABLE [TABLENAME] ADD MyNewColumn INT not null default 0 GO\n</code></pre>\n" }, { "answer_id": 34208117, "author": "Tony L.", "author_id": 3347858, "author_profile": "https://Stackoverflow.com/users/3347858", "pm_score": 6, "selected": false, "text": "<p>This can be done in the SSMS GUI as well. I show a default date below but the default value can be whatever, of course.</p>\n<ol>\n<li>Put your table in design view (Right click on the table in object\nexplorer-&gt;Design)</li>\n<li>Add a column to the table (or click on the column you want to update if\nit already exists)</li>\n<li>In Column Properties below, enter <code>(getdate())</code> or <code>'abc'</code> or <code>0</code> or whatever value you want in <em>Default Value or Binding</em> field as pictured below:</li>\n</ol>\n<p><a href=\"https://i.stack.imgur.com/FQbi1.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/FQbi1.png\" alt=\"enter image description here\" /></a></p>\n" }, { "answer_id": 34414140, "author": "Chiragkumar Thakar", "author_id": 4574888, "author_profile": "https://Stackoverflow.com/users/4574888", "pm_score": 4, "selected": false, "text": "<p>Add a new column to a table:</p>\n\n<pre><code>ALTER TABLE [table]\nADD Column1 Datatype\n</code></pre>\n\n<p><strong>For example,</strong></p>\n\n<pre><code>ALTER TABLE [test]\nADD ID Int\n</code></pre>\n\n<p>If the user wants to make it auto incremented then:</p>\n\n<pre><code>ALTER TABLE [test]\nADD ID Int IDENTITY(1,1) NOT NULL\n</code></pre>\n" }, { "answer_id": 36856212, "author": "Jeevan Gharti", "author_id": 2650834, "author_profile": "https://Stackoverflow.com/users/2650834", "pm_score": 4, "selected": false, "text": "<pre><code>IF NOT EXISTS (\n SELECT * FROM INFORMATION_SCHEMA.COLUMNS\n WHERE TABLE_NAME ='TABLENAME' AND COLUMN_NAME = 'COLUMNNAME'\n)\nBEGIN\n ALTER TABLE TABLENAME ADD COLUMNNAME Nvarchar(MAX) Not Null default\nEND\n</code></pre>\n" }, { "answer_id": 37118360, "author": "usefulBee", "author_id": 2093880, "author_profile": "https://Stackoverflow.com/users/2093880", "pm_score": 3, "selected": false, "text": "<p>If the default is Null, then:</p>\n\n<ol>\n<li>In SQL Server, open the tree of the targeted table</li>\n<li>Right click \"Columns\" ==> <code>New Column</code></li>\n<li>Type the column Name, <code>Select Type</code>, and Check the Allow Nulls Checkbox</li>\n<li>From the Menu Bar, click <code>Save</code></li>\n</ol>\n\n<p>Done!</p>\n" }, { "answer_id": 37412089, "author": "Sandeep Kumar", "author_id": 6280120, "author_profile": "https://Stackoverflow.com/users/6280120", "pm_score": 3, "selected": false, "text": "<pre><code>ALTER TABLE tbl_table ADD int_column int NOT NULL DEFAULT(0)\n</code></pre>\n\n<p>From this query you can add a column of datatype integer with default value 0.</p>\n" }, { "answer_id": 39405328, "author": "Mohit Dagar", "author_id": 4261212, "author_profile": "https://Stackoverflow.com/users/4261212", "pm_score": 4, "selected": false, "text": "<p>This can be done by the below code.</p>\n\n<pre><code>CREATE TABLE TestTable\n (FirstCol INT NOT NULL)\n GO\n ------------------------------\n -- Option 1\n ------------------------------\n -- Adding New Column\n ALTER TABLE TestTable\n ADD SecondCol INT\n GO\n -- Updating it with Default\n UPDATE TestTable\n SET SecondCol = 0\n GO\n -- Alter\n ALTER TABLE TestTable\n ALTER COLUMN SecondCol INT NOT NULL\n GO\n</code></pre>\n" }, { "answer_id": 40145396, "author": "Laxmi", "author_id": 6755093, "author_profile": "https://Stackoverflow.com/users/6755093", "pm_score": 5, "selected": false, "text": "<p><strong>First create a table with name student:</strong></p>\n\n<pre><code>CREATE TABLE STUDENT (STUDENT_ID INT NOT NULL)\n</code></pre>\n\n<p><strong>Add one column to it:</strong></p>\n\n<pre><code>ALTER TABLE STUDENT \nADD STUDENT_NAME INT NOT NULL DEFAULT(0)\n\nSELECT * \nFROM STUDENT\n</code></pre>\n\n<p>The table is created and a column is added to an existing table with a default value.</p>\n\n<p><a href=\"https://i.stack.imgur.com/lMXvg.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/lMXvg.png\" alt=\"Image 1\"></a></p>\n" }, { "answer_id": 42695588, "author": "Ananda G", "author_id": 2256217, "author_profile": "https://Stackoverflow.com/users/2256217", "pm_score": 4, "selected": false, "text": "<p>Well, I now have some modification to my previous answer. I have noticed that none of the answers mentioned <code>IF NOT EXISTS</code>. So I am going to provide a new solution of it as I have faced some problems altering the table.</p>\n\n<pre><code>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.columns WHERE table_name = 'TaskSheet' AND column_name = 'IsBilledToClient')\nBEGIN\nALTER TABLE dbo.TaskSheet ADD\n IsBilledToClient bit NOT NULL DEFAULT ((1))\nEND\nGO\n</code></pre>\n\n<p>Here <code>TaskSheet</code> is the particular table name and <code>IsBilledToClient</code> is the new column which you are going to insert and <code>1</code> the default value. That means in the new column what will be the value of the existing rows, therefore one will be set automatically there. However, you can change as you wish with the respect of the column type like I have used <code>BIT</code>, so I put in default value 1.</p>\n\n<p>I suggest the above system, because I have faced a problem. So what is the problem? The problem is, if the <code>IsBilledToClient</code> column does exists in the table table then if you execute only the portion of the code given below you will see an error in the SQL server Query builder. But if it does not exist then for the first time there will be no error when executing.</p>\n\n<pre><code>ALTER TABLE {TABLENAME}\nADD {COLUMNNAME} {TYPE} {NULL|NOT NULL}\nCONSTRAINT {CONSTRAINT_NAME} DEFAULT {DEFAULT_VALUE}\n[WITH VALUES]\n</code></pre>\n" }, { "answer_id": 42801734, "author": "Arun D", "author_id": 5261509, "author_profile": "https://Stackoverflow.com/users/5261509", "pm_score": 3, "selected": false, "text": "<p>You can use this query:</p>\n\n<pre><code>ALTER TABLE tableName ADD ColumnName datatype DEFAULT DefaultValue;\n</code></pre>\n" }, { "answer_id": 43800406, "author": "Ste Bov", "author_id": 4442467, "author_profile": "https://Stackoverflow.com/users/4442467", "pm_score": 5, "selected": false, "text": "<p>This has a lot of answers, but I feel the need to add this extended method. This seems a lot longer, but it is extremely useful if you're adding a NOT NULL field to a table with millions of rows in an active database.</p>\n\n<pre><code>ALTER TABLE {schemaName}.{tableName}\n ADD {columnName} {datatype} NULL\n CONSTRAINT {constraintName} DEFAULT {DefaultValue}\n\nUPDATE {schemaName}.{tableName}\n SET {columnName} = {DefaultValue}\n WHERE {columName} IS NULL\n\nALTER TABLE {schemaName}.{tableName}\n ALTER COLUMN {columnName} {datatype} NOT NULL\n</code></pre>\n\n<p>What this will do is add the column as a nullable field and with the default value, update all fields to the default value (or you can assign more meaningful values), and finally it will change the column to be NOT NULL.</p>\n\n<p>The reason for this is if you update a large scale table and add a new not null field it has to write to every single row and hereby will lock out the entire table as it adds the column and then writes all the values.</p>\n\n<p>This method will add the nullable column which operates a lot faster by itself, then fills the data before setting the not null status.</p>\n\n<p>I've found that doing the entire thing in one statement will lock out one of our more active tables for 4-8 minutes and quite often I have killed the process. This method each part usually takes only a few seconds and causes minimal locking.</p>\n\n<p>Additionally, if you have a table in the area of billions of rows it may be worth batching the update like so:</p>\n\n<pre><code>WHILE 1=1\nBEGIN\n UPDATE TOP (1000000) {schemaName}.{tableName}\n SET {columnName} = {DefaultValue}\n WHERE {columName} IS NULL\n\n IF @@ROWCOUNT &lt; 1000000\n BREAK;\nEND\n</code></pre>\n" }, { "answer_id": 43869564, "author": "Mohammad Reza Shahrestani", "author_id": 6174449, "author_profile": "https://Stackoverflow.com/users/6174449", "pm_score": 3, "selected": false, "text": "<p>Right click on the table name and click on <strong>Design</strong>, click under the last column name and enter Column Name, Data Type, Allow Nulls.</p>\n\n<p>Then in bottom of page set a <strong>default value or binding</strong> : something like '1' for string or 1 for int.</p>\n" }, { "answer_id": 46561968, "author": "raju chowrsiya", "author_id": 5819598, "author_profile": "https://Stackoverflow.com/users/5819598", "pm_score": 3, "selected": false, "text": "<p>step-1. FIRST YOU HAVE TO ALTER TABLE WITH ADD a FIELD</p>\n\n<pre><code>alter table table_name add field field_name data_type\n</code></pre>\n\n<p>step-2 CREATE DEFAULT</p>\n\n<pre><code>USE data_base_name;\nGO\nCREATE DEFAULT default_name AS 'default_value';\n</code></pre>\n\n<p>step-3 THEN YOU HAVE TO EXECUTE THIS PROCEDURE</p>\n\n<pre><code>exec sp_bindefault 'default_name' , 'schema_name.table_name.field_name'\n</code></pre>\n\n<p>example - </p>\n\n<pre><code>USE master;\nGO\nEXEC sp_bindefault 'today', 'HumanResources.Employee.HireDate';\n</code></pre>\n" }, { "answer_id": 48617607, "author": "Akhil Singh", "author_id": 7528842, "author_profile": "https://Stackoverflow.com/users/7528842", "pm_score": 5, "selected": false, "text": "<p>This is for SQL Server:</p>\n\n<pre><code>ALTER TABLE TableName\nADD ColumnName (type) -- NULL OR NOT NULL\nDEFAULT (default value)\nWITH VALUES\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>ALTER TABLE Activities\nADD status int NOT NULL DEFAULT (0)\nWITH VALUES\n</code></pre>\n\n<p>If you want to add constraints then:</p>\n\n<pre><code>ALTER TABLE Table_1\nADD row3 int NOT NULL\nCONSTRAINT CONSTRAINT_NAME DEFAULT (0)\nWITH VALUES\n</code></pre>\n" }, { "answer_id": 48687262, "author": "wild coder", "author_id": 9106094, "author_profile": "https://Stackoverflow.com/users/9106094", "pm_score": 4, "selected": false, "text": "<pre><code>--Adding Value with Default Value\nALTER TABLE TestTable\nADD ThirdCol INT NOT NULL DEFAULT(0)\nGO\n</code></pre>\n" }, { "answer_id": 48761215, "author": "Krishan Dutt Sharma", "author_id": 9308236, "author_profile": "https://Stackoverflow.com/users/9308236", "pm_score": 2, "selected": false, "text": "<pre><code>ALTER TABLE Table1 ADD Col3 INT NOT NULL DEFAULT(0)\n</code></pre>\n" }, { "answer_id": 49839398, "author": "Erfan Mohammadi", "author_id": 4214920, "author_profile": "https://Stackoverflow.com/users/4214920", "pm_score": 3, "selected": false, "text": "<pre><code>--Adding New Column with Default Value\nALTER TABLE TABLENAME \nADD COLUMNNAME DATATYPE NULL|NOT NULL DEFAULT (DEFAULT_VALUE)\n</code></pre>\n\n<p>OR</p>\n\n<pre><code>--Adding CONSTRAINT And Set Default Value on Column\nALTER TABLE TABLENAME ADD CONSTRAINT [CONSTRAINT_Name] DEFAULT \n(DEFAULT_VALUE) FOR [COLUMNNAME]\n</code></pre>\n" }, { "answer_id": 52053260, "author": "Anshul Dubey", "author_id": 5239013, "author_profile": "https://Stackoverflow.com/users/5239013", "pm_score": 4, "selected": false, "text": "<p>Try with the below query:</p>\n\n<pre><code>ALTER TABLE MyTable\nADD MyNewColumn DataType DEFAULT DefaultValue\n</code></pre>\n\n<p>This will add a new column into the Table.</p>\n" }, { "answer_id": 58934529, "author": "Samay", "author_id": 4675202, "author_profile": "https://Stackoverflow.com/users/4675202", "pm_score": 2, "selected": false, "text": "<p>In SQL Server, you can use below template:</p>\n\n<pre><code>ALTER TABLE {tablename}\nADD \n {columnname} {datatype} DEFAULT {default_value}\n</code></pre>\n\n<p>For example, to add a new column [Column1] of data type <code>int</code> with default value = 1 into an existing table [Table1] , you can use below query:</p>\n\n<pre><code>ALTER TABLE [Table1]\nADD \n [Column1] INT DEFAULT 1\n</code></pre>\n" }, { "answer_id": 59169992, "author": "wish", "author_id": 6293871, "author_profile": "https://Stackoverflow.com/users/6293871", "pm_score": 2, "selected": false, "text": "<p>ALTER table dataset.tablename\nADD column_current_ind integer DEFAULT 0</p>\n" }, { "answer_id": 61683667, "author": "jithu thomas", "author_id": 11170679, "author_profile": "https://Stackoverflow.com/users/11170679", "pm_score": 2, "selected": false, "text": "<p><code>OFFLINE</code> and <code>ONLINE</code> pertain to how to ALTER table performed on NDB Cluster Tables.\nNDB Cluster supports online ALTER TABLE operations using the ALGORITHM=INPLACE syntax in MySQL NDB Cluster 7.3 and later. NDB Cluster also supports an older syntax specific to NDB that uses the ONLINE and OFFLINE keywords. These keywords are deprecated beginning with MySQL NDB Cluster 7.3; they continue to be supported in MySQL NDB Cluster 7.4 but are subject to removal in a future version of NDB Cluster.</p>\n\n<p><code>IGNORE</code> pertains to how the ALTER statement will deal with duplicate value in the column that has newly added constraint UNIQUE. If IGNORE is not specified, ALTER will fail and not be applied. If IGNORE is specified, the first row of all duplicate rows is kept, the reset deleted and the ALTER applied.</p>\n\n<p>The <code>ALTER_SPECIFICATION</code> would be what you are changing. what column or index you are adding, dropping or modifying, or what constraints you are applying on the column. </p>\n\n<pre><code>ALTER [ONLINE | OFFLINE] [IGNORE] TABLE tbl_name\n alter_specification [, alter_specification] ...\n\n alter_specification:\n ...\n ADD [COLUMN] (col_name column_definition,...)\n ...\n\nEg: ALTER TABLE table1 ADD COLUMN foo INT DEFAULT 0;\n</code></pre>\n" }, { "answer_id": 62352803, "author": "Somendra Kanaujia", "author_id": 11784748, "author_profile": "https://Stackoverflow.com/users/11784748", "pm_score": 3, "selected": false, "text": "<pre><code>ALTER TABLE &lt;YOUR_TABLENAME&gt;\nADD &lt;YOUR_COLUMNNAME&gt; &lt;DATATYPE&gt; &lt;NULL|NOT NULL&gt; \nADD CONSTRAINT &lt;CONSTRAINT_NAME&gt; ----OPTIONAL\nDEFAULT &lt;DEFAULT_VALUE&gt;\n</code></pre>\n\n<p>If you are not giving constrain name then sql server use default name for this.</p>\n\n<p><strong>Example:-</strong></p>\n\n<pre><code>ALTER TABLE TEMP_TABLENAME\nADD COLUMN1 NUMERIC(10,0) NOT NULL\nADD CONSTRAINT ABCDE ----OPTIONAL\nDEFAULT (0)\n</code></pre>\n" }, { "answer_id": 69717519, "author": "Priyanka Vadhwani", "author_id": 10349278, "author_profile": "https://Stackoverflow.com/users/10349278", "pm_score": 0, "selected": false, "text": "<p><strong>SYNTAX:</strong></p>\n<pre><code>ALTER TABLE {TABLENAME} \nADD {COLUMNNAME} {TYPE} {NULL|NOT NULL} \nCONSTRAINT {CONSTRAINT_NAME} DEFAULT {DEFAULT_VALUE}\nWITH VALUES\n</code></pre>\n<p><strong>EXAMPLE:</strong></p>\n<pre><code>ALTER TABLE Admin_Master \nADD Can_View_Password BIT NULL \nCONSTRAINT DF_Admin_Master_Can_View_Password DEFAULT (1)\nWITH VALUES \n</code></pre>\n" }, { "answer_id": 70013571, "author": "ishant kaushik", "author_id": 16513489, "author_profile": "https://Stackoverflow.com/users/16513489", "pm_score": 3, "selected": false, "text": "<p>There are 2 different ways to address this problem.\nBoth adds a default value but adds a totally different meaning to the problem statement here.</p>\n<p>Lets start with creating some sample data.</p>\n<h2><strong>Create Sample Data</strong></h2>\n<pre><code>CREATE TABLE ExistingTable (ID INT)\nGO\nINSERT INTO ExistingTable (ID)\nVALUES (1), (2), (3)\nGO\nSELECT *\nFROM ExistingTable\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/4DGjz.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/4DGjz.png\" alt=\"enter image description here\" /></a></p>\n<h2><strong>1.Add Columns with Default Value for Future Inserts</strong></h2>\n<pre><code>ALTER TABLE ExistingTable\nADD ColWithDefault VARCHAR(10) DEFAULT 'Hi'\nGO\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/K0IzB.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/K0IzB.png\" alt=\"enter image description here\" /></a></p>\n<p>So now as we have added a default column when we are inserting a new record it will default it's value to <code>'Hi'</code> if value not provided</p>\n<pre><code>INSERT INTO ExistingTable(ID)\nVALUES (4)\nGO\nSelect * from ExistingTable\nGO\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/0Ddse.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/0Ddse.png\" alt=\"enter image description here\" /></a></p>\n<p>Well this addresses our problem to have default value but here is a catch to the problem.\nWhat if we want to have default value in all the columns not just the future inserts???\nFor this we have Method 2.</p>\n<h2><strong>2.Add Column with Default Value for ALL Inserts</strong></h2>\n<pre><code>ALTER TABLE ExistingTable\nADD DefaultColWithVal VARCHAR(10) DEFAULT 'DefaultAll'\nWITH VALUES\nGO\nSelect * from ExistingTable\nGO\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/WQEVe.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/WQEVe.png\" alt=\"enter image description here\" /></a></p>\n<p>The following script will add a new column with a default value in every possible scenario.</p>\n<p>Hope it adds value to the question asked.\nThanks.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/92082", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7241/" ]
How can I add a column with a default value to an existing table in [SQL Server 2000](http://en.wikipedia.org/wiki/Microsoft_SQL_Server#Genesis) / [SQL Server 2005](http://en.wikipedia.org/wiki/Microsoft_SQL_Server#SQL_Server_2005)?
Syntax: ------- ``` ALTER TABLE {TABLENAME} ADD {COLUMNNAME} {TYPE} {NULL|NOT NULL} CONSTRAINT {CONSTRAINT_NAME} DEFAULT {DEFAULT_VALUE} WITH VALUES ``` Example: -------- ``` ALTER TABLE SomeTable ADD SomeCol Bit NULL --Or NOT NULL. CONSTRAINT D_SomeTable_SomeCol --When Omitted a Default-Constraint Name is autogenerated. DEFAULT (0)--Optional Default-Constraint. WITH VALUES --Add if Column is Nullable and you want the Default Value for Existing Records. ``` Notes: ------ **Optional Constraint Name:** If you leave out `CONSTRAINT D_SomeTable_SomeCol` then SQL Server will autogenerate     a Default-Contraint with a funny Name like: `DF__SomeTa__SomeC__4FB7FEF6` **Optional With-Values Statement:** The `WITH VALUES` is only needed when your Column is Nullable     and you want the Default Value used for Existing Records. If your Column is `NOT NULL`, then it will automatically use the Default Value     for all Existing Records, whether you specify `WITH VALUES` or not. **How Inserts work with a Default-Constraint:** If you insert a Record into `SomeTable` and do ***not*** Specify `SomeCol`'s value, then it will Default to `0`. If you insert a Record ***and*** Specify `SomeCol`'s value as `NULL` (and your column allows nulls),     then the Default-Constraint will ***not*** be used and `NULL` will be inserted as the Value. Notes were based on everyone's great feedback below. Special Thanks to:     @Yatrix, @WalterStabosz, @YahooSerious, and @StackMan for their Comments.
92,093
<p>I am working on a SQL query that reads from a SQLServer database to produce an extract file. One of the requirements to remove the leading zeroes from a particular field, which is a simple <code>VARCHAR(10)</code> field. So, for example, if the field contains '00001A', the SELECT statement needs to return the data as '1A'.</p> <p>Is there a way in SQL to easily remove the leading zeroes in this way? I know there is an <code>RTRIM</code> function, but this seems only to remove spaces. </p>
[ { "answer_id": 92363, "author": "Ian Horwill", "author_id": 5816, "author_profile": "https://Stackoverflow.com/users/5816", "pm_score": 8, "selected": true, "text": "<pre><code>select substring(ColumnName, patindex('%[^0]%',ColumnName), 10)\n</code></pre>\n" }, { "answer_id": 4504913, "author": "Kathryn Wilson", "author_id": 550612, "author_profile": "https://Stackoverflow.com/users/550612", "pm_score": 2, "selected": false, "text": "<p>If you want the query to return a 0 instead of a string of zeroes or any other value for that matter you can turn this into a case statement like this:</p>\n\n<pre><code>select CASE\n WHEN ColumnName = substring(ColumnName, patindex('%[^0]%',ColumnName), 10) \n THEN '0'\n ELSE substring(ColumnName, patindex('%[^0]%',ColumnName), 10) \n END\n</code></pre>\n" }, { "answer_id": 11978913, "author": "MTZ", "author_id": 1601905, "author_profile": "https://Stackoverflow.com/users/1601905", "pm_score": 5, "selected": false, "text": "<pre><code>select replace(ltrim(replace(ColumnName,'0',' ')),' ','0')\n</code></pre>\n" }, { "answer_id": 12012414, "author": "Nat", "author_id": 1607814, "author_profile": "https://Stackoverflow.com/users/1607814", "pm_score": 3, "selected": false, "text": "<pre><code>select substring(substring('B10000N0Z', patindex('%[0]%','B10000N0Z'), 20), \n patindex('%[^0]%',substring('B10000N0Z', patindex('%[0]%','B10000N0Z'), \n 20)), 20)\n</code></pre>\n\n<p>returns <code>N0Z</code>, that is, will get rid of leading zeroes and anything that comes before them.</p>\n" }, { "answer_id": 22939235, "author": "Afzal", "author_id": 3511273, "author_profile": "https://Stackoverflow.com/users/3511273", "pm_score": -1, "selected": false, "text": "<p>To remove the leading 0 from month following statement will definitely work.</p>\n\n<pre><code>SELECT replace(left(Convert(nvarchar,GETDATE(),101),2),'0','')+RIGHT(Convert(nvarchar,GETDATE(),101),8) \n</code></pre>\n\n<p>Just Replace <code>GETDATE()</code> with the date field of your Table.</p>\n" }, { "answer_id": 25399844, "author": "user3809240", "author_id": 3809240, "author_profile": "https://Stackoverflow.com/users/3809240", "pm_score": -1, "selected": false, "text": "<pre><code>select ltrim('000045', '0') from dual;\n\nLTRIM\n-----\n45\n</code></pre>\n\n<p>This should do.</p>\n" }, { "answer_id": 26909939, "author": "ekc", "author_id": 4248387, "author_profile": "https://Stackoverflow.com/users/4248387", "pm_score": 3, "selected": false, "text": "<p>I had the same need and used this: </p>\n\n<pre><code>select \n case \n when left(column,1) = '0' \n then right(column, (len(column)-1)) \n else column \n end\n</code></pre>\n" }, { "answer_id": 35373156, "author": "Brian Ellison", "author_id": 5920739, "author_profile": "https://Stackoverflow.com/users/5920739", "pm_score": -1, "selected": false, "text": "<p>I borrowed from ideas above. This is neither fast nor elegant. but it is accurate.</p>\n\n<p>CASE </p>\n\n<pre><code>WHEN left(column, 3) = '000' THEN right(column, (len(column)-3))\n\nWHEN left(column, 2) = '00' THEN right(a.column, (len(column)-2))\n\nWHEN left(column, 1) = '0' THEN right(a.column, (len(column)-1))\n\nELSE \n</code></pre>\n\n<p>END </p>\n" }, { "answer_id": 36689325, "author": "Stelian", "author_id": 6218798, "author_profile": "https://Stackoverflow.com/users/6218798", "pm_score": 3, "selected": false, "text": "<p>You can use this:</p>\n\n<pre><code>SELECT REPLACE(LTRIM(REPLACE('000010A', '0', ' ')),' ', '0')\n</code></pre>\n" }, { "answer_id": 40868049, "author": "Lynn Caveny", "author_id": 7225894, "author_profile": "https://Stackoverflow.com/users/7225894", "pm_score": -1, "selected": false, "text": "<pre><code>select CASE\n WHEN TRY_CONVERT(bigint,Mtrl_Nbr) = 0\n THEN ''\n ELSE substring(Mtrl_Nbr, patindex('%[^0]%',Mtrl_Nbr), 18)\n END\n</code></pre>\n" }, { "answer_id": 48179132, "author": "Madhurupa Moitra", "author_id": 9154612, "author_profile": "https://Stackoverflow.com/users/9154612", "pm_score": -1, "selected": false, "text": "<p>you can try this\n<code> SELECT REPLACE(columnname,'0','') FROM table\n</code></p>\n" }, { "answer_id": 48556389, "author": "Shailendra Mishra", "author_id": 2528335, "author_profile": "https://Stackoverflow.com/users/2528335", "pm_score": 0, "selected": false, "text": "<p>You can try this - it takes special care to <em>only</em> remove leading zeroes if needed:</p>\n\n<pre><code>DECLARE @LeadingZeros VARCHAR(10) ='-000987000'\n\nSET @LeadingZeros =\n CASE WHEN PATINDEX('%-0', @LeadingZeros) = 1 THEN \n @LeadingZeros\n ELSE \n CAST(CAST(@LeadingZeros AS INT) AS VARCHAR(10)) \n END \n\nSELECT @LeadingZeros\n</code></pre>\n\n<p>Or you can simply call</p>\n\n<pre><code>CAST(CAST(@LeadingZeros AS INT) AS VARCHAR(10)) \n</code></pre>\n" }, { "answer_id": 50394671, "author": "Krin", "author_id": 8189558, "author_profile": "https://Stackoverflow.com/users/8189558", "pm_score": -1, "selected": false, "text": "<p>To remove leading 0, You can multiply number column with 1\nEg: <strong>Select (ColumnName * 1)</strong></p>\n" }, { "answer_id": 54454715, "author": "Vikas", "author_id": 415865, "author_profile": "https://Stackoverflow.com/users/415865", "pm_score": 0, "selected": false, "text": "<p>Here is the SQL scalar value function that removes leading zeros from string:</p>\n\n<pre><code>SET ANSI_NULLS ON\nGO\nSET QUOTED_IDENTIFIER ON\nGO\n-- =============================================\n-- Author: Vikas Patel\n-- Create date: 01/31/2019\n-- Description: Remove leading zeros from string\n-- =============================================\nCREATE FUNCTION dbo.funRemoveLeadingZeros \n(\n -- Add the parameters for the function here\n @Input varchar(max)\n)\nRETURNS varchar(max)\nAS\nBEGIN\n -- Declare the return variable here\n DECLARE @Result varchar(max)\n\n -- Add the T-SQL statements to compute the return value here\n SET @Result = @Input\n\n WHILE LEFT(@Result, 1) = '0'\n BEGIN\n SET @Result = SUBSTRING(@Result, 2, LEN(@Result) - 1)\n END\n\n -- Return the result of the function\n RETURN @Result\n\nEND\nGO\n</code></pre>\n" }, { "answer_id": 60555560, "author": "e-Fungus", "author_id": 6110450, "author_profile": "https://Stackoverflow.com/users/6110450", "pm_score": 0, "selected": false, "text": "<p>In case you want to remove the leading zeros from a string with a unknown size.</p>\n\n<p>You may consider using the STUFF command. </p>\n\n<p>Here is an example of how it would work.</p>\n\n<pre><code>SELECT ISNULL(STUFF(ColumnName\n ,1\n ,patindex('%[^0]%',ColumnName)-1\n ,'')\n ,REPLACE(ColumnName,'0','')\n )\n</code></pre>\n\n<p>See in fiddler various scenarios it will cover</p>\n\n<p><a href=\"https://dbfiddle.uk/?rdbms=sqlserver_2012&amp;fiddle=14c2dca84aa28f2a7a1fac59c9412d48\" rel=\"nofollow noreferrer\">https://dbfiddle.uk/?rdbms=sqlserver_2012&amp;fiddle=14c2dca84aa28f2a7a1fac59c9412d48</a></p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/92093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7585/" ]
I am working on a SQL query that reads from a SQLServer database to produce an extract file. One of the requirements to remove the leading zeroes from a particular field, which is a simple `VARCHAR(10)` field. So, for example, if the field contains '00001A', the SELECT statement needs to return the data as '1A'. Is there a way in SQL to easily remove the leading zeroes in this way? I know there is an `RTRIM` function, but this seems only to remove spaces.
``` select substring(ColumnName, patindex('%[^0]%',ColumnName), 10) ```
92,100
<p>Is it possible to set code behind a resource dictionary in WPF. For example in a usercontrol for a button you declare it in XAML. The event handling code for the button click is done in the code file behind the control. If I was to create a data template with a button how can I write the event handler code for it's button click within the resource dictionary.</p>
[ { "answer_id": 92205, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": -1, "selected": false, "text": "<p>XAML is for constructing object graphs not containing code.<br>\nA Data template is used to indicate how a custom user-object is to be rendered on screen... (e.g. if it is a listbox item) behavior is not part of a data template's area of expertise. Redraw the solution...</p>\n" }, { "answer_id": 98422, "author": "ageektrapped", "author_id": 631, "author_profile": "https://Stackoverflow.com/users/631", "pm_score": 9, "selected": true, "text": "<p>I think what you're asking is you want a code-behind file for a ResourceDictionary. You can totally do this! In fact, you do it the same way as for a Window:</p>\n\n<p>Say you have a ResourceDictionary called MyResourceDictionary. In your MyResourceDictionary.xaml file, put the x:Class attribute in the root element, like so:</p>\n\n<pre><code>&lt;ResourceDictionary xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n x:Class=\"MyCompany.MyProject.MyResourceDictionary\"\n x:ClassModifier=\"public\"&gt;\n</code></pre>\n\n<p>Then, create a code behind file called MyResourceDictionary.xaml.cs with the following declaration:</p>\n\n<pre><code>namespace MyCompany.MyProject\n{\n partial class MyResourceDictionary : ResourceDictionary\n { \n public MyResourceDictionary()\n {\n InitializeComponent();\n } \n ... // event handlers ahead..\n }\n}\n</code></pre>\n\n<p>And you're done. You can put whatever you wish in the code behind: methods, properties and event handlers.</p>\n\n<p><strong>== Update for Windows 10 apps ==</strong></p>\n\n<p>And just in case you are playing with <strong>UWP</strong> there is one more thing to be aware of:</p>\n\n<pre><code>&lt;Application x:Class=\"SampleProject.App\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:rd=\"using:MyCompany.MyProject\"&gt;\n&lt;!-- no need in x:ClassModifier=\"public\" in the header above --&gt;\n\n &lt;Application.Resources&gt;\n &lt;ResourceDictionary&gt;\n &lt;ResourceDictionary.MergedDictionaries&gt;\n\n &lt;!-- This will NOT work --&gt;\n &lt;!-- &lt;ResourceDictionary Source=\"/MyResourceDictionary.xaml\" /&gt;--&gt;\n\n &lt;!-- Create instance of your custom dictionary instead of the above source reference --&gt;\n &lt;rd:MyResourceDictionary /&gt;\n\n &lt;/ResourceDictionary.MergedDictionaries&gt;\n &lt;/ResourceDictionary&gt;\n &lt;/Application.Resources&gt;\n\n&lt;/Application&gt;\n</code></pre>\n" }, { "answer_id": 136805, "author": "Phobis", "author_id": 19854, "author_profile": "https://Stackoverflow.com/users/19854", "pm_score": 3, "selected": false, "text": "<p>I disagree with \"ageektrapped\"... using the method of a partial class is not a good practice. What would be the purpose of separating the Dictionary from the page then?</p>\n\n<p>From a code-behind, you can access a x:Name element by using:</p>\n\n<pre><code>Button myButton = this.GetTemplateChild(\"ButtonName\") as Button;\nif(myButton != null){\n ...\n}\n</code></pre>\n\n<p>You can do <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.controls.control.gettemplatechild(VS.95).aspx\" rel=\"noreferrer\">this</a> in the OnApplyTemplate method if you want to hookup to controls when your custom control loads. OnApplyTemplate needs to be overridden to do this. This is a common practice and allows your style to stay disconnected from the control. (The style should not depend on the control, but the control should depend on having a style).</p>\n" }, { "answer_id": 1808512, "author": "Pete Maher", "author_id": 107702, "author_profile": "https://Stackoverflow.com/users/107702", "pm_score": 3, "selected": false, "text": "<p>Gishu - whilst this might seem to be a \"generally not to be encouraged practice\" Here is one reason you might want to do it:</p>\n\n<p>The standard behaviour for text boxes when they get focus is for the caret to be placed at the same position that it was when the control lost focus. If you would prefer throughout your application that when the user tabs to any textbox that the whole content of the textbox was highlighted then adding a simple handler in the resource dictionary would do the trick.</p>\n\n<p>Any other reason where you want the default user interaction behaviour to be different from the out of the box behaviour seems like good candidates for a code behind in a resource dictionary. </p>\n\n<p>Totally agree that anything which is application functionality specific ought not be in a code behind of a resource dictionary.</p>\n" }, { "answer_id": 66377405, "author": "Jason Barkley", "author_id": 2205253, "author_profile": "https://Stackoverflow.com/users/2205253", "pm_score": 0, "selected": false, "text": "<p>Adding on....these days, with the advent of {x:Bind ...}, if you want to put your DataTemplate into a shared ResourceDictionary file, you are required to give that file a code behind.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/92100", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6204/" ]
Is it possible to set code behind a resource dictionary in WPF. For example in a usercontrol for a button you declare it in XAML. The event handling code for the button click is done in the code file behind the control. If I was to create a data template with a button how can I write the event handler code for it's button click within the resource dictionary.
I think what you're asking is you want a code-behind file for a ResourceDictionary. You can totally do this! In fact, you do it the same way as for a Window: Say you have a ResourceDictionary called MyResourceDictionary. In your MyResourceDictionary.xaml file, put the x:Class attribute in the root element, like so: ``` <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Class="MyCompany.MyProject.MyResourceDictionary" x:ClassModifier="public"> ``` Then, create a code behind file called MyResourceDictionary.xaml.cs with the following declaration: ``` namespace MyCompany.MyProject { partial class MyResourceDictionary : ResourceDictionary { public MyResourceDictionary() { InitializeComponent(); } ... // event handlers ahead.. } } ``` And you're done. You can put whatever you wish in the code behind: methods, properties and event handlers. **== Update for Windows 10 apps ==** And just in case you are playing with **UWP** there is one more thing to be aware of: ``` <Application x:Class="SampleProject.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:rd="using:MyCompany.MyProject"> <!-- no need in x:ClassModifier="public" in the header above --> <Application.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <!-- This will NOT work --> <!-- <ResourceDictionary Source="/MyResourceDictionary.xaml" />--> <!-- Create instance of your custom dictionary instead of the above source reference --> <rd:MyResourceDictionary /> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Application.Resources> </Application> ```
92,103
<p>What do you find is the optimal setting for mysql slow query log parameter, and why?</p>
[ { "answer_id": 92140, "author": "David Precious", "author_id": 4040, "author_profile": "https://Stackoverflow.com/users/4040", "pm_score": 2, "selected": false, "text": "<p>Whatever time /you/ feel is unacceptably slow for a query on your systems.</p>\n\n<p>It depends on the kind of queries you run and the kind of system; a query taking several seconds might not matter if it's some back-end reporting system doing complex data-mining etc where a delay doesn't matter, but might be completely unacceptable on a user-facing system which is expected to return results promptly.</p>\n" }, { "answer_id": 92143, "author": "MarkR", "author_id": 13724, "author_profile": "https://Stackoverflow.com/users/13724", "pm_score": 2, "selected": false, "text": "<p>Set it to whatever you like. The only problem is that in a stock MySQL, it can only be set in increments of 1 second, which is too slow for some people.</p>\n\n<p>Most heavily used production servers execute far too many queries to log them all. The slow log is a way of filtering the log so that we can see the ones which take a long time (most queries are likely to be executed almost instantly). It's a bit of a blunt instrument.</p>\n\n<p>Set it to 1 sec if you like, you're probably not going to run out of disc space or create a performance problem by doing that.</p>\n\n<p>It's really about the risk of enabling the slow log- don't do it if you feel it's likely to cause further disc or performance problems.</p>\n\n<p>Of course you could enable the slow log on a non-production server and put simulated load through, but that is never quite the same.</p>\n" }, { "answer_id": 92392, "author": "cori", "author_id": 8151, "author_profile": "https://Stackoverflow.com/users/8151", "pm_score": 1, "selected": false, "text": "<p>Not only is it a blunt instrument as far as resolution is concerned, but also it is MySQL-instance wide, so that if you have different databases with differing performancy requirements you're kind of out of luck. Obviously there are ways around that, but it's important to keep that in mind when setting your slow log setting.</p>\n\n<p>Aside from performance requirements of your application, another factor to consider is what you're trying to log. Are you using the log to catch queries that would threaten the stability of your db instance (ones that cause deadlocks or Cartesian joins, for instance) or queries that affect the performance for specific users and that might require a little tuning? That will influence where you set your threshold.</p>\n" }, { "answer_id": 92643, "author": "Dave Cheney", "author_id": 6449, "author_profile": "https://Stackoverflow.com/users/6449", "pm_score": 5, "selected": true, "text": "<p>I recommend these three lines</p>\n\n<pre>\nlog_slow_queries\nset-variable = long_query_time=1\nlog-queries-not-using-indexes\n</pre>\n\n<p>The first and second will log any query over a second. As others have pointed out a one second query is pretty far gone if you are a shooting for a high transaction rate on your website, but I find that it turns up some real WTFs; queries that <em>should</em> be fast, but for whatever combination of data it was run against was not. </p>\n\n<p>The last will log any query that does not use an index. Unless your doing data warehousing any common query should have the best index you can find so pay attention to its output.</p>\n\n<p>Although its certainly not for production, this last option</p>\n\n<pre>\nlog = /var/log/mysql/mysql.log\n</pre>\n\n<p>will log all queries, which can be useful if you are trying to tune a specific page or action.</p>\n" }, { "answer_id": 97167, "author": "Shinhan", "author_id": 18219, "author_profile": "https://Stackoverflow.com/users/18219", "pm_score": 2, "selected": false, "text": "<p>Peter Zaitsev posted a <a href=\"http://www.mysqlperformanceblog.com/2006/09/06/slow-query-log-analyzes-tools/\" rel=\"nofollow noreferrer\" title=\"Slow Query Log analyzes tools\">nice article</a> about using the slow query log. One thing he notes is important is to also consider how often a certain query is used. Reports run once a day are not important to be fast. But something that is run very often might be a problem even if it takes half a second. And you cant detect that without the microslow patch.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/92103", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10596/" ]
What do you find is the optimal setting for mysql slow query log parameter, and why?
I recommend these three lines ``` log_slow_queries set-variable = long_query_time=1 log-queries-not-using-indexes ``` The first and second will log any query over a second. As others have pointed out a one second query is pretty far gone if you are a shooting for a high transaction rate on your website, but I find that it turns up some real WTFs; queries that *should* be fast, but for whatever combination of data it was run against was not. The last will log any query that does not use an index. Unless your doing data warehousing any common query should have the best index you can find so pay attention to its output. Although its certainly not for production, this last option ``` log = /var/log/mysql/mysql.log ``` will log all queries, which can be useful if you are trying to tune a specific page or action.
92,114
<p>There is a limitation on Windows Server 2003 that prevents you from copying extremely large files, in proportion to the amount of RAM you have. The limitation is in the CopyFile and CopyFileEx functions, which are used by xcopy, Explorer, Robocopy, and the .NET FileInfo class.</p> <p>Here is the error that you get:</p> <blockquote> <p>Cannot copy [filename]: Insufficient system resources exist to complete the requested service.</p> </blockquote> <p>The is a <a href="http://support.microsoft.com/default.aspx/kb/259837" rel="noreferrer">knowledge base article</a> on the subject, but it pertains to NT4 and 2000.</p> <p>There is also a suggestion to <a href="http://blogs.technet.com/askperf/archive/2007/05/08/slow-large-file-copy-issues.aspx" rel="noreferrer">use ESEUTIL</a> from an Exchange installation, but I haven't had any luck getting that to work.</p> <p>Does anybody know of a quick, easy way to handle this? I'm talking about >50Gb on a machine with 2Gb of RAM. I plan to fire up Visual Studio and just write something to do it for me, but it would be nice to have something that was already out there, stable and well-tested.</p> <p><strong>[Edit]</strong> I provided working C# code to accompany the accepted answer.</p>
[ { "answer_id": 92165, "author": "jabial", "author_id": 16995, "author_profile": "https://Stackoverflow.com/users/16995", "pm_score": 5, "selected": true, "text": "<p>The best option is to just open the original file for reading, the destination file for writing and then loop copying it block by block. In pseudocode :</p>\n\n<pre><code>f1 = open(filename1);\nf2 = open(filename2, \"w\");\nwhile( !f1.eof() ) {\n buffer = f1.read(buffersize);\n err = f2.write(buffer, buffersize);\n if err != NO_ERROR_CODE\n break;\n}\nf1.close(); f2.close();\n</code></pre>\n\n<p><strong>[Edit by Asker]</strong> Ok, this is how it looks in C# (it's slow but it seems to work Ok, and it gives progress):</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Text;\n\nnamespace LoopCopy\n{\n class Program\n {\n static void Main(string[] args)\n {\n if (args.Length != 2)\n {\n Console.WriteLine(\n \"Usage: LoopCopy.exe SourceFile DestFile\");\n return;\n }\n\n string srcName = args[0];\n string destName = args[1];\n\n FileInfo sourceFile = new FileInfo(srcName);\n if (!sourceFile.Exists)\n {\n Console.WriteLine(\"Source file {0} does not exist\", \n srcName);\n return;\n }\n long fileLen = sourceFile.Length;\n\n FileInfo destFile = new FileInfo(destName);\n if (destFile.Exists)\n {\n Console.WriteLine(\"Destination file {0} already exists\", \n destName);\n return;\n }\n\n int buflen = 1024;\n byte[] buf = new byte[buflen];\n long totalBytesRead = 0;\n double pctDone = 0;\n string msg = \"\";\n int numReads = 0;\n Console.Write(\"Progress: \");\n using (FileStream sourceStream = \n new FileStream(srcName, FileMode.Open))\n {\n using (FileStream destStream = \n new FileStream(destName, FileMode.CreateNew))\n {\n while (true)\n {\n numReads++;\n int bytesRead = sourceStream.Read(buf, 0, buflen);\n if (bytesRead == 0) break; \n destStream.Write(buf, 0, bytesRead);\n\n totalBytesRead += bytesRead;\n if (numReads % 10 == 0)\n {\n for (int i = 0; i &lt; msg.Length; i++)\n {\n Console.Write(\"\\b \\b\");\n }\n pctDone = (double)\n ((double)totalBytesRead / (double)fileLen);\n msg = string.Format(\"{0}%\", \n (int)(pctDone * 100));\n Console.Write(msg);\n }\n\n if (bytesRead &lt; buflen) break;\n\n }\n }\n }\n\n for (int i = 0; i &lt; msg.Length; i++)\n {\n Console.Write(\"\\b \\b\");\n }\n Console.WriteLine(\"100%\");\n Console.WriteLine(\"Done\");\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 92181, "author": "Gulzar Nazim", "author_id": 4337, "author_profile": "https://Stackoverflow.com/users/4337", "pm_score": 3, "selected": false, "text": "<p>If you want to write code, one way you can optimize is sending the file in chunks (like using <a href=\"http://www.codeproject.com/KB/XML/MTOMWebServices.aspx\" rel=\"nofollow noreferrer\">MTOM</a>). I used this approach for sending down huge files from a DataCenter down to our office for printing..</p>\n\n<p>Also, check the TeraCopy utility mentioned <a href=\"http://lifehacker.com/software/lifehacker-top-10/top-10-free-windows-file-wranglers-330037.php\" rel=\"nofollow noreferrer\">here</a>..</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/92114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1219/" ]
There is a limitation on Windows Server 2003 that prevents you from copying extremely large files, in proportion to the amount of RAM you have. The limitation is in the CopyFile and CopyFileEx functions, which are used by xcopy, Explorer, Robocopy, and the .NET FileInfo class. Here is the error that you get: > > Cannot copy [filename]: Insufficient system resources exist to complete the requested service. > > > The is a [knowledge base article](http://support.microsoft.com/default.aspx/kb/259837) on the subject, but it pertains to NT4 and 2000. There is also a suggestion to [use ESEUTIL](http://blogs.technet.com/askperf/archive/2007/05/08/slow-large-file-copy-issues.aspx) from an Exchange installation, but I haven't had any luck getting that to work. Does anybody know of a quick, easy way to handle this? I'm talking about >50Gb on a machine with 2Gb of RAM. I plan to fire up Visual Studio and just write something to do it for me, but it would be nice to have something that was already out there, stable and well-tested. **[Edit]** I provided working C# code to accompany the accepted answer.
The best option is to just open the original file for reading, the destination file for writing and then loop copying it block by block. In pseudocode : ``` f1 = open(filename1); f2 = open(filename2, "w"); while( !f1.eof() ) { buffer = f1.read(buffersize); err = f2.write(buffer, buffersize); if err != NO_ERROR_CODE break; } f1.close(); f2.close(); ``` **[Edit by Asker]** Ok, this is how it looks in C# (it's slow but it seems to work Ok, and it gives progress): ``` using System; using System.Collections.Generic; using System.IO; using System.Text; namespace LoopCopy { class Program { static void Main(string[] args) { if (args.Length != 2) { Console.WriteLine( "Usage: LoopCopy.exe SourceFile DestFile"); return; } string srcName = args[0]; string destName = args[1]; FileInfo sourceFile = new FileInfo(srcName); if (!sourceFile.Exists) { Console.WriteLine("Source file {0} does not exist", srcName); return; } long fileLen = sourceFile.Length; FileInfo destFile = new FileInfo(destName); if (destFile.Exists) { Console.WriteLine("Destination file {0} already exists", destName); return; } int buflen = 1024; byte[] buf = new byte[buflen]; long totalBytesRead = 0; double pctDone = 0; string msg = ""; int numReads = 0; Console.Write("Progress: "); using (FileStream sourceStream = new FileStream(srcName, FileMode.Open)) { using (FileStream destStream = new FileStream(destName, FileMode.CreateNew)) { while (true) { numReads++; int bytesRead = sourceStream.Read(buf, 0, buflen); if (bytesRead == 0) break; destStream.Write(buf, 0, bytesRead); totalBytesRead += bytesRead; if (numReads % 10 == 0) { for (int i = 0; i < msg.Length; i++) { Console.Write("\b \b"); } pctDone = (double) ((double)totalBytesRead / (double)fileLen); msg = string.Format("{0}%", (int)(pctDone * 100)); Console.Write(msg); } if (bytesRead < buflen) break; } } } for (int i = 0; i < msg.Length; i++) { Console.Write("\b \b"); } Console.WriteLine("100%"); Console.WriteLine("Done"); } } } ```
92,239
<p>If you have several <code>div</code>s on a page, you can use CSS to size, float them and move them round a little... but I can't see a way to get past the fact that the first <code>div</code> will show near the top of the page and the last <code>div</code> will be near the bottom! I cannot completely override the order of the elements as they come from the source HTML, can you?</p> <p>I must be missing something because people say "we can change the look of the whole website by just editing one CSS file.", but that would depend on you still wanting the <code>div</code>s in the same order!</p> <p>(P.S. I am sure no one uses <code>position:absolute</code> on every element on a page.)</p>
[ { "answer_id": 92264, "author": "workmad3", "author_id": 16035, "author_profile": "https://Stackoverflow.com/users/16035", "pm_score": 2, "selected": false, "text": "<p>You don't need position:absolute on every element to do what you want.</p>\n\n<p>You just use it on a few key items and then you can position them where-ever you want, moving all the items contained within them along with the root element of the section.</p>\n" }, { "answer_id": 92278, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 5, "selected": false, "text": "<p>CSS can take elements <em>out of the normal flow</em> and position them anywhere, in any manner you want. But it cannot <em>create a new flow</em>. </p>\n\n<p>By this I mean that you can position the last item from the html document at the beginning/top of the page/window, and you can position the first item from the html document at the end/bottom of the page/window. But when you do this you can't position these items relative to each other; you have to know for yourself how far down the end of the page will be for the first item from the html document to be positioned correctly. If that content is dynamic (ie: from a database or CMS), this can be far from trivial.</p>\n" }, { "answer_id": 92291, "author": "Nick Craver", "author_id": 13249, "author_profile": "https://Stackoverflow.com/users/13249", "pm_score": 2, "selected": false, "text": "<p>You may want to look at <a href=\"http://www.csszengarden.com/\" rel=\"nofollow noreferrer\">CSS Zen Garden</a> for excellent examples of how to do what you want. Plenty of sample layouts via the links on the right to see the various way to move everything using strictly CSS.</p>\n" }, { "answer_id": 92315, "author": "ZombieSheep", "author_id": 377, "author_profile": "https://Stackoverflow.com/users/377", "pm_score": 1, "selected": false, "text": "<p>I think that the most important factor is to place your html elements in a way that makes sense semantically, and with luck your layout in CSS will not have to do too much work. For example, your site's header will probably be the first element on the page, followed by common navigation, then sub-navigation, content and the footer (incomplete list).</p>\n\n<p>Probably around 90-95% of the layouts you'll want to work with should be relatively trivial to manipulate that markup into something like what you're after. the other 5-10% will still be possible, with a little more effort, but the question you need to ask yourself is \"How often am I likely to want my site header positioned in the bottom-right corner of the page?\"</p>\n\n<p>I've always found that the layout of a site is not too tough to manipulate after the fact if you do want to dramatically change the look and feel, at least in comparison with a ground-up recode.</p>\n\n<p>&lt;/2c&gt;</p>\n" }, { "answer_id": 92343, "author": "Magnus Smith", "author_id": 11461, "author_profile": "https://Stackoverflow.com/users/11461", "pm_score": 0, "selected": false, "text": "<p>Good point about the header always being first and the footer last! But I might want to move my advertising DIV from along the top, to down the right.</p>\n\n<p>The other thing I've heard about is putting the content DIV first, so Google pays you more attention (relevant keywords near the top of the page score higher)...or is that a myth? Doing that would require the sort of CSS trick I'm enquiring about too.</p>\n" }, { "answer_id": 92357, "author": "Jonathan Arkell", "author_id": 11052, "author_profile": "https://Stackoverflow.com/users/11052", "pm_score": 4, "selected": true, "text": "<p>With Floating, and with position absolute, you can pull some pretty good positioning magic to change some of the order of the page.</p>\n\n<p>For instance, with StackOverflow, if the markup was setup right, the title, and main body content could be the first 2 things in the markup, and then the navigation/search, and finally the right hand sidebar. This would be done by having a content container with a top margin big enough to hold the navigation and a right margin big enough to hold the sidebars. Then both could be absolutely positioned in place. The markup might look like:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>h1 {\r\n position: absolute;\r\n top: 0;\r\n left: 0;\r\n}\r\n\r\n#content {\r\n margin-top: 100px;\r\n margin-right: 250px;\r\n}\r\n\r\n#nav {\r\n position: absolute;\r\n top: 0;\r\n left: 300px;\r\n}\r\n\r\n#side {\r\n position: absolute;\r\n right: 0;\r\n top: 100px;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;h1&gt; Stack Overflow &lt;/h1&gt;\r\n&lt;div id=\"content\"&gt;\r\n &lt;h2&gt; Can Css truly blah blah? &lt;/h2&gt;\r\n ...\r\n&lt;/div&gt;\r\n&lt;div id=\"nav\"&gt;\r\n &lt;ul class=\"main\"&gt;\r\n &lt;li&gt;quiestions&lt;/li&gt; ... &lt;/ul&gt;\r\n ....\r\n&lt;/div&gt;\r\n&lt;div id=\"side\"&gt;\r\n &lt;div class=\"box\"&gt;\r\n &lt;h3&gt; Sponsored By &lt;/h3&gt;\r\n &lt;h4&gt; New Zelands fish market &lt;/h4&gt;\r\n ....\r\n &lt;/div&gt;\r\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>The important thing here is that the markup has to be done with this kind of positioning magic in mind. </p>\n\n<p>Changing things so that the navbar is on the left and the sidebar below the nav be too hard.</p>\n" }, { "answer_id": 92391, "author": "JacquesB", "author_id": 7488, "author_profile": "https://Stackoverflow.com/users/7488", "pm_score": 1, "selected": false, "text": "<p>You can position individual boxes completely independent from the source order using position:absolute. So you can move the header to the bottom of the page, and the footer to the top using CSS.</p>\n\n<p>Note however that this is genereally bad for accessibility: You should have the order of the content in the source more or less in the same order that you would present it for the reader. The reason is that a screen reader or similar device will present the content in the order it is defined in the source rather than the visual order defined by your CSS.</p>\n" }, { "answer_id": 13326589, "author": "pieroxy", "author_id": 1480910, "author_profile": "https://Stackoverflow.com/users/1480910", "pm_score": 2, "selected": false, "text": "<p>There are a couple of ways of doing it today. The first one works on more browsers but is more limited:</p>\n\n<ol>\n<li><p>Using the CSS display values of <code>table-caption</code>, <code>table-row</code> and <code>table-cell</code> allow vertical ordering of at most three elements controlled exclusively with CSS.</p></li>\n<li><p>This is much more recent and will only work in all latest browsers (yes, it will fail in IE9): Use of the flexbox CSS properties.</p></li>\n</ol>\n\n<p>You can view live examples and read more about these techniques at the \"<a href=\"http://bradfrost.github.com/this-is-responsive/patterns.html\" rel=\"nofollow\">this is responsive</a>\" patterns page. The two I'm talking about are in the section titled \"Source-Order Shift\"</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/92239", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11461/" ]
If you have several `div`s on a page, you can use CSS to size, float them and move them round a little... but I can't see a way to get past the fact that the first `div` will show near the top of the page and the last `div` will be near the bottom! I cannot completely override the order of the elements as they come from the source HTML, can you? I must be missing something because people say "we can change the look of the whole website by just editing one CSS file.", but that would depend on you still wanting the `div`s in the same order! (P.S. I am sure no one uses `position:absolute` on every element on a page.)
With Floating, and with position absolute, you can pull some pretty good positioning magic to change some of the order of the page. For instance, with StackOverflow, if the markup was setup right, the title, and main body content could be the first 2 things in the markup, and then the navigation/search, and finally the right hand sidebar. This would be done by having a content container with a top margin big enough to hold the navigation and a right margin big enough to hold the sidebars. Then both could be absolutely positioned in place. The markup might look like: ```css h1 { position: absolute; top: 0; left: 0; } #content { margin-top: 100px; margin-right: 250px; } #nav { position: absolute; top: 0; left: 300px; } #side { position: absolute; right: 0; top: 100px; } ``` ```html <h1> Stack Overflow </h1> <div id="content"> <h2> Can Css truly blah blah? </h2> ... </div> <div id="nav"> <ul class="main"> <li>quiestions</li> ... </ul> .... </div> <div id="side"> <div class="box"> <h3> Sponsored By </h3> <h4> New Zelands fish market </h4> .... </div> </div> ``` The important thing here is that the markup has to be done with this kind of positioning magic in mind. Changing things so that the navbar is on the left and the sidebar below the nav be too hard.