qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
252,156
<p>In Sql Server 2005 what data type should be used to store passwords <a href="http://msdn.microsoft.com/en-us/library/system.security.cryptography.sha256managed(VS.71).aspx" rel="noreferrer">hashed by SHA-256 algorithm</a>? </p> <p>The data is <a href="http://msdn.microsoft.com/en-us/library/system.security.cryptography.sha256managed(VS.71).aspx" rel="noreferrer">hashed by the application</a> and passed to the database</p>
[ { "answer_id": 252175, "author": "Peter Parker", "author_id": 23264, "author_profile": "https://Stackoverflow.com/users/23264", "pm_score": 4, "selected": false, "text": "0x" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/252156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3241/" ]
252,179
<p>What is the best way to check if a given url points to a valid file (i.e. not return a 404/301/etc.)? I've got a script that will load certain .js files on a page, but I need a way to verify each URL it receives points to a valid file.</p> <p>I'm still poking around the PHP manual to see which file functions (if any) will actually work with remote URLs. I'll edit my post as I find more details, but if anyone has already been down this path feel free to chime in.</p>
[ { "answer_id": 252418, "author": "Czimi", "author_id": 3906, "author_profile": "https://Stackoverflow.com/users/3906", "pm_score": 4, "selected": true, "text": "<?php\n// create a new cURL resource\n$ch = curl_init();\n\n// set URL and other appropriate options\ncurl_setopt($ch, CURLOPT_URL, \"http://www.example.com/\");\ncurl_setopt($ch, CURLOPT_HEADER, 1);\ncurl_setopt($ch, CURLOPT_NOBODY, 1);\n\n// grab URL and pass it to the browser\ncurl_exec($ch);\n\n// close cURL resource, and free up system resources\ncurl_close($ch);\n?>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/252179", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5291/" ]
252,202
<p>In my database I have tables that define types for example</p> <p>Table: Publication Types</p> <pre> ID | Type ---------- 1 | Article 2 | Abstract 3 | Book .... </pre> <p>Which is related through the ID key to a publication tables which has the field <em>TypeID</em>.</p> <p>I then create a PublicationTable data table my .NET application which I want to filter based on the publication type. For example the following function gives me the number of publications for a specific author and publication type.</p> <pre> Public Function countPublications(ByVal authorID As Integer, _ ByVal publicationType As Integer) As Integer Dim authPubs As New PublicationsDataSet.tblPublicationsDataTable authPubs = Me.getAuthorsPublications(authorID) Dim dv As New DataView(authPubs) dv.RowFilter = "status='published' AND type='" + _ publicationType.ToString + "'" Return dv.Count End Function </pre> <p>To call this function to get a count of articles by an author of a specific type, I could</p> <ol> <li><p>call the function with two integers</p> <p>countPublications(authorID, 1)</p></li> <li><p>setup an enum so that I can write</p> <p>countPublications(authorID, pubType.Article)</p> <p>or </p></li> <li><p>somehow use the publication type table to filter the publication data set but I haven't got my head around how to do this.</p></li> </ol> <p>What other approaches should I consider.</p> <p>Thanks</p>
[ { "answer_id": 252212, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 4, "selected": true, "text": "inner join lookuptable lt on lt.id = (int)myenum.sometype \n inner join lookuptable lt on lt.name = \"somehardcodeddescription\"\n inner join lookuptable lt on lt.name = myenum.sometype.ToString\n" }, { "answer_id": 252278, "author": "Adam Liss", "author_id": 29157, "author_profile": "https://Stackoverflow.com/users/29157", "pm_score": 3, "selected": false, "text": "enum enum enum Publication Types" }, { "answer_id": 254091, "author": "Azim J", "author_id": 4612, "author_profile": "https://Stackoverflow.com/users/4612", "pm_score": 0, "selected": false, "text": "countPublications(authorID, publicationType.JournalArticle)\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252202", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4612/" ]
252,203
<p>I am using the following code to check if a variable is not nil and not zero</p> <pre><code>if(discount != nil &amp;&amp; discount != 0) ... end </code></pre> <p>Is there a better way to do this?</p>
[ { "answer_id": 252220, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 5, "selected": false, "text": "if (!discount.nil? && !discount.zero?)\n discount nil zero? discount.zero? discount nil" }, { "answer_id": 252330, "author": "madlep", "author_id": 14160, "author_profile": "https://Stackoverflow.com/users/14160", "pm_score": 5, "selected": false, "text": "class Object\n def nil_zero?\n self.nil? || self == 0\n end\nend\n\n# which lets you do\nnil.nil_zero? # returns true\n0.nil_zero? # returns true\n1.nil_zero? # returns false\n\"a\".nil_zero? # returns false\n\nunless discount.nil_zero?\n # do stuff...\nend\n" }, { "answer_id": 253366, "author": "Raimonds Simanovskis", "author_id": 16829, "author_profile": "https://Stackoverflow.com/users/16829", "pm_score": 4, "selected": false, "text": "if (discount||0) != 0\n #...\nend\n" }, { "answer_id": 255215, "author": "Jeff Waltzer", "author_id": 23513, "author_profile": "https://Stackoverflow.com/users/23513", "pm_score": -1, "selected": false, "text": "if discount != 0\nend\n" }, { "answer_id": 5321351, "author": "rubyprince", "author_id": 584440, "author_profile": "https://Stackoverflow.com/users/584440", "pm_score": 2, "selected": false, "text": "if discount and discount != 0\n ..\nend\n false discount = false" }, { "answer_id": 12599075, "author": "oivoodoo", "author_id": 171350, "author_profile": "https://Stackoverflow.com/users/171350", "pm_score": 4, "selected": false, "text": "\"\".to_i.zero? => true\nnil.to_i.zero? => true\n" }, { "answer_id": 20012233, "author": "rewritten", "author_id": 384417, "author_profile": "https://Stackoverflow.com/users/384417", "pm_score": 5, "selected": false, "text": "if discount.try :nonzero?\n ...\nend\n try" }, { "answer_id": 30522783, "author": "Dave G-W", "author_id": 3614669, "author_profile": "https://Stackoverflow.com/users/3614669", "pm_score": 2, "selected": false, "text": "NilClass #to_i nil unless discount.to_i.zero?\n # Code here\nend\n discount #to_f" }, { "answer_id": 32566847, "author": "pastullo", "author_id": 1490947, "author_profile": "https://Stackoverflow.com/users/1490947", "pm_score": 1, "selected": false, "text": "add_column :products, :price, :integer, default: 0\n" }, { "answer_id": 34819818, "author": "ndnenkov", "author_id": 2423164, "author_profile": "https://Stackoverflow.com/users/2423164", "pm_score": 5, "selected": false, "text": "&. Numeric#nonzero? &. nil nil nonzero? 0 if discount&.nonzero?\n # ...\nend\n do_something if discount&.nonzero?\n" }, { "answer_id": 36447296, "author": "Saroj", "author_id": 5293076, "author_profile": "https://Stackoverflow.com/users/5293076", "pm_score": 2, "selected": false, "text": "def is_nil_and_zero(data)\n data.blank? || data == 0 \nend \n" }, { "answer_id": 38489061, "author": "Abhinay Reddy Keesara", "author_id": 6495570, "author_profile": "https://Stackoverflow.com/users/6495570", "pm_score": 1, "selected": false, "text": "if discount.nil? || discount == 0\n [do something]\nend\n" }, { "answer_id": 52403584, "author": "RichOrElse", "author_id": 6913691, "author_profile": "https://Stackoverflow.com/users/6913691", "pm_score": -1, "selected": false, "text": "module Nothingness\n refine Numeric do\n alias_method :nothing?, :zero?\n end\n\n refine NilClass do\n alias_method :nothing?, :nil?\n end\nend\n\nusing Nothingness\n\nif discount.nothing?\n # do something\nend\n" }, { "answer_id": 62130247, "author": "Ozesh", "author_id": 3436775, "author_profile": "https://Stackoverflow.com/users/3436775", "pm_score": 2, "selected": false, "text": "val.to_i.zero?\n val.to_i 0 nil" }, { "answer_id": 64062974, "author": "NIshank", "author_id": 6014558, "author_profile": "https://Stackoverflow.com/users/6014558", "pm_score": 2, "selected": false, "text": "discount.to_f.zero?\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252203", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14755/" ]
252,222
<p>What is the best way to access an ASP.NET HiddenField control that is embedded in an ASP.NET PlaceHolder control through JavaScript? The Visible attribute is set to false in the initial page load and can changed via an AJAX callback.</p> <p>Here is my current source code:</p> <pre><code>&lt;script language="javascript" type="text/javascript"&gt; function AccessMyHiddenField() { var HiddenValue = document.getElementById("&lt;%= MyHiddenField.ClientID %&gt;").value; //do my thing thing..... } &lt;/script&gt; &lt;asp:PlaceHolder ID="MyPlaceHolder" runat="server" Visible="false"&gt; &lt;asp:HiddenField ID="MyHiddenField" runat="server" /&gt; &lt;/asp:PlaceHolder&gt; </code></pre> <p><b>EDIT:</b> How do I set the style for a div tag in the ascx code behind in C#? This is the description from the code behind: CssStyleCollection HtmlControl.Style</p> <p><b>UPDATE:</b> I replaced the asp:hiddenfield with an asp:label and I am getting an "undefined" when I display the HiddenValue variable in a alert box. How would I resolve this.</p> <p><b>UPDATE 2:</b> I went ahead and refactored the code, I replaced the hidden field control with a text box control and set the style to "display: none;". I also removed the JavaScript function (it was used by a CustomValidator control) and replaced it with a RequiredFieldValidator control. </p>
[ { "answer_id": 11045023, "author": "BinuAmitSanish", "author_id": 1457853, "author_profile": "https://Stackoverflow.com/users/1457853", "pm_score": 2, "selected": false, "text": "function popup(lid)\n{\n var linkid=lid.id.toString(); \n var lengthid=linkid.length-25; \n var idh=linkid.substring(0,parseInt(lengthid)); \n var hid=idh+\"hiddenfield1\";\n\n var gv = document.getElementById(\"<%=GridViewComplaints.ClientID %>\");\n var gvRowCount = gv.rows.length;\n var rwIndex = 1;\n var username=gv.rows[rwIndex].cells[1].childNodes[1].innerHTML;\n var prdid=gv.rows[rwIndex].cells[3].childNodes[1].innerHTML;\n var msg=document.getElementById(hid.toString()).value;\n alert(msg);\n\n\n document.getElementById('<%= Labelcmpnme.ClientID %>').innerHTML=username;\n document.getElementById('<%= Labelprdid.ClientID %>').innerHTML=prdid;\n document.getElementById('<%= TextBoxviewmessage.ClientID %>').value=msg;\n return false;\n}\n <ItemTemplate>\n <asp:LinkButton ID=\"LabelComplaintdisplayitem\" runat =\"server\" Text='<%#Eval(\"ComplaintDisp\").ToString().Length>5?Eval(\"ComplaintDisp\").ToString().Substring(0,5)+\"....\":Eval(\"ComplaintDisp\") %>' CommandName =\"viewmessage\" CommandArgument ='<%#Eval(\"username\")+\";\"+Eval(\"productId\")+\";\"+Eval(\"ComplaintDisp\") %>' class='basic' OnClientClick =\" return popup(this)\"></asp:LinkButton>\n <asp:HiddenField ID=\"hiddenfield1\" runat =\"server\" Value='<%#Eval(\"ComplaintDisp\")%>'/>\n</ItemTemplate>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252222", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26327/" ]
252,226
<p>I have an <a href="http://en.wikipedia.org/wiki/EXE" rel="noreferrer">EXE</a> file that I should like to sign so that Windows will not warn the end user about an application from an "unknown publisher". I am not a Windows developer. The application in question is a screensaver generated from an application that generates screensaver applications. As such I have no influence on how the file is generated.</p> <p>I've already found out that I will need a <a href="https://en.wikipedia.org/wiki/Code_signing#Trusted-Library_Attribute" rel="noreferrer">code signing</a> certificate from a <a href="https://en.wikipedia.org/wiki/Certificate_authority" rel="noreferrer">CA</a> like <a href="https://en.wikipedia.org/wiki/Verisign" rel="noreferrer">Verisign</a> or instantssl.com. What I don't understand is what I need to do (if at all possible) to sign my EXE file. What is a simple explanation?</p> <p>Mel Green's answer took me further, but signtool wants me to specify what certificate to use in any case. Can I get a free code signing certificate somehow to test if this will work for me at all?</p> <p>Also please specify which certificate kind is the correct one. Most sites only mention "code signing" and talk about signing applications that are actually compiled by the user. This is not the case for me.</p>
[ { "answer_id": 25922635, "author": "Lee Richardson", "author_id": 40783, "author_profile": "https://Stackoverflow.com/users/40783", "pm_score": 5, "selected": false, "text": "signtool.exe sign /t http://timestamp.verisign.com/scripts/timstamp.dll /f \"MyCert.pfx\" /p MyPassword /d SignedFile.exe SignedFile.exe\n" }, { "answer_id": 49696454, "author": "Erick Castrillo", "author_id": 6353851, "author_profile": "https://Stackoverflow.com/users/6353851", "pm_score": 6, "selected": false, "text": "signtool.exe sign /a /s MY /sha1 sha1_thumbprint_value /t http://timestamp.verisign.com/scripts/timstamp.dll /v \"C:\\filename.dll\" C:\\filename.dll signtool sign /tr http://timestamp.digicert.com /td sha256 /fd sha256 /f \"c:\\path\\to\\mycert.pfx\" /p pfxpassword \"c:\\path\\to\\file.exe\" c:\\path\\to\\mycert.pfx pfxpassword c:\\path\\to\\file.exe CMD signtool signtool.exe verify /pa /v \"C:\\filename.dll\"" }, { "answer_id": 58559506, "author": "Server Overflow", "author_id": 46207, "author_profile": "https://Stackoverflow.com/users/46207", "pm_score": 4, "selected": false, "text": "prompt $\necho off\ncls\n\ncopy \"my.exe\" \"my.bak.exe\"\n\n\"c:\\Program Files (x86)\\Windows Kits\\10\\bin\\10.0.22000.0\\x64\\signtool.exe\" sign /fd SHA256 /f MyCertificate.pfx /p MyPassword My.exe\n\npause \n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252226", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9438/" ]
252,229
<p>What's the best way to unify several overlapping id systems into a unified one while maintaining the old id system.</p> <p>I have several different ids on my website... (E.g /publisher/1234 and /designer/1234) I would like to unify the ids into a new system, but want to preserve the functionality of the older system.</p>
[ { "answer_id": 25922635, "author": "Lee Richardson", "author_id": 40783, "author_profile": "https://Stackoverflow.com/users/40783", "pm_score": 5, "selected": false, "text": "signtool.exe sign /t http://timestamp.verisign.com/scripts/timstamp.dll /f \"MyCert.pfx\" /p MyPassword /d SignedFile.exe SignedFile.exe\n" }, { "answer_id": 49696454, "author": "Erick Castrillo", "author_id": 6353851, "author_profile": "https://Stackoverflow.com/users/6353851", "pm_score": 6, "selected": false, "text": "signtool.exe sign /a /s MY /sha1 sha1_thumbprint_value /t http://timestamp.verisign.com/scripts/timstamp.dll /v \"C:\\filename.dll\" C:\\filename.dll signtool sign /tr http://timestamp.digicert.com /td sha256 /fd sha256 /f \"c:\\path\\to\\mycert.pfx\" /p pfxpassword \"c:\\path\\to\\file.exe\" c:\\path\\to\\mycert.pfx pfxpassword c:\\path\\to\\file.exe CMD signtool signtool.exe verify /pa /v \"C:\\filename.dll\"" }, { "answer_id": 58559506, "author": "Server Overflow", "author_id": 46207, "author_profile": "https://Stackoverflow.com/users/46207", "pm_score": 4, "selected": false, "text": "prompt $\necho off\ncls\n\ncopy \"my.exe\" \"my.bak.exe\"\n\n\"c:\\Program Files (x86)\\Windows Kits\\10\\bin\\10.0.22000.0\\x64\\signtool.exe\" sign /fd SHA256 /f MyCertificate.pfx /p MyPassword My.exe\n\npause \n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252229", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4133/" ]
252,242
<p>Specifically, I have a model that has a field like this</p> <pre><code>pub_date = models.DateField("date published") </code></pre> <p>I want to be able to easily grab the object with the most recent <code>pub_date</code>. What is the easiest/best way to do this?</p> <p>Would something like the following do what I want?</p> <pre><code>Edition.objects.order_by('pub_date')[:-1] </code></pre>
[ { "answer_id": 252248, "author": "Harley Holcombe", "author_id": 1057, "author_profile": "https://Stackoverflow.com/users/1057", "pm_score": 6, "selected": true, "text": "obj = Edition.objects.latest('pub_date')\n get_latest_by obj = Edition.objects.latest()\n ordering" }, { "answer_id": 252414, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 5, "selected": false, "text": "Edition.objects.order_by('-pub_date')[0]\n" }, { "answer_id": 252496, "author": "Dan", "author_id": 444, "author_profile": "https://Stackoverflow.com/users/444", "pm_score": 2, "selected": false, "text": "0th" }, { "answer_id": 257243, "author": "Yogi", "author_id": 32801, "author_profile": "https://Stackoverflow.com/users/32801", "pm_score": 2, "selected": false, "text": "Edition.objects.order_by('-pub_date')[0]\n try:\n last = Edition.objects.order_by('-pub_date')[0]\nexcept IndexError:\n # Didn't find anything...\n latest()" }, { "answer_id": 17963568, "author": "Bharadwaj Srigiriraju", "author_id": 1076075, "author_profile": "https://Stackoverflow.com/users/1076075", "pm_score": 0, "selected": false, "text": ">>> Publisher.objects.order_by('name')[-1]\nTraceback (most recent call last):\n ...\nAssertionError: Negative indexing is not supported.\n >>> Publisher.objects.order_by('-name')[0]\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252242", "https://Stackoverflow.com", "https://Stackoverflow.com/users/85/" ]
252,249
<p>Lucene is an excellent search engine, but the .NET version is behind the official Java release (latest stable .NET release is 2.0, but the latest Java Lucene version is 2.4, which has more features).</p> <p>How do you get around this?</p>
[ { "answer_id": 252254, "author": "Kalid", "author_id": 109, "author_profile": "https://Stackoverflow.com/users/109", "pm_score": 5, "selected": true, "text": "ikvmc -target:library <path-to-lucene.jar>\n QueryParser parser = new QueryParser(\"field1\", analyzer);\njava.util.Map boosts = new java.util.HashMap();\nboosts.put(\"field1\", new java.lang.Float(1.0));\nboosts.put(\"field2\", new java.lang.Float(10.0));\n\nMultiFieldQueryParser multiParser = new MultiFieldQueryParser\n (new string[] { \"field1\", \"field2\" }, analyzer, boosts);\nmultiParser.setDefaultOperator(QueryParser.Operator.OR);\n\nQuery query = multiParser.parse(\"ABC\");\nHits hits = isearcher.search(query);\n System.Out Console.Writeln ikvmc -target:library lucene-highlighter-2.4.0.jar -r:lucene-core-2.4.0.dll\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252249", "https://Stackoverflow.com", "https://Stackoverflow.com/users/109/" ]
252,252
<p>Given the following markup:</p> <pre><code>&lt;ul&gt; &lt;li&gt;apple&lt;/li&gt; &lt;li class="highlight"&gt;orange&lt;/li&gt; &lt;li&gt;pear&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>Both the <code>ul</code>s and the <code>li</code>s widths appear to be 100%. If I apply a <code>background-color</code> to the list item, the highlight stretches the full width of the page.</p> <p>I only want the background highlight to stretch as wide as the widest item (with maybe some padding). How do I constrain the <code>li</code>s (or perhaps the <code>ul</code>s) width to the width of the widest item?</p>
[ { "answer_id": 252259, "author": "BoltBait", "author_id": 20848, "author_profile": "https://Stackoverflow.com/users/20848", "pm_score": 2, "selected": false, "text": "<ul>\n <li>apple</li>\n <li><span class=\"highlight\">orange</span></li>\n <li>pear</li>\n</ul>\n" }, { "answer_id": 252290, "author": "buti-oxa", "author_id": 2515, "author_profile": "https://Stackoverflow.com/users/2515", "pm_score": 6, "selected": true, "text": "ul {float: left; }" }, { "answer_id": 252334, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 2, "selected": false, "text": "span <ul>\n <li>apple</li>\n <li><span class=\"highlight\">orange</span></li>\n <li>pear</li>\n</ul>\n $('li.highlight').wrapInner(\"<span></span>\");\n li.highlight span { background-color: #f0f; }\n" }, { "answer_id": 29753670, "author": "Nathan", "author_id": 294317, "author_profile": "https://Stackoverflow.com/users/294317", "pm_score": 0, "selected": false, "text": "style=\"float: left;\" ul ul style=\"clear: left;\" ul float clear" }, { "answer_id": 32468792, "author": "redress", "author_id": 4167140, "author_profile": "https://Stackoverflow.com/users/4167140", "pm_score": 0, "selected": false, "text": "ul li div display: inline-block <div id='dropdown_tab' style='display: inline-block'>dropdown\n <ul id='dropdown_menu' style='display: none'>\n <li>optoin 1</li>\n <li>optoin 2</li>\n <li id='option_3'>optoin 3\n <ul id='dropdown_menu2' style='display: none'>\n <li>second 1</li>\n <li>second 2</li>\n <li>second 3</li>\n </ul>\n </li>\n </ul>\n </div>\n" }, { "answer_id": 59270684, "author": "TylerH", "author_id": 2756409, "author_profile": "https://Stackoverflow.com/users/2756409", "pm_score": -1, "selected": false, "text": "float <ul> display: block; display <ul> float display: inline-block; ul {\n display: inline-block;\n background-color: green;\n}\n.highlight {\n background-color: orange; /* for demonstration */\n padding: 15px; /* for demonstration */\n} <ul>\n <li>apple</li>\n <li class=\"highlight\">orange</li>\n <li>pear</li>\n <li>banana</li>\n</ul>" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26627/" ]
252,257
<p>I was just wondering, since the <strong>sealed</strong> keyword's existence indicates that it's the class author's decision as to whether other classes are allowed to inherit from it, why aren't classes sealed by default, with some keyword to mark them explicitly as extensible?</p> <p>I know it's somewhat different, but access modifiers work this way. With the default being restrictive and fuller access only being granted with the insertion of a keyword.</p> <p>There's a large chance that I haven't thought this through properly, though, so please be humane!</p>
[ { "answer_id": 252745, "author": "Pablo Retyk", "author_id": 30729, "author_profile": "https://Stackoverflow.com/users/30729", "pm_score": 6, "selected": true, "text": "public extensible class MyClass\n public sealed class MyClass\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252257", "https://Stackoverflow.com", "https://Stackoverflow.com/users/82/" ]
252,260
<p>I am trying to use reflector.InvokeMethod to invoke a function with an optional parameter. The function looks like this: </p> <pre><code>Private Function DoSomeStuff(ByVal blah1 as string, ByVal blah2 as string, Optional ByVal blah3 as string = "45") as boolean 'stuff end function </code></pre> <p>and I'm Invoking it like this:</p> <pre><code>Dim result As Boolean = Reflector.InvokeMethod(AccessModifier.private,obj_of_Class, "DoSomeStuff", Param1, Param2, Param3) </code></pre> <p>This works fine, other than when I don't pass the third (optional) parameter, it dosn't hit the function.</p> <pre><code>Dim result As Boolean = Reflector.InvokeMethod(AccessModifier.private,obj_of_Class, "DoSomeStuff", Param1, Param2) </code></pre> <p>Is there a way I can use Reflector.invokeMethod to call this function without passing the optional parameter? or another way to achieve this?</p>
[ { "answer_id": 319190, "author": "codeConcussion", "author_id": 1321, "author_profile": "https://Stackoverflow.com/users/1321", "pm_score": 0, "selected": false, "text": "Private Overloads Function DoSomeStuff(ByVal blah1 As String, ByVal blah2 As String) As Boolean\n Return DoSomeStuff(blah1, blah2, \"45\")\nEnd Function\n\nPrivate Overloads Function DoSomeStuff(ByVal blah1 As String, ByVal blah2 As String, ByVal blah3 As String) As Boolean\n 'stuff\nEnd Function\n" }, { "answer_id": 319209, "author": "Rob", "author_id": 34224, "author_profile": "https://Stackoverflow.com/users/34224", "pm_score": 2, "selected": false, "text": "DoSomeStuff(blah1, blah2) DoSomeStuff(blah1, blah2, \"45\")" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252260", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
252,267
<p>The code at the end produces a compile error:</p> <pre><code>NotApplicable.java:7: run() in cannot be applied to (int) run(42); ^ 1 error </code></pre> <p>The question is why? Why does javac think I am calling run(), and does not find run(int bar)? It correctly called foo(int bar). Why do I have to use NotApplicable.this.run(42);? Is it a bug?</p> <pre><code>public class NotApplicable { public NotApplicable() { new Runnable() { public void run() { foo(42); run(42); // uncomment below to fix //NotApplicable.this.run(42); } }; } private void run(int bar) { } public void foo(int bar) { } } </code></pre>
[ { "answer_id": 252276, "author": "Claudiu", "author_id": 15055, "author_profile": "https://Stackoverflow.com/users/15055", "pm_score": 0, "selected": false, "text": "run new Runnable() {} import java.util.*;\n\npublic class tmp\n{\n private int x = 20;\n public static class Inner\n {\n private List x = new ArrayList();\n public void func()\n {\n System.out.println(x + 10);\n }\n }\n\n public static void main(String[] args)\n {\n (new Inner()).func();\n }\n}\n x" }, { "answer_id": 252401, "author": "Alex B", "author_id": 6180, "author_profile": "https://Stackoverflow.com/users/6180", "pm_score": 5, "selected": true, "text": "this run(int) this NotApplicable.this.run(42) this Runnable run() NotApplicable.this NotApplicable run(int) public class Outer{\n\n public Outer() {\n new Runnable() {\n public void printit() {\n System.out.println( \"Anonymous Inner\" );\n }\n public void run() {\n printit(); // prints \"Anonymous Inner\"\n this.printit(); //prints \"Anonymous Inner\"\n\n // would not be possible to execute next line without this behavior\n Outer.this.printit(); //prints \"Outer\" \n }\n };\n }\n\n public void printit() {\n System.out.println( \"Outer\" );\n }\n}\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252267", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21838/" ]
252,268
<p>I develop and maintain small intranet web apps(JSP and Resin).</p> <p>Some users takes so much time to complete the forms that, when they submit, they lose all their input data because of session timeout.</p> <p>Currently I prolonged session timeout to 30 minutes and display count-down clock till session timeout on top of the page, but, I think their must be better ways to protect user inputs.</p> <p>What is the best practices?</p> <hr> <p><strong>Addendum</strong> Our users make several kind of reports with the web-app, and the whole contents of each report are stored in a JavaBean stored in the session.</p> <p>As suggested by some, Ajax or iframe should do the quick fix.</p> <p>I now know that it is better not to abuse session with heavy objects, but I'm not sure how best to refactor current mess. Some people suggested to make the web-app <em>stateless</em>. Any suggestion for refactoring is welcome.</p>
[ { "answer_id": 252349, "author": "Jere.Jones", "author_id": 19476, "author_profile": "https://Stackoverflow.com/users/19476", "pm_score": 2, "selected": false, "text": "<input type=\"hidden\" name=\"user\" value=\"bob\" />\n<input type=\"hidden\" name=\"currentRecordId\" value=\"2345\" />\n<input type=\"hidden\" name=\"otherStuff\" value=\"whocares\" />\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252268", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29197/" ]
252,274
<p>I open gmail, click on an inbox item, and look at source of the page. It doesn't look like there isn't any proper html to relate to what is shown on the actual page.</p> <p>How is the source getting processed into the actual page? Is there some javascript processing this information?</p>
[ { "answer_id": 252307, "author": "Richard A", "author_id": 24355, "author_profile": "https://Stackoverflow.com/users/24355", "pm_score": 2, "selected": false, "text": "try{function aa(a,b){return a.appendChild=b}function ba(a,b){return a.textContent=b}function da(a,b){return a.stop=b}function ea(a,b){return a.toString=b}function fa(a,b){return a.length=b}function ga(a,b){return a.title=b}function ha(a,b){return a.position=b}function ia(a,b){return a.create=b}function ja(a,b){return a.className=b}function ka(a,b){return a.width=b}function la(a,b){return a.expand=b}function ma(a,b){return a.abort=b}function na(a,b){return a.data=b}function oa(a,b){return a.next=b}\nfunction pa(a,b){return a.load=b}function d(a,b){return a.innerHTML=b}function qa(a,b){return a.onerror=b}function sa(a,b){return a.getDate=b}function ta(a,b){return a.value=b}function ua(a,b){return a.disabled=b}function va(a,b){return a.dispatchEvent=b}function wa(a,b){return a.currentTarget=b}function xa(a,b){return a.left=b}function ya(a,b){return a.hideFocus=b}function za(a,b){return a.removeChild=b}function Aa(a,b){return a.target=b}function Ba(a,b){return a.screenX=b}\nfunction Ca(a,b){return a.screenY=b}function Da(a,b){return a.send=b}function Ea(a,b){return a.remove=b}function Fa(a,b){return a.start=b}function Ga(a,b){return a.cssText=b}function Ha(a,b){return a.keyCode=b}function Ia(a,b){return a.enabled=b}function Ja(a,b){return a.href=b}function Ka(a,b){return a.handleEvent=b}function La(a,b){return a.removeNode=b}function Ma(a,b){return a.detach=b}function Na(a,b){return a.type=b}function Oa(a,b){return a.contains=b}function Pa(a,b){return a.tabIndex=b}\nfunction Qa(a,b){return a.cellSpacing=b}function Ra(a,b){return a.clear=b}function Sa(a,b){return a.setPosition=b}function Ta(a,b){return a.cellPadding=b}function Ua(a,b){return a.display=b}function Va(a,b){return a.execute=b}function Wa(a,b){return a.height=b}function Xa(a,b){return a.nodeValue=b}function Ya(a,b){return a.clientX=b}function Za(a,b){return a.clientY=b}function ab(a,b){return a.right=b}function bb(a,b){return a.visibility=b}\nfunction aaa(a){var b=cb[i](db);(new Image).src=baa+eb(b)+\"&jsmsg=\"+eb(a)+caa+fb+daa+(new Date)[gb]()}function _B_record(){cb[k]((new Date)[gb]())}function _B_prog(a){top.pr=a;if(hb===undefined){var b=top[ib][jb](eaa);hb=b?b[m]:null}if(hb){ka(hb,n[kb](a*0.99)+lb);if(a==100)hb=null}}function _B_err(a){aaa(a);throw a;}function mb(a,b){var c=a[nb](ob),e=b||pb;for(var f;f=c[rb]();)if(e[f])e=e[f];else return null;return e}function sb(){}function tb(a){a.lg=function $(){return a.bmc||(a.bmc=new a)}}\nfunction ub(a){var b=typeof a;if(b==vb)if(a){if(typeof a[o]==wb&&typeof a[xb]!=\"undefined\"&&!faa(a,gaa))return yb;if(typeof a[q]!=\"undefined\")return zb}else return Ab;else if(b==zb&&typeof a[q]==\"undefined\")return vb;return b}function haa(a,b){if(b in a)for(var c in a)if(c==b&&Bb[r][Cb][q](a,b))return true;return false}function Db(a){return typeof a!=\"undefined\"}function Eb(a){return ub(a)==yb}function Fb(a){var b=ub(a);return b==yb||b==vb&&typeof a[o]==wb}function Gb(a){return typeof a==Hb}\nfunction Ib(a){return typeof a==wb}function Jb(a){return ub(a)==zb}function Kb(a){var b=ub(a);return b==vb||b==yb||b==zb}function Lb(a){if(a[Cb]&&a[Cb](iaa)){var b=a.closure_hashCode_;if(b)return b}a.closure_hashCode_||(a.closure_hashCode_=++jaa);return a.closure_hashCode_}\nfunction s(a,b){var c=a.SSb;if(arguments[o]>2){var e=Array[r][Mb][q](arguments,2);c&&e[Nb][Ob](e,c);c=e}b=a.WSb||b;a=a.TSb||a;var f,g=b||pb;f=c?function(){var h=Array[r][Mb][q](arguments);h[Nb][Ob](h,c);return a[Ob](g,h)}:function(){return a[Ob](g,arguments)};f.SSb=c;f.WSb=b;f.TSb=a;return f}function Pb(a){var b=Array[r][Mb][q](arguments,1);b[Nb](a,null);return s[Ob](null,b)}function Qb(a,b){for(var c in b)a[c]=b[c]}\nfunction t(a,b){function c(){}c.prototype=b[r];a.F=b[r];a.prototype=new c;a[r].constructor=a}function Rb(a,b,c){if(a[Sb])return a[Sb](b,c);if(Array[Sb])return Array[Sb](a,b,c);var e=c==null?0:c<0?n.max(0,a[o]+c):c;for(var f=e;f<a[o];f++)if(f in a&&a[f]===b)return f;return-1}function Tb(a,b,c){if(a[Ub])a[Ub](b,c);else if(Array[Ub])Array[Ub](a,b,c);else{var e=a[o],f=Gb(a)?a[nb](v):a;for(var g=0;g<e;g++)g in f&&b[q](c,f[g],g,a)}}\nfunction Vb(a,b,c){if(a.map)return a.map(b,c);if(Array.map)return Array.map(a,b,c);var e=a[o],f=[],g=0,h=Gb(a)?a[nb](v):a;for(var j=0;j<e;j++)if(j in h)f[g++]=b[q](c,h[j],j,a);return f}function Wb(a,b,c){if(a[Xb])return a[Xb](b,c);if(Array[Xb])return Array[Xb](a,b,c);var e=a[o],f=Gb(a)?a[nb](v):a;for(var g=0;g<e;g++)if(g in f&&b[q](c,f[g],g,a))return true;return false}\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252274", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
252,282
<p>I'm working on an import (from Excel) dialog to select ranges of cells.</p> <p>When the range is selected, I use the event sink to catch the event and highlight the first row and first column.</p> <p>I need to unhighlight the previous selection's first row and column. I don't think it's safe to just get the selected range at the time the selection changes and remember it, such as (pseudocode for brevity and clarity):</p> <pre><code>OnSelectionChange() { if (m_PrevSelection) UnHilite(m_PrevSelection); HiliteCurrentSelection(); GetSelectedRange(m_PrevSelection); } </code></pre> <p>I'm guessing that just holding onto that range (obtained from _Application::Selection) without releasing it is going to cause all sorts of problems. I haven't found a way to copy the range (IRange Copy just copies cell contents from one range to another).</p> <p>I guess I could take the range's cell addresses and store those, then recreate a range from them when I need to do the unhighlighting. This would seem to me to come up often. Is there a more elegant solution?</p>
[ { "answer_id": 252439, "author": "dbb", "author_id": 25675, "author_profile": "https://Stackoverflow.com/users/25675", "pm_score": 3, "selected": true, "text": "Set Rng = Application.Selection\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252282", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965047/" ]
252,286
<p>This sounds dumb, but I can't get it to work. I think i just dont' understand the difference between <code>%%v, %v% and %v</code></p> <p>Here's what I'm trying to do:</p> <pre><code>for %%v in (*.flv) do ffmpeg.exe -i "%%v" -y -f mjpeg -ss 0.001 -vframes 1 -an "%%v.jpg" </code></pre> <p>This successfully generates a thumbnail for each of the movies, but the problem is:</p> <pre><code>movie.flv -&gt; movie.flv.jpg </code></pre> <p>So what I would like to do is pull the last 4 characters off <code>%%v</code> and use that for the second variable.</p> <p>I've been trying things like this:</p> <pre><code>%%v:~0,-3% </code></pre> <p>But it's not working, nor are any of the iterations of that that I could think of.</p> <p>Any ideas?</p>
[ { "answer_id": 252316, "author": "Jeff Hillman", "author_id": 3950, "author_profile": "https://Stackoverflow.com/users/3950", "pm_score": 3, "selected": false, "text": "for %%v in (*.flv) do ffmpeg.exe -i \"%%v\" -y -f mjpeg -ss 0.001 -vframes 1 -an \"%%~nv.jpg\"\n %~I - expands %I removing any surrounding quotes (\")\n%~fI - expands %I to a fully qualified path name\n%~dI - expands %I to a drive letter only\n%~pI - expands %I to a path only\n%~nI - expands %I to a file name only\n%~xI - expands %I to a file extension only\n%~sI - expanded path contains short names only\n%~aI - expands %I to file attributes of file\n%~tI - expands %I to date/time of file\n%~zI - expands %I to size of file\n%~$PATH:I - searches the directories listed in the PATH\n environment variable and expands %I to the\n fully qualified name of the first one found.\n If the environment variable name is not\n defined or the file is not found by the\n search, then this modifier expands to the\n empty string\n" }, { "answer_id": 252768, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 2, "selected": false, "text": "for help for set FOO=C:\\bar\\foo\ncd %FOO%\\gah\n" }, { "answer_id": 6310580, "author": "BlueRaja - Danny Pflughoeft", "author_id": 238419, "author_profile": "https://Stackoverflow.com/users/238419", "pm_score": 5, "selected": false, "text": "setlocal enabledelayedexpansion\n\n...\n\n::Replace \"12345\" with \"abcde\"\nfor %%i in (*.txt) do (\n set temp=%%i\n echo !temp:12345=abcde!\n)\n" }, { "answer_id": 36946079, "author": "Farsee", "author_id": 3366321, "author_profile": "https://Stackoverflow.com/users/3366321", "pm_score": 1, "selected": false, "text": "for %%v in (*.flv) do call :processMpeg \"%%v\"\ngoto :eof\n\n:processMpeg\n set fileName=%~n1\n echo P1=%1 fileName=%fileName% fullpath=%~dpnx1\n ffmpeg.exe -i \"%~1\" -y -f mjpeg -ss 0.001 -vframes 1 -an \"%filename%.jpg\"\n goto :eof\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252286", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10680/" ]
252,287
<p>Here's my setup: a Mac, running OS X Tiger. Windows XP running in a virtual machine (Parallels). Windows XP has my Mac home directory mapped as a network drive.</p> <p>I have two files in a directory of my Mac home directory:</p> <h3>foo.py</h3> <pre><code>pass </code></pre> <h3>test.py</h3> <pre><code>import foo </code></pre> <p>If I run test.py from within my virtual machine by typing 'python test.py', I get this:</p> <pre><code>Traceback (most recent call last): File "test.py", line 1, in &lt;module&gt; import foo ImportError: No module named foo </code></pre> <p>If I try to import foo from the console (running python under Windows from the same directory), all is well:</p> <pre><code>Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import foo &gt;&gt;&gt; </code></pre> <p>If I run test.py with Mac python, all is well.</p> <p>If I copy test.py and foo.py to a different directory, I can run test.py under Windows without problems.</p> <p>There is an <strong>init</strong>.py in the original directory, but it is empty. Furthermore, copying it with the other files doesn't break anything in the previous paragraph.</p> <p>There are no python-related environment variables set.</p> <p>Any ideas?</p>
[ { "answer_id": 254355, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 1, "selected": false, "text": "python -v -v test.py\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252287", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15154/" ]
252,297
<p>I was making the following call:</p> <pre><code>result = RegOpenKeyEx(key, s, 0, KEY_READ, &amp;key); </code></pre> <p>(C++, Visual Studio 5, Vista 64bit).</p> <p>It is failing with error code 2 ("File not found") even though "<code>regedit</code>" shows that the key exists. This code has always worked on 32bit XP. Why is it "file not found" when it clearly is there?</p>
[ { "answer_id": 252302, "author": "Tim Cooper", "author_id": 10592, "author_profile": "https://Stackoverflow.com/users/10592", "pm_score": 7, "selected": true, "text": "KEY_WOW64_64KEY result = RegOpenKeyEx(key, s, 0, KEY_READ|KEY_WOW64_64KEY, &key);\n" }, { "answer_id": 3104602, "author": "Alex", "author_id": 371598, "author_profile": "https://Stackoverflow.com/users/371598", "pm_score": 0, "selected": false, "text": "dwResult = RegOpenKeyEx(HKEY_LOCAL_MACHINE,\n (LPWSTR)\"SOFTWARE\\\\0test\",\n 0,\n WRITE_DAC ,\n &hKey);\n dwResult = RegOpenKeyEx(HKEY_LOCAL_MACHINE,\n _T(\"SOFTWARE\\\\0test\"),\n 0,\n WRITE_DAC ,\n &hKey);\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10592/" ]
252,304
<p>In our data access layer at work we have this standard implementation where the class is accessed through a singleton public property which looks something like this:</p> <pre><code>public static CustomerController Instance { get { lock(singletonLock) { if( _instance == null ) { _instance = new CustomerController(); } return _instance; } } } </code></pre> <p>now, I get what the code is doing, but I was wondering why you would do this over just creating an instance of the class each time it is used?</p>
[ { "answer_id": 252363, "author": "Keith Nicholas", "author_id": 10431, "author_profile": "https://Stackoverflow.com/users/10431", "pm_score": 1, "selected": false, "text": " public static CustomerController Instance\n {\n get \n {\n if( _instance == null )\n {\n lock(singletonLock)\n {\n if( _instance == null )\n {\n _instance = new CustomerController(); \n }\n\n }\n } \n return _instance;\n }\n }\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252304", "https://Stackoverflow.com", "https://Stackoverflow.com/users/493/" ]
252,323
<p>I have a program that monitors debug messages and I have tried using a TextBox and appended the messages to it but it doesn't scale very well and slows way down when the number of messages gets large. I then tried a ListBox but the scrolling was snapping to the top when appending new messages. It also doesn't allow for cut and paste like the text box does.</p> <p>What is a better way to implement a console like element embedded in a winforms window.</p> <p>Edit: I would still like to be able to embed a output window like visual studio but since I can't figure out an easy way here are the two solutions I use. In addition to using the RichTextBox which works but you have to clear it every now and then. I use a console that I pinvoke. Here is a little wrapper class that I wrote to handle this. </p> <pre><code> using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.InteropServices; namespace Con { class Ext_Console { static bool console_on = false; public static void Show(bool on,string title) { console_on = on; if (console_on) { AllocConsole(); Console.Title = title; // use to change color Console.BackgroundColor = System.ConsoleColor.White; Console.ForegroundColor = System.ConsoleColor.Black; } else { FreeConsole(); } } public static void Write(string output) { if (console_on) { Console.Write(output); } } public static void WriteLine(string output) { if (console_on) { Console.WriteLine(output); } } [DllImport("kernel32.dll")] public static extern Boolean AllocConsole(); [DllImport("kernel32.dll")] public static extern Boolean FreeConsole(); } } // example calls Ext_Console.Write("console output "); Ext_Console.WriteLine("console output"); Ext_Console.Show(true,"Title of console"); </code></pre>
[ { "answer_id": 252347, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": " private void AddConsoleComment(string comment)\n {\n textBoxConsole.Text += comment + System.Environment.NewLine;\n textBoxConsole.Select(textBoxConsole.Text.Length,0);\n textBoxConsole.ScrollToCaret();\n }\n" }, { "answer_id": 252366, "author": "Corey Trager", "author_id": 9328, "author_profile": "https://Stackoverflow.com/users/9328", "pm_score": 2, "selected": false, "text": " ListViewItem itm = new ListViewItem();\n itm.Text = txt;\n this.listView1.Items.Add(itm);\n this.listView1.EnsureVisible(listView1.Items.Count - 1);\n" }, { "answer_id": 252460, "author": "Foredecker", "author_id": 18256, "author_profile": "https://Stackoverflow.com/users/18256", "pm_score": 3, "selected": false, "text": "using System;\nusing System.Windows.Forms;\nusing Microsoft.Win32.SafeHandles;\nusing System.Diagnostics;\nusing MWin32Api;\n\nnamespace WFConsole\n{\n static class Program\n {\n static private SafeFileHandle ConsoleHandle;\n\n /// <summary>\n /// Initialize the Win32 console for this process.\n /// </summary>\n static private void InitWin32Console()\n {\n if ( !K32.AllocConsole() ) {\n MessageBox.Show( \"Cannot allocate console\",\n \"Error\",\n MessageBoxButtons.OK,\n MessageBoxIcon.Error );\n return;\n }\n\n IntPtr handle = K32.CreateFile(\n \"CONOUT$\", // name\n K32.GENERIC_WRITE | K32.GENERIC_READ, // desired access\n K32.FILE_SHARE_WRITE | K32.FILE_SHARE_READ, // share access\n null, // no security attributes\n K32.OPEN_EXISTING, // device already exists\n 0, // no flags or attributes\n IntPtr.Zero ); // no template file.\n\n ConsoleHandle = new SafeFileHandle( handle, true );\n\n if ( ConsoleHandle.IsInvalid ) {\n MessageBox.Show( \"Cannot create diagnostic console\",\n \"Error\",\n MessageBoxButtons.OK,\n MessageBoxIcon.Error );\n return;\n }\n\n //\n // Set the console screen buffer and window to a reasonable size\n // 1) set the screen buffer sizse\n // 2) Get the maximum window size (in terms of characters) \n // 3) set the window to be this size\n //\n const UInt16 conWidth = 256;\n const UInt16 conHeight = 5000;\n\n K32.Coord dwSize = new K32.Coord( conWidth, conHeight );\n if ( !K32.SetConsoleScreenBufferSize( ConsoleHandle.DangerousGetHandle(), dwSize ) ) {\n MessageBox.Show( \"Can't get console screen buffer information.\",\n \"Error\",\n MessageBoxButtons.OK,\n MessageBoxIcon.Error );\n return;\n }\n\n K32.Console_Screen_Buffer_Info SBInfo = new K32.Console_Screen_Buffer_Info();\n if ( !K32.GetConsoleScreenBufferInfo( ConsoleHandle.DangerousGetHandle(), out SBInfo ) ) {\n MessageBox.Show( \"Can't get console screen buffer information.\",\n \"Error\",\n MessageBoxButtons.OK,\n MessageBoxIcon.Exclamation);\n return;\n }\n\n K32.Small_Rect sr; ;\n sr.Left = 0;\n sr.Top = 0;\n sr.Right = 132 - 1;\n sr.Bottom = 51 - 1;\n\n if ( !K32.SetConsoleWindowInfo( ConsoleHandle.DangerousGetHandle(), true, ref sr ) ) {\n MessageBox.Show( \"Can't set console screen buffer information.\",\n \"Error\",\n MessageBoxButtons.OK,\n MessageBoxIcon.Error );\n return;\n }\n\n IntPtr conHWND = K32.GetConsoleWindow();\n\n if ( conHWND == IntPtr.Zero ) {\n MessageBox.Show( \"Can't get console window handle.\",\n \"Error\",\n MessageBoxButtons.OK,\n MessageBoxIcon.Error );\n return;\n }\n\n if ( !U32.SetForegroundWindow( conHWND ) ) {\n MessageBox.Show( \"Can't set console window as foreground.\",\n \"Error\",\n MessageBoxButtons.OK,\n MessageBoxIcon.Error );\n return;\n }\n\n K32.SetConsoleTitle( \"Test - Console\" );\n\n Trace.Listeners.Add( new ConsoleTraceListener() );\n }\n\n /// <summary>\n /// The main entry point for the application.\n /// </summary>\n [STAThread]\n static void Main()\n {\n InitWin32Console();\n Application.EnableVisualStyles();\n Application.SetCompatibleTextRenderingDefault( false );\n Application.Run( new Main() );\n }\n }\n}\n\n\nusing System;\nusing System.Runtime.InteropServices;\n\nnamespace MWin32Api\n{\n #region Kernel32 Functions\n\n //--------------------------------------------------------------------------\n /// <summary>\n /// Functions in Kernel32.dll\n /// </summary>\n public sealed class K32\n {\n #region Data Structures, Types and Constants\n //----------------------------------------------------------------------\n // Data Structures, Types and Constants\n // \n\n [StructLayout( LayoutKind.Sequential )]\n public class SecurityAttributes\n {\n public UInt32 nLength;\n public UIntPtr lpSecurityDescriptor;\n public bool bInheritHandle;\n }\n\n [StructLayout( LayoutKind.Sequential, Pack = 1, Size = 4 )]\n public struct Coord\n {\n public Coord( UInt16 tx, UInt16 ty )\n {\n x = tx;\n y = ty;\n }\n public UInt16 x;\n public UInt16 y;\n }\n\n [StructLayout( LayoutKind.Sequential, Pack = 1, Size = 8 )]\n public struct Small_Rect\n {\n public Int16 Left;\n public Int16 Top;\n public Int16 Right;\n public Int16 Bottom;\n\n public Small_Rect( short tLeft, short tTop, short tRight, short tBottom )\n {\n Left = tLeft;\n Top = tTop;\n Right = tRight;\n Bottom = tBottom;\n }\n }\n\n [StructLayout( LayoutKind.Sequential, Pack = 1, Size = 24 )]\n public struct Console_Screen_Buffer_Info\n {\n public Coord dwSize;\n public Coord dwCursorPosition;\n public UInt32 wAttributes;\n public Small_Rect srWindow;\n public Coord dwMaximumWindowSize;\n }\n\n\n public const int ZERO_HANDLE_VALUE = 0;\n public const int INVALID_HANDLE_VALUE = -1;\n\n #endregion\n #region Console Functions\n //----------------------------------------------------------------------\n // Console Functions\n // \n [DllImport( \"kernel32.dll\", SetLastError = true )]\n public static extern bool AllocConsole();\n\n [DllImport( \"kernel32.dll\", SetLastError = true )]\n public static extern bool SetConsoleScreenBufferSize(\n IntPtr hConsoleOutput,\n Coord dwSize );\n\n [DllImport( \"kernel32.dll\", SetLastError = true )]\n public static extern bool GetConsoleScreenBufferInfo(\n IntPtr hConsoleOutput,\n out Console_Screen_Buffer_Info lpConsoleScreenBufferInfo );\n\n [DllImport( \"kernel32.dll\", SetLastError = true )]\n public static extern bool SetConsoleWindowInfo(\n IntPtr hConsoleOutput,\n bool bAbsolute,\n ref Small_Rect lpConsoleWindow );\n\n [DllImport( \"kernel32.dll\", SetLastError = true )]\n public static extern IntPtr GetConsoleWindow();\n\n [DllImport( \"kernel32.dll\", SetLastError = true )]\n public static extern bool SetConsoleTitle(\n string Filename );\n\n #endregion\n #region Create File\n //----------------------------------------------------------------------\n // Create File\n // \n public const UInt32 CREATE_NEW = 1;\n public const UInt32 CREATE_ALWAYS = 2;\n public const UInt32 OPEN_EXISTING = 3;\n public const UInt32 OPEN_ALWAYS = 4;\n public const UInt32 TRUNCATE_EXISTING = 5;\n public const UInt32 FILE_SHARE_READ = 1;\n public const UInt32 FILE_SHARE_WRITE = 2;\n public const UInt32 GENERIC_WRITE = 0x40000000;\n public const UInt32 GENERIC_READ = 0x80000000;\n\n [DllImport( \"kernel32.dll\", SetLastError = true )]\n public static extern IntPtr CreateFile(\n string Filename,\n UInt32 DesiredAccess,\n UInt32 ShareMode,\n SecurityAttributes SecAttr,\n UInt32 CreationDisposition,\n UInt32 FlagsAndAttributes,\n IntPtr TemplateFile );\n\n #endregion\n #region Win32 Miscelaneous\n //----------------------------------------------------------------------\n // Miscelaneous\n // \n [DllImport( \"kernel32.dll\" )]\n public static extern bool CloseHandle( UIntPtr handle );\n\n #endregion\n\n //----------------------------------------------------------------------\n private K32()\n {\n }\n }\n #endregion\n\n //--------------------------------------------------------------------------\n /// <summary>\n /// Functions in User32.dll\n /// </summary>\n #region User32 Functions\n public sealed class U32\n {\n [StructLayout( LayoutKind.Sequential )]\n public struct Rect\n {\n public Int32 Left;\n public Int32 Top;\n public Int32 Right;\n public Int32 Bottom;\n\n public Rect( short tLeft, short tTop, short tRight, short tBottom )\n {\n Left = tLeft;\n Top = tTop;\n Right = tRight;\n Bottom = tBottom;\n }\n }\n\n [DllImport( \"user32.dll\" )]\n public static extern bool GetWindowRect(\n IntPtr hWnd,\n [In][MarshalAs( UnmanagedType.LPStruct )]Rect lpRect );\n\n [DllImport( \"user32.dll\", SetLastError = true )]\n public static extern bool SetForegroundWindow(\n IntPtr hWnd );\n\n //----------------------------------------------------------------------\n private U32()\n {\n }\n } // U32 class\n #endregion\n} // MWin32Api namespace\n" }, { "answer_id": 252507, "author": "dbkk", "author_id": 838, "author_profile": "https://Stackoverflow.com/users/838", "pm_score": 3, "selected": false, "text": "void AddLogMessage(String message)\n{\n list.Items.Add(message);\n\n // DO: Append message to file as needed\n\n // Clip the list\n if (list.count > ListMaxSize)\n { \n list.Items.RemoveRange(0, list.Count - listMinSize);\n }\n\n // DO: Focus the last item on the list\n}\n" }, { "answer_id": 14944970, "author": "psamwel", "author_id": 3089, "author_profile": "https://Stackoverflow.com/users/3089", "pm_score": 2, "selected": false, "text": "public class ConsoleTextBox: TextBox\n{\n private List<string> contents = new List<string>();\n private const int MAX = 50;\n\n public void WriteLine(string input)\n {\n if (contents.Count == MAX)\n contents.RemoveAt(MAX-1);\n contents.Insert(0, input);\n\n Rewrite();\n }\n\n private void Rewrite()\n {\n var sb = new StringBuilder();\n foreach (var s in contents)\n {\n sb.Append(s);\n sb.Append(Environment.NewLine);\n }\n this.Text = sb.ToString();\n }\n}\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252323", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32958/" ]
252,352
<p>Is it possible to change the <code>RowCount</code> of a <code>DataGrid</code> in flash after it has been created on the stage?</p> <p>I am loading an XML file externally that contains the number of rows the <code>DataGrid</code> should have, but the problem is that because this file is not loaded at runtime, it just picks the default 3 items. Maybe I have to reload the <code>DataGrid</code> on the stage, or loop until it is defined.</p> <p>Does anyone have experience with this?</p>
[ { "answer_id": 252347, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": " private void AddConsoleComment(string comment)\n {\n textBoxConsole.Text += comment + System.Environment.NewLine;\n textBoxConsole.Select(textBoxConsole.Text.Length,0);\n textBoxConsole.ScrollToCaret();\n }\n" }, { "answer_id": 252366, "author": "Corey Trager", "author_id": 9328, "author_profile": "https://Stackoverflow.com/users/9328", "pm_score": 2, "selected": false, "text": " ListViewItem itm = new ListViewItem();\n itm.Text = txt;\n this.listView1.Items.Add(itm);\n this.listView1.EnsureVisible(listView1.Items.Count - 1);\n" }, { "answer_id": 252460, "author": "Foredecker", "author_id": 18256, "author_profile": "https://Stackoverflow.com/users/18256", "pm_score": 3, "selected": false, "text": "using System;\nusing System.Windows.Forms;\nusing Microsoft.Win32.SafeHandles;\nusing System.Diagnostics;\nusing MWin32Api;\n\nnamespace WFConsole\n{\n static class Program\n {\n static private SafeFileHandle ConsoleHandle;\n\n /// <summary>\n /// Initialize the Win32 console for this process.\n /// </summary>\n static private void InitWin32Console()\n {\n if ( !K32.AllocConsole() ) {\n MessageBox.Show( \"Cannot allocate console\",\n \"Error\",\n MessageBoxButtons.OK,\n MessageBoxIcon.Error );\n return;\n }\n\n IntPtr handle = K32.CreateFile(\n \"CONOUT$\", // name\n K32.GENERIC_WRITE | K32.GENERIC_READ, // desired access\n K32.FILE_SHARE_WRITE | K32.FILE_SHARE_READ, // share access\n null, // no security attributes\n K32.OPEN_EXISTING, // device already exists\n 0, // no flags or attributes\n IntPtr.Zero ); // no template file.\n\n ConsoleHandle = new SafeFileHandle( handle, true );\n\n if ( ConsoleHandle.IsInvalid ) {\n MessageBox.Show( \"Cannot create diagnostic console\",\n \"Error\",\n MessageBoxButtons.OK,\n MessageBoxIcon.Error );\n return;\n }\n\n //\n // Set the console screen buffer and window to a reasonable size\n // 1) set the screen buffer sizse\n // 2) Get the maximum window size (in terms of characters) \n // 3) set the window to be this size\n //\n const UInt16 conWidth = 256;\n const UInt16 conHeight = 5000;\n\n K32.Coord dwSize = new K32.Coord( conWidth, conHeight );\n if ( !K32.SetConsoleScreenBufferSize( ConsoleHandle.DangerousGetHandle(), dwSize ) ) {\n MessageBox.Show( \"Can't get console screen buffer information.\",\n \"Error\",\n MessageBoxButtons.OK,\n MessageBoxIcon.Error );\n return;\n }\n\n K32.Console_Screen_Buffer_Info SBInfo = new K32.Console_Screen_Buffer_Info();\n if ( !K32.GetConsoleScreenBufferInfo( ConsoleHandle.DangerousGetHandle(), out SBInfo ) ) {\n MessageBox.Show( \"Can't get console screen buffer information.\",\n \"Error\",\n MessageBoxButtons.OK,\n MessageBoxIcon.Exclamation);\n return;\n }\n\n K32.Small_Rect sr; ;\n sr.Left = 0;\n sr.Top = 0;\n sr.Right = 132 - 1;\n sr.Bottom = 51 - 1;\n\n if ( !K32.SetConsoleWindowInfo( ConsoleHandle.DangerousGetHandle(), true, ref sr ) ) {\n MessageBox.Show( \"Can't set console screen buffer information.\",\n \"Error\",\n MessageBoxButtons.OK,\n MessageBoxIcon.Error );\n return;\n }\n\n IntPtr conHWND = K32.GetConsoleWindow();\n\n if ( conHWND == IntPtr.Zero ) {\n MessageBox.Show( \"Can't get console window handle.\",\n \"Error\",\n MessageBoxButtons.OK,\n MessageBoxIcon.Error );\n return;\n }\n\n if ( !U32.SetForegroundWindow( conHWND ) ) {\n MessageBox.Show( \"Can't set console window as foreground.\",\n \"Error\",\n MessageBoxButtons.OK,\n MessageBoxIcon.Error );\n return;\n }\n\n K32.SetConsoleTitle( \"Test - Console\" );\n\n Trace.Listeners.Add( new ConsoleTraceListener() );\n }\n\n /// <summary>\n /// The main entry point for the application.\n /// </summary>\n [STAThread]\n static void Main()\n {\n InitWin32Console();\n Application.EnableVisualStyles();\n Application.SetCompatibleTextRenderingDefault( false );\n Application.Run( new Main() );\n }\n }\n}\n\n\nusing System;\nusing System.Runtime.InteropServices;\n\nnamespace MWin32Api\n{\n #region Kernel32 Functions\n\n //--------------------------------------------------------------------------\n /// <summary>\n /// Functions in Kernel32.dll\n /// </summary>\n public sealed class K32\n {\n #region Data Structures, Types and Constants\n //----------------------------------------------------------------------\n // Data Structures, Types and Constants\n // \n\n [StructLayout( LayoutKind.Sequential )]\n public class SecurityAttributes\n {\n public UInt32 nLength;\n public UIntPtr lpSecurityDescriptor;\n public bool bInheritHandle;\n }\n\n [StructLayout( LayoutKind.Sequential, Pack = 1, Size = 4 )]\n public struct Coord\n {\n public Coord( UInt16 tx, UInt16 ty )\n {\n x = tx;\n y = ty;\n }\n public UInt16 x;\n public UInt16 y;\n }\n\n [StructLayout( LayoutKind.Sequential, Pack = 1, Size = 8 )]\n public struct Small_Rect\n {\n public Int16 Left;\n public Int16 Top;\n public Int16 Right;\n public Int16 Bottom;\n\n public Small_Rect( short tLeft, short tTop, short tRight, short tBottom )\n {\n Left = tLeft;\n Top = tTop;\n Right = tRight;\n Bottom = tBottom;\n }\n }\n\n [StructLayout( LayoutKind.Sequential, Pack = 1, Size = 24 )]\n public struct Console_Screen_Buffer_Info\n {\n public Coord dwSize;\n public Coord dwCursorPosition;\n public UInt32 wAttributes;\n public Small_Rect srWindow;\n public Coord dwMaximumWindowSize;\n }\n\n\n public const int ZERO_HANDLE_VALUE = 0;\n public const int INVALID_HANDLE_VALUE = -1;\n\n #endregion\n #region Console Functions\n //----------------------------------------------------------------------\n // Console Functions\n // \n [DllImport( \"kernel32.dll\", SetLastError = true )]\n public static extern bool AllocConsole();\n\n [DllImport( \"kernel32.dll\", SetLastError = true )]\n public static extern bool SetConsoleScreenBufferSize(\n IntPtr hConsoleOutput,\n Coord dwSize );\n\n [DllImport( \"kernel32.dll\", SetLastError = true )]\n public static extern bool GetConsoleScreenBufferInfo(\n IntPtr hConsoleOutput,\n out Console_Screen_Buffer_Info lpConsoleScreenBufferInfo );\n\n [DllImport( \"kernel32.dll\", SetLastError = true )]\n public static extern bool SetConsoleWindowInfo(\n IntPtr hConsoleOutput,\n bool bAbsolute,\n ref Small_Rect lpConsoleWindow );\n\n [DllImport( \"kernel32.dll\", SetLastError = true )]\n public static extern IntPtr GetConsoleWindow();\n\n [DllImport( \"kernel32.dll\", SetLastError = true )]\n public static extern bool SetConsoleTitle(\n string Filename );\n\n #endregion\n #region Create File\n //----------------------------------------------------------------------\n // Create File\n // \n public const UInt32 CREATE_NEW = 1;\n public const UInt32 CREATE_ALWAYS = 2;\n public const UInt32 OPEN_EXISTING = 3;\n public const UInt32 OPEN_ALWAYS = 4;\n public const UInt32 TRUNCATE_EXISTING = 5;\n public const UInt32 FILE_SHARE_READ = 1;\n public const UInt32 FILE_SHARE_WRITE = 2;\n public const UInt32 GENERIC_WRITE = 0x40000000;\n public const UInt32 GENERIC_READ = 0x80000000;\n\n [DllImport( \"kernel32.dll\", SetLastError = true )]\n public static extern IntPtr CreateFile(\n string Filename,\n UInt32 DesiredAccess,\n UInt32 ShareMode,\n SecurityAttributes SecAttr,\n UInt32 CreationDisposition,\n UInt32 FlagsAndAttributes,\n IntPtr TemplateFile );\n\n #endregion\n #region Win32 Miscelaneous\n //----------------------------------------------------------------------\n // Miscelaneous\n // \n [DllImport( \"kernel32.dll\" )]\n public static extern bool CloseHandle( UIntPtr handle );\n\n #endregion\n\n //----------------------------------------------------------------------\n private K32()\n {\n }\n }\n #endregion\n\n //--------------------------------------------------------------------------\n /// <summary>\n /// Functions in User32.dll\n /// </summary>\n #region User32 Functions\n public sealed class U32\n {\n [StructLayout( LayoutKind.Sequential )]\n public struct Rect\n {\n public Int32 Left;\n public Int32 Top;\n public Int32 Right;\n public Int32 Bottom;\n\n public Rect( short tLeft, short tTop, short tRight, short tBottom )\n {\n Left = tLeft;\n Top = tTop;\n Right = tRight;\n Bottom = tBottom;\n }\n }\n\n [DllImport( \"user32.dll\" )]\n public static extern bool GetWindowRect(\n IntPtr hWnd,\n [In][MarshalAs( UnmanagedType.LPStruct )]Rect lpRect );\n\n [DllImport( \"user32.dll\", SetLastError = true )]\n public static extern bool SetForegroundWindow(\n IntPtr hWnd );\n\n //----------------------------------------------------------------------\n private U32()\n {\n }\n } // U32 class\n #endregion\n} // MWin32Api namespace\n" }, { "answer_id": 252507, "author": "dbkk", "author_id": 838, "author_profile": "https://Stackoverflow.com/users/838", "pm_score": 3, "selected": false, "text": "void AddLogMessage(String message)\n{\n list.Items.Add(message);\n\n // DO: Append message to file as needed\n\n // Clip the list\n if (list.count > ListMaxSize)\n { \n list.Items.RemoveRange(0, list.Count - listMinSize);\n }\n\n // DO: Focus the last item on the list\n}\n" }, { "answer_id": 14944970, "author": "psamwel", "author_id": 3089, "author_profile": "https://Stackoverflow.com/users/3089", "pm_score": 2, "selected": false, "text": "public class ConsoleTextBox: TextBox\n{\n private List<string> contents = new List<string>();\n private const int MAX = 50;\n\n public void WriteLine(string input)\n {\n if (contents.Count == MAX)\n contents.RemoveAt(MAX-1);\n contents.Insert(0, input);\n\n Rewrite();\n }\n\n private void Rewrite()\n {\n var sb = new StringBuilder();\n foreach (var s in contents)\n {\n sb.Append(s);\n sb.Append(Environment.NewLine);\n }\n this.Text = sb.ToString();\n }\n}\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252352", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6822/" ]
252,355
<p>After I read a bunch of LINQ related stuff, I suddenly realized that no articles introduce how to write asynchronous LINQ query. </p> <p>Suppose we use LINQ to SQL, below statement is clear. However, if the SQL database responds slowly, then the thread using this block of code would be hindered.</p> <pre><code>var result = from item in Products where item.Price &gt; 3 select item.Name; foreach (var name in result) { Console.WriteLine(name); } </code></pre> <p>Seems that current LINQ query spec doesn't provide support to this.</p> <p>Is there any way to do asynchronous programming LINQ? It works like there is a callback notification when results are ready to use without any blocking delay on I/O.</p>
[ { "answer_id": 252426, "author": "TheSoftwareJedi", "author_id": 18941, "author_profile": "https://Stackoverflow.com/users/18941", "pm_score": 6, "selected": true, "text": "public static class AsynchronousQueryExecutor\n{\n public static void Call<T>(IEnumerable<T> query, Action<IEnumerable<T>> callback, Action<Exception> errorCallback)\n {\n Func<IEnumerable<T>, IEnumerable<T>> func =\n new Func<IEnumerable<T>, IEnumerable<T>>(InnerEnumerate<T>);\n IEnumerable<T> result = null;\n IAsyncResult ar = func.BeginInvoke(\n query,\n new AsyncCallback(delegate(IAsyncResult arr)\n {\n try\n {\n result = ((Func<IEnumerable<T>, IEnumerable<T>>)((AsyncResult)arr).AsyncDelegate).EndInvoke(arr);\n }\n catch (Exception ex)\n {\n if (errorCallback != null)\n {\n errorCallback(ex);\n }\n return;\n }\n //errors from inside here are the callbacks problem\n //I think it would be confusing to report them\n callback(result);\n }),\n null);\n }\n private static IEnumerable<T> InnerEnumerate<T>(IEnumerable<T> query)\n {\n foreach (var item in query) //the method hangs here while the query executes\n {\n yield return item;\n }\n }\n}\n class Program\n{\n\n public static void Main(string[] args)\n {\n //this could be your linq query\n var qry = TestSlowLoadingEnumerable();\n\n //We begin the call and give it our callback delegate\n //and a delegate to an error handler\n AsynchronousQueryExecutor.Call(qry, HandleResults, HandleError);\n\n Console.WriteLine(\"Call began on seperate thread, execution continued\");\n Console.ReadLine();\n }\n\n public static void HandleResults(IEnumerable<int> results)\n {\n //the results are available in here\n foreach (var item in results)\n {\n Console.WriteLine(item);\n }\n }\n\n public static void HandleError(Exception ex)\n {\n Console.WriteLine(\"error\");\n }\n\n //just a sample lazy loading enumerable\n public static IEnumerable<int> TestSlowLoadingEnumerable()\n {\n Thread.Sleep(5000);\n foreach (var i in new int[] { 1, 2, 3, 4, 5, 6 })\n {\n yield return i;\n }\n }\n\n}\n" }, { "answer_id": 7085108, "author": "James Dunne", "author_id": 172557, "author_profile": "https://Stackoverflow.com/users/172557", "pm_score": 2, "selected": false, "text": "IQueryable DbCommand DataContext.GetCommand() DbCommand GetCommand() SqlCommand SqlCeCommand BeginExecuteReader EndExecuteReader BeginExecuteReader EndExecuteReader SqlCommand DbDataReader BeginExecuteReader DbDataReader IQueryable ElementType query.Take(10).Skip(0) query.Take(10).Skip(10) DbDataReader ElementType IQueryable DataContext.Translate() DbDataReader DataContext.Translate() IQueryable from x in db.Table1 select new { a = x, b = x } DbDataReader DbDataReader IQueryable Expression DbDataReader" }, { "answer_id": 38678827, "author": "Nenad", "author_id": 186822, "author_profile": "https://Stackoverflow.com/users/186822", "pm_score": 3, "selected": false, "text": "async await ExecuteAsync<T>(...) SqlCommand protected static async Task<IEnumerable<T>> ExecuteAsync<T>(IQueryable<T> query,\n DataContext ctx,\n CancellationToken token = default(CancellationToken))\n{\n var cmd = (SqlCommand)ctx.GetCommand(query);\n\n if (cmd.Connection.State == ConnectionState.Closed)\n await cmd.Connection.OpenAsync(token);\n var reader = await cmd.ExecuteReaderAsync(token);\n\n return ctx.Translate<T>(reader);\n}\n public async Task WriteNamesToConsoleAsync(string connectionString, CancellationToken token = default(CancellationToken))\n{\n using (var ctx = new DataContext(connectionString))\n {\n var query = from item in Products where item.Price > 3 select item.Name;\n var result = await ExecuteAsync(query, ctx, token);\n foreach (var name in result)\n {\n Console.WriteLine(name);\n }\n }\n}\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26349/" ]
252,365
<p>I'm trying to create a TCP connection and send/read data that uses SSL, but I haven't been able to successfully accomplish this.</p> <p>What I'd like to do is something like this:</p> <pre><code> TcpClient _tcpClient = new TcpClient("host", 110); BinaryReader reader = new BinaryReader(new System.Net.Security.SslStream(_tcpClient.GetStream(), true)); Console.WriteLine(reader.ReadString()); </code></pre> <p>I haven't had any luck with it though. An exception is thrown when creating the BinaryReader.</p> <p>Does anyone know of a simple example that does this? I'm not interested in writing the server side of this, just the client.</p>
[ { "answer_id": 252389, "author": "Ovidiu Pacurar", "author_id": 28419, "author_profile": "https://Stackoverflow.com/users/28419", "pm_score": 5, "selected": true, "text": "TcpClient _tcpClient = new TcpClient(\"host\", 110);\n\nStreamReader reader = \n new StreamReader(new System.Net.Security.SslStream(_tcpClient.GetStream(), true));\n\nConsole.WriteLine(reader.ReadToEnd());\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252365", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32226/" ]
252,371
<p>What's the easiest way to increase or decrease indentation for a large block of code in vi?</p>
[ { "answer_id": 252380, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 2, "selected": false, "text": ">% <%" }, { "answer_id": 252385, "author": "Harley Holcombe", "author_id": 1057, "author_profile": "https://Stackoverflow.com/users/1057", "pm_score": 5, "selected": true, "text": ">> 50>>" }, { "answer_id": 252449, "author": "Markus Jarderot", "author_id": 22364, "author_profile": "https://Stackoverflow.com/users/22364", "pm_score": 2, "selected": false, "text": "Ctrl-T Ctrl-D" }, { "answer_id": 11438728, "author": "kjohri", "author_id": 1518661, "author_profile": "https://Stackoverflow.com/users/1518661", "pm_score": 0, "selected": false, "text": ":m,ns/^/ /g \n :m,ns/\\t/ /g\n :m,ns/^ //g\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252371", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1693/" ]
252,391
<p>Currently I have:</p> <pre><code>&lt;system.net&gt; &lt;mailSettings&gt; &lt;smtp from="me@mydomain.com"&gt; &lt;network host="localhost" port="25" /&gt; &lt;/smtp&gt; &lt;/mailSettings&gt; &lt;/system.net&gt; </code></pre> <p>How can I change it so the email is sent with a name and not the email address only? </p>
[ { "answer_id": 252415, "author": "Ty.", "author_id": 16948, "author_profile": "https://Stackoverflow.com/users/16948", "pm_score": 7, "selected": true, "text": "new SmtpClient(...).Send(\"\\\"John Smith\\\" jsmith@somewhere.com\", ...);\n <smtp from=\"&quot;John Smith&quot; &lt;jsmith@somewhere.com&gt;\">\n" }, { "answer_id": 28046831, "author": "Aakash Dhoundiyal", "author_id": 2833709, "author_profile": "https://Stackoverflow.com/users/2833709", "pm_score": -1, "selected": false, "text": "<system.net>\n<mailSettings>\n<smtp from =\"XYZ&lt;xyz@xyz.com&gt;\">\n<network host=\"smtp.gmail.com\" port=\"25\" userName=\"xyz@xyz.com\" password=\"******\" enableSsl=\"true\"/>\n</smtp>\n</mailSettings>\n</system.net>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2385/" ]
252,411
<p>At the moment I have a console application. I would like to be able to exit the application, update through svn, recompile and then relaunch. This is running under a Linux environment. At the moment I'm not sure how I would be able to relaunch the application. Is there a way to do this?</p>
[ { "answer_id": 252415, "author": "Ty.", "author_id": 16948, "author_profile": "https://Stackoverflow.com/users/16948", "pm_score": 7, "selected": true, "text": "new SmtpClient(...).Send(\"\\\"John Smith\\\" jsmith@somewhere.com\", ...);\n <smtp from=\"&quot;John Smith&quot; &lt;jsmith@somewhere.com&gt;\">\n" }, { "answer_id": 28046831, "author": "Aakash Dhoundiyal", "author_id": 2833709, "author_profile": "https://Stackoverflow.com/users/2833709", "pm_score": -1, "selected": false, "text": "<system.net>\n<mailSettings>\n<smtp from =\"XYZ&lt;xyz@xyz.com&gt;\">\n<network host=\"smtp.gmail.com\" port=\"25\" userName=\"xyz@xyz.com\" password=\"******\" enableSsl=\"true\"/>\n</smtp>\n</mailSettings>\n</system.net>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252411", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23120/" ]
252,417
<p>What is the easiest way to use a <code>DLL</code> file from within <code>Python</code>?</p> <p>Specifically, how can this be done <em>without</em> writing any additional wrapper <code>C++</code> code to expose the functionality to <code>Python</code>?</p> <p>Native <code>Python</code> functionality is strongly preferred over using a third-party library.</p>
[ { "answer_id": 252473, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 8, "selected": true, "text": "import ctypes\n\n# Load DLL into memory.\n\nhllDll = ctypes.WinDLL (\"c:\\\\PComm\\\\ehlapi32.dll\")\n\n# Set up prototype and parameters for the desired function call.\n# HLLAPI\n\nhllApiProto = ctypes.WINFUNCTYPE (\n ctypes.c_int, # Return type.\n ctypes.c_void_p, # Parameters 1 ...\n ctypes.c_void_p,\n ctypes.c_void_p,\n ctypes.c_void_p) # ... thru 4.\nhllApiParams = (1, \"p1\", 0), (1, \"p2\", 0), (1, \"p3\",0), (1, \"p4\",0),\n\n# Actually map the call (\"HLLAPI(...)\") to a Python name.\n\nhllApi = hllApiProto ((\"HLLAPI\", hllDll), hllApiParams)\n\n# This is how you can actually call the DLL function.\n# Set up the variables and call the Python name with them.\n\np1 = ctypes.c_int (1)\np2 = ctypes.c_char_p (sessionVar)\np3 = ctypes.c_int (1)\np4 = ctypes.c_int (0)\nhllApi (ctypes.byref (p1), p2, ctypes.byref (p3), ctypes.byref (p4))\n ctypes int char short void* int int int hllApi (void *p1, void *p2, void *p3, void *p4)\n ctypes ctypes WINFUNCTYPE hllApiParams ctypes hllApi p1 p4" }, { "answer_id": 3173926, "author": "atul", "author_id": 382977, "author_profile": "https://Stackoverflow.com/users/382977", "pm_score": 6, "selected": false, "text": "add sub add(a, b) sub(a, b) from ctypes import*\n# give location of dll\nmydll = cdll.LoadLibrary(\"C:\\\\demo.dll\")\nresult1= mydll.add(10,1)\nresult2= mydll.sub(10,1)\nprint \"Addition value:\"+result1\nprint \"Substraction:\"+result2\n Addition value:11\nSubstraction:9\n" }, { "answer_id": 17157302, "author": "Carlos Gomez", "author_id": 2495062, "author_profile": "https://Stackoverflow.com/users/2495062", "pm_score": 3, "selected": false, "text": "Dispatch from win32com.client import Dispatch\n\nzk = Dispatch(\"zkemkeeper.ZKEM\") \n zk.Connect_Net(IP_address, port)\n" }, { "answer_id": 55509725, "author": "Vitality", "author_id": 1886641, "author_profile": "https://Stackoverflow.com/users/1886641", "pm_score": 4, "selected": false, "text": "shared library Python ctypes Windows DLLs shared library testDLL.cpp testDLL int #include <stdio.h>\n​\nextern \"C\" {\n​\n__declspec(dllexport)\n​\nvoid testDLL(const int i) {\n printf(\"%d\\n\", i);\n}\n​\n} // extern \"C\"\n DLL Visual Studio \"C:\\Program Files (x86)\\Microsoft Visual Studio 12.0\\Common7\\Tools\\vsdevcmd\"\n cl.exe /D_USRDLL /D_WINDLL testDLL.cpp /MT /link /DLL /OUT:testDLL.dll\n DLL DLL Visual Studio import os\nimport sys\nfrom ctypes import *\n\nlib = cdll.LoadLibrary('testDLL.dll')\n\nlib.testDLL(3)\n" }, { "answer_id": 62104617, "author": "sattva_venu", "author_id": 5605353, "author_profile": "https://Stackoverflow.com/users/5605353", "pm_score": 2, "selected": false, "text": "pip install pythonnet\n import clr\nclr.AddReference('path_to_your_dll')\n\n# import the namespace and class\n\nfrom Namespace import Class\n\n# create an object of the class\n\nobj = Class()\n\n# access functions return type using object\n\nvalue = obj.Function(<arguments>)\n\n\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252417", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6839/" ]
252,451
<p>I have a dynamic Facelets page that needs to show information from database when the page loads. At this point in the flow, there have not been any form submissions. Every JSF example I can find only shows a form submission with dynamic results on the next page.</p> <p>Every call I make to our database is currently takes place after an action has been triggered by a form submission. Where should this code go if there hasn't been a form submission, and how do I trigger it? A code snippet would really help me out!</p>
[ { "answer_id": 252943, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "public class BackingBean implements InitializingBean\n{\n public void afterPropertiesSet()\n {\n loadInitialData();\n }\n}\n faces-config.xml public void setLoaded(boolean loaded) { loadInitialData(); }" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
252,459
<p>If you have multiple, unrelated projects, is it a good idea to put them in the same repository?</p> <pre><code>myRepo/projectA/trunk myRepo/projectA/tags myRepo/projectA/branches myRepo/projectB/trunk myRepo/projectB/tags myRepo/projectB/branches </code></pre> <p>or would you create new repositories for each?</p> <pre><code>myRepoA/trunk myRepoA/tags myRepoA/branches myRepoB/trunk myRepoB/tags myRepoB/branches </code></pre> <p>What are the pros and cons of each? All that I can currently think of is that you get mixed revision numbers (so what?), and that you can't use <code>svn:externals</code> unless the repository is actually external. (i think?)</p> <p>The reason I ask is because I'm considering consolidating my multiple repos into one, since my SVN host has started charging per repo.</p>
[ { "answer_id": 252659, "author": "mlambie", "author_id": 17453, "author_profile": "https://Stackoverflow.com/users/17453", "pm_score": 3, "selected": false, "text": "/client/<clientname>/<project>/<trunk, branches, tags>\n" }, { "answer_id": 252717, "author": "Frederic Morin", "author_id": 4064, "author_profile": "https://Stackoverflow.com/users/4064", "pm_score": 3, "selected": false, "text": "$ svn-admin create /var/svn/repos1\n$ svn-admin create /var/svn/repos2\n$ svn-admin create /var/svn/repos3\n [general]\nanon-access = none # or read or write\nauth-access = write\npassword-db = /var/svn/conf/passwd\nauthz-db = /var/svn/conf/authz\nrealm = Repos1 SVN Repository\n [groups]\ngroup_repos1_read = user1, user2\ngroup_repos1_write = user3, user4\ngroup_repos2_read = user1, user4\n\n### Global Right for all repositories ###\n[/]\n### Could be a superadmin or something else ###\nuser5 = rw\n\n### Global Rights for one repository (e.g. repos1) ###\n[repos1:/]\n@group_repos1_read = r\n@group_repos1_write = rw\n\n### Repository folder specific rights (e.g. the trunk folder) ###\n[repos1:/trunk]\nuser1 = rw\n\n### And soon for the other repositories ###\n[repos2:/]\n@group_repos2_read = r\nuser3 = rw\n" }, { "answer_id": 701323, "author": "Harvey", "author_id": 47078, "author_profile": "https://Stackoverflow.com/users/47078", "pm_score": 2, "selected": false, "text": "#!/bin/bash\n\n# Usage:\n# svn-create.sh repository_name\n\n# This will:\n# - create a new repository\n# - link the necessary commit scripts\n# - setup permissions\n# - create and commit the initial directory structure\n# - clean up after itself\n\nif [ \"empty\" = ${1}\"empty\" ] ; then\n echo \"Usage:\"\n echo \" ${0} repository_name\"\n exit\nfi\n\nSVN_HOME=/svn\nSVN_ROOT=${SVN_HOME}/svnroot\nSVN_COMMON_FILES=${SVN_HOME}/repository_files\nNEW_DIR=${SVN_ROOT}/${1}\nTMP_DIR=/tmp/${1}_$$\n\necho \"Creating repository: ${1}\"\n\n# Create the repository\nsvnadmin create ${NEW_DIR}\n\n# Copy/Link the hook scripts\ncd ${NEW_DIR}\nrm -rf hooks\nln -s ${SVN_COMMON_FILES}/hooks hooks\n\n# Setup the user configuration\ncd ${NEW_DIR}\nrm -rf conf\nln -s ${SVN_COMMON_FILES}/conf conf\n\n# Checkout the newly created project\nsvn co file://${NEW_DIR} ${TMP_DIR}\n\n# Create the initial directory structure\ncd ${TMP_DIR}\nmkdir trunk\nmkdir tags\nmkdir branches\n\n# Schedule the directories addition to the repository\nsvn add trunk tags branches\n\n# Check in the changes\nsvn ci -m \"Initial Setup\"\n\n# Delete the temporary working copy\ncd /\nrm -rf ${TMP_DIR}\n\n# That's it!\necho \"Repository ${1} created. (most likely)\"\n" }, { "answer_id": 2951325, "author": "J.D.", "author_id": 82934, "author_profile": "https://Stackoverflow.com/users/82934", "pm_score": 2, "selected": false, "text": "/<src|lib>/<app-settings|afl|cs|js|iphone|sql|ts|web>/<ClientName>/<ProjectName>/<branches|tags>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252459", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9021/" ]
252,464
<p>I'm trying to send the output to the console (or colouredconsole) ... which I'm hoping would (also?) go to the Visual Studio's <code>Output</code> window for any ASP.NET web site/app/mvc app.</p> <p>It doesn't by default, but if I change the target to 'file' then it works for sure.</p> <p>Can NLog output to the <code>Output</code> window for web apps?</p>
[ { "answer_id": 260576, "author": "Scott P", "author_id": 33848, "author_profile": "https://Stackoverflow.com/users/33848", "pm_score": 8, "selected": true, "text": "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<nlog xmlns=\"http://www.nlog-project.org/schemas/NLog.xsd\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n\n <targets>\n <target name=\"debugger\" xsi:type=\"Debugger\" layout=\"${logger}::${message}\"/>\n </targets>\n\n <rules>\n <logger name=\"*\" minlevel=\"Trace\" writeTo=\"debugger\" />\n </rules>\n</nlog>\n" }, { "answer_id": 72901426, "author": "NickG", "author_id": 229587, "author_profile": "https://Stackoverflow.com/users/229587", "pm_score": 0, "selected": false, "text": "<logger name=\"*\" minlevel=\"Trace\" writeTo=\"debugger\">\n <filters defaultAction=\"Ignore\">\n <when condition=\"'${environment:ASPNETCORE_ENVIRONMENT}' == 'Development'\" action=\"Log\" />\n </filters>\n</logger>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30674/" ]
252,489
<p>Given a simple switch statement</p> <pre><code>switch (int) { case 1 : { printf("1\n"); break; } case 2 : { printf("2\n"); } case 3 : { printf("3\n"); } } </code></pre> <p>The absence of a break statement in case 2, implies that execution will continue inside the code for case 3. This is not an accident; it was designed that way. Why was this decisions made? What benefit does this provide vs. having an automatic break semantic for the blocks? What was the rationale?</p>
[ { "answer_id": 252497, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 4, "selected": false, "text": "case 0:\ncase 1:\ncase 2:\n // all do the same thing.\n break;\ncase 3:\ncase 4:\n // do something different.\n break;\ndefault:\n // something else entirely.\n" }, { "answer_id": 252500, "author": "LeopardSkinPillBoxHat", "author_id": 22489, "author_profile": "https://Stackoverflow.com/users/22489", "pm_score": 4, "selected": false, "text": "case optionA:\n // optionA needs to do its own thing, and also B's thing.\n // Fall-through to optionB afterwards.\n // Its behaviour is a superset of B's.\ncase optionB:\n // optionB needs to do its own thing\n // Its behaviour is a subset of A's.\n break;\ncase optionC:\n // optionC is quite independent so it does its own thing.\n break;\n" }, { "answer_id": 252501, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 5, "selected": false, "text": "dsend(to, from, count)\nchar *to, *from;\nint count;\n{\n int n = (count + 7) / 8;\n switch (count % 8) {\n case 0: do { *to = *from++;\n case 7: *to = *from++;\n case 6: *to = *from++;\n case 5: *to = *from++;\n case 4: *to = *from++;\n case 3: *to = *from++;\n case 2: *to = *from++;\n case 1: *to = *from++;\n } while (--n > 0);\n }\n}\n" }, { "answer_id": 252733, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 8, "selected": true, "text": "break switch (operator->num_of_operands) {\n case 2: process_operand( operator->operand_2);\n /* FALLTHRU */\n\n case 1: process_operand( operator->operand_1);\n break;\n}\n goto" }, { "answer_id": 4169724, "author": "R.. GitHub STOP HELPING ICE", "author_id": 379897, "author_profile": "https://Stackoverflow.com/users/379897", "pm_score": 3, "selected": false, "text": "switch(foo) {\ncase 1:\n /* stuff for case 1 only */\n if (0) {\ncase 2:\n /* stuff for case 2 only */\n }\n /* stuff for cases 1 and 2 */\ncase 3:\n /* stuff for cases 1, 2, and 3 */\n}\n case goto" }, { "answer_id": 51839034, "author": "Martti K", "author_id": 9126440, "author_profile": "https://Stackoverflow.com/users/9126440", "pm_score": 2, "selected": false, "text": "break switch (nShorts)\n{\ncase 4: frame.leadV1 = shortArray[3];\ncase 3: frame.leadIII = shortArray[2];\ncase 2: frame.leadII = shortArray[1];\ncase 1: frame.leadI = shortArray[0]; break;\ndefault: TS_ASSERT(false);\n}\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252489", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7734/" ]
252,493
<p>Besides the DateTime ctor (new DateTime(year, month, day)) , is there any other way to truncate a date?</p>
[ { "answer_id": 252495, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 2, "selected": false, "text": "DateTime.Now.ToShortDateString();\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252493", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1130097/" ]
252,515
<p>This is a question that's been nagging me for some time. I always thought that C++ should have been designed so that the <code>delete</code> operator (without brackets) works even with the <code>new[]</code> operator.</p> <p>In my opinion, writing this:</p> <pre><code>int* p = new int; </code></pre> <p>should be equivalent to allocating an array of 1 element:</p> <pre><code>int* p = new int[1]; </code></pre> <p>If this was true, the <code>delete</code> operator could always be deleting arrays, and we wouldn't need the <code>delete[]</code> operator.</p> <p>Is there any reason why the <code>delete[]</code> operator was introduced in C++? The only reason I can think of is that allocating arrays has a small memory footprint (you have to store the array size somewhere), so that distinguishing <code>delete</code> vs <code>delete[]</code> was a small memory optimization.</p>
[ { "answer_id": 252518, "author": "David Nehme", "author_id": 14167, "author_profile": "https://Stackoverflow.com/users/14167", "pm_score": 6, "selected": true, "text": "new delete new[] delete[] new[] delete[] new delete malloc free delete delete[]" }, { "answer_id": 252521, "author": "Ates Goral", "author_id": 23501, "author_profile": "https://Stackoverflow.com/users/23501", "pm_score": 2, "selected": false, "text": "delete [] delete" }, { "answer_id": 252623, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 3, "selected": false, "text": "for(int i=0; i<1; ++i)" }, { "answer_id": 252830, "author": "Malkocoglu", "author_id": 31152, "author_profile": "https://Stackoverflow.com/users/31152", "pm_score": 3, "selected": false, "text": "delete[] delete[cnt] delete[9] delete[cnt] [] [] [] delete[] delete delete[] delete[] delete[] delete delete delete delete new delete" }, { "answer_id": 254862, "author": "Aaron", "author_id": 14153, "author_profile": "https://Stackoverflow.com/users/14153", "pm_score": 3, "selected": false, "text": "delete[] new[] delete struct Base { virtual ~Base(); };\nstruct Derived : Base { };\nint main(){\n Base* b = new Derived;\n delete b; // this is good\n\n Base* b = new Derived[2];\n delete[] b; // bad! undefined behavior\n}\n delete ::operator delete int main(){\n int * p = new int;\n delete p; // cheap operation, no dynamic dispatch, no conditional branching\n}\n" }, { "answer_id": 20378501, "author": "David E.", "author_id": 438085, "author_profile": "https://Stackoverflow.com/users/438085", "pm_score": 1, "selected": false, "text": "delete[] ~Base Base *b struct Base { virtual ~Base(){ }>; };\nstruct Derived : Base { };\nint main(){\nBase* b = new Derived;\ndelete b; // this is good\n\n<strike>Base</strike> b = new Derived[2];\ndelete[] b; // bad! undefined behavior\n}\n david@Godel:g++ -o atest atest.cpp \ndavid@Godel: ./atest \ndavid@Godel: # No error message\n delete[] struct Base { virtual ~Base(){}; };\nstruct Derived : Base { };\n\nint main(){\n Base* b = new Derived;\n delete b; // this is good\n\n b = new Derived[2];\n delete b; // bad! undefined behavior\n}\n david@Godel:g++ -o atest atest.cpp \ndavid@Godel: ./atest \natest(30746) malloc: *** error for object 0x1099008c8: pointer being freed was n\not allocated\n*** set a breakpoint in malloc_error_break to debug\nAbort trap: 6\n delete[] b" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252515", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9936/" ]
252,517
<p>I'm using c#, and have an open tcpip connection receiving data. Is it possible to save the stream to an ms sql server database as I'm receiving it, instead of receiving all the data then saving it all? If the stream could be sent to the database as it's being received, you wouldn't have to keep the entire chunk of data in memory. Is this at all possible?</p>
[ { "answer_id": 252526, "author": "TheSoftwareJedi", "author_id": 18941, "author_profile": "https://Stackoverflow.com/users/18941", "pm_score": 3, "selected": true, "text": "update myTable set myColumn.Write(@data, @offset, @length) where someid = @someId\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252517", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9266/" ]
252,519
<p>How can I calculate the number of work days between two dates in SQL Server? </p> <p>Monday to Friday and it must be T-SQL.</p>
[ { "answer_id": 252532, "author": "Bogdan Maxim", "author_id": 23795, "author_profile": "https://Stackoverflow.com/users/23795", "pm_score": 5, "selected": false, "text": "--Changing current database to the Master database allows function to be shared by everyone.\nUSE MASTER\nGO\n--If the function already exists, drop it.\nIF EXISTS\n(\n SELECT *\n FROM dbo.SYSOBJECTS\n WHERE ID = OBJECT_ID(N'[dbo].[fn_WorkDays]')\n AND XType IN (N'FN', N'IF', N'TF')\n)\nDROP FUNCTION [dbo].[fn_WorkDays]\nGO\n CREATE FUNCTION dbo.fn_WorkDays\n--Presets\n--Define the input parameters (OK if reversed by mistake).\n(\n @StartDate DATETIME,\n @EndDate DATETIME = NULL --@EndDate replaced by @StartDate when DEFAULTed\n)\n\n--Define the output data type.\nRETURNS INT\n\nAS\n--Calculate the RETURN of the function.\nBEGIN\n --Declare local variables\n --Temporarily holds @EndDate during date reversal.\n DECLARE @Swap DATETIME\n\n --If the Start Date is null, return a NULL and exit.\n IF @StartDate IS NULL\n RETURN NULL\n\n --If the End Date is null, populate with Start Date value so will have two dates (required by DATEDIFF below).\n IF @EndDate IS NULL\n SELECT @EndDate = @StartDate\n\n --Strip the time element from both dates (just to be safe) by converting to whole days and back to a date.\n --Usually faster than CONVERT.\n --0 is a date (01/01/1900 00:00:00.000)\n SELECT @StartDate = DATEADD(dd,DATEDIFF(dd,0,@StartDate), 0),\n @EndDate = DATEADD(dd,DATEDIFF(dd,0,@EndDate) , 0)\n\n --If the inputs are in the wrong order, reverse them.\n IF @StartDate > @EndDate\n SELECT @Swap = @EndDate,\n @EndDate = @StartDate,\n @StartDate = @Swap\n\n --Calculate and return the number of workdays using the input parameters.\n --This is the meat of the function.\n --This is really just one formula with a couple of parts that are listed on separate lines for documentation purposes.\n RETURN (\n SELECT\n --Start with total number of days including weekends\n (DATEDIFF(dd,@StartDate, @EndDate)+1)\n --Subtact 2 days for each full weekend\n -(DATEDIFF(wk,@StartDate, @EndDate)*2)\n --If StartDate is a Sunday, Subtract 1\n -(CASE WHEN DATENAME(dw, @StartDate) = 'Sunday'\n THEN 1\n ELSE 0\n END)\n --If EndDate is a Saturday, Subtract 1\n -(CASE WHEN DATENAME(dw, @EndDate) = 'Saturday'\n THEN 1\n ELSE 0\n END)\n )\n END\nGO\n" }, { "answer_id": 252533, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 9, "selected": true, "text": "DECLARE @StartDate DATETIME\nDECLARE @EndDate DATETIME\nSET @StartDate = '2008/10/01'\nSET @EndDate = '2008/10/31'\n\n\nSELECT\n (DATEDIFF(dd, @StartDate, @EndDate) + 1)\n -(DATEDIFF(wk, @StartDate, @EndDate) * 2)\n -(CASE WHEN DATENAME(dw, @StartDate) = 'Sunday' THEN 1 ELSE 0 END)\n -(CASE WHEN DATENAME(dw, @EndDate) = 'Saturday' THEN 1 ELSE 0 END)\n" }, { "answer_id": 2416297, "author": "Muthuvel", "author_id": 290422, "author_profile": "https://Stackoverflow.com/users/290422", "pm_score": 3, "selected": false, "text": " DECLARE @TotalDays INT,@WorkDays INT\n DECLARE @ReducedDayswithEndDate INT\n DECLARE @WeekPart INT\n DECLARE @DatePart INT\n\n SET @TotalDays= DATEDIFF(day, @StartDate, @EndDate) +1\n SELECT @ReducedDayswithEndDate = CASE DATENAME(weekday, @EndDate)\n WHEN 'Saturday' THEN 1\n WHEN 'Sunday' THEN 2\n ELSE 0 END \n SET @TotalDays=@TotalDays-@ReducedDayswithEndDate\n SET @WeekPart=@TotalDays/7;\n SET @DatePart=@TotalDays%7;\n SET @WorkDays=(@WeekPart*5)+@DatePart\n\n RETURN @WorkDays\n" }, { "answer_id": 2416322, "author": "Muthuvel", "author_id": 290422, "author_profile": "https://Stackoverflow.com/users/290422", "pm_score": 1, "selected": false, "text": "DECLARE @StartDate datetime,@EndDate datetime\n\nselect @StartDate='3/2/2010', @EndDate='3/7/2010'\n\nDECLARE @TotalDays INT,@WorkDays INT\n\nDECLARE @ReducedDayswithEndDate INT\n\nDECLARE @WeekPart INT\n\nDECLARE @DatePart INT\n\nSET @TotalDays= DATEDIFF(day, @StartDate, @EndDate) +1\n\nSELECT @ReducedDayswithEndDate = CASE DATENAME(weekday, @EndDate)\n WHEN 'Saturday' THEN 1\n WHEN 'Sunday' THEN 2\n ELSE 0 END\n\nSET @TotalDays=@TotalDays-@ReducedDayswithEndDate\n\nSET @WeekPart=@TotalDays/7;\n\nSET @DatePart=@TotalDays%7;\n\nSET @WorkDays=(@WeekPart*5)+@DatePart\n\nSELECT @WorkDays\n" }, { "answer_id": 5109908, "author": "Carter Cole", "author_id": 180434, "author_profile": "https://Stackoverflow.com/users/180434", "pm_score": 3, "selected": false, "text": "DATEPART DATENAME(dw, @StartDate) = 'Sunday'\n SET ANSI_NULLS ON\nGO\nSET QUOTED_IDENTIFIER ON\nGO\n\nCREATE FUNCTION BDATEDIFF\n(\n @startdate as DATETIME,\n @enddate as DATETIME\n)\nRETURNS INT\nAS\nBEGIN\n DECLARE @res int\n\nSET @res = (DATEDIFF(dd, @startdate, @enddate) + 1)\n -(DATEDIFF(wk, @startdate, @enddate) * 2)\n -(CASE WHEN DATEPART(dw, @startdate) = 1 THEN 1 ELSE 0 END)\n -(CASE WHEN DATEPART(dw, @enddate) = 7 THEN 1 ELSE 0 END)\n\n RETURN @res\nEND\nGO\n" }, { "answer_id": 9124292, "author": "bel", "author_id": 1186819, "author_profile": "https://Stackoverflow.com/users/1186819", "pm_score": 1, "selected": false, "text": "CREATE FUNCTION x\n(\n @StartDate DATETIME,\n @EndDate DATETIME\n)\nRETURNS INT\nAS\nBEGIN\n DECLARE @Teller INT\n\n SET @StartDate = DATEADD(dd,1,@StartDate)\n\n SET @Teller = 0\n IF DATEDIFF(dd,@StartDate,@EndDate) <= 0\n BEGIN\n SET @Teller = 0 \n END\n ELSE\n BEGIN\n WHILE\n DATEDIFF(dd,@StartDate,@EndDate) >= 0\n BEGIN\n IF DATEPART(dw,@StartDate) < 6\n BEGIN\n SET @Teller = @Teller + 1\n END\n SET @StartDate = DATEADD(dd,1,@StartDate)\n END\n END\n RETURN @Teller\nEND\n" }, { "answer_id": 9228962, "author": "phareim", "author_id": 373975, "author_profile": "https://Stackoverflow.com/users/373975", "pm_score": 3, "selected": false, "text": "select @Result = (..CMS's answer..)\nif (@Result < 0)\n select @Result = 0\n RETURN @Result\n" }, { "answer_id": 12898069, "author": "joaopintocruz", "author_id": 1139347, "author_profile": "https://Stackoverflow.com/users/1139347", "pm_score": 3, "selected": false, "text": " CREATE TABLE [dbo].[Holiday](\n[Id] [int] IDENTITY(1,1) NOT NULL,\n[Name] [nvarchar](50) NULL,\n[Date] [datetime] NOT NULL)\n CREATE TABLE [dbo].[Plan_Phase](\n[Id] [int] IDENTITY(1,1) NOT NULL,\n[Id_Plan] [int] NOT NULL,\n[Id_Phase] [int] NOT NULL,\n[Start_Date] [datetime] NULL,\n[End_Date] [datetime] NULL,\n[Work_Days] [int] NULL)\n SELECT Start_Date, End_Date,\n (DATEDIFF(dd, Start_Date, End_Date) + 1)\n-(DATEDIFF(wk, Start_Date, End_Date) * 2)\n-(SELECT COUNT(*) From Holiday Where Date >= Start_Date AND Date <= End_Date)\n-(CASE WHEN DATENAME(dw, Start_Date) = 'Sunday' THEN 1 ELSE 0 END)\n-(CASE WHEN DATENAME(dw, End_Date) = 'Saturday' THEN 1 ELSE 0 END)\n-(CASE WHEN (SELECT COUNT(*) From Holiday Where Start_Date = Date) > 0 THEN 1 ELSE 0 END)\n-(CASE WHEN (SELECT COUNT(*) From Holiday Where End_Date = Date) > 0 THEN 1 ELSE 0 END) AS Work_Days\nfrom Plan_Phase\n" }, { "answer_id": 14653545, "author": "RobertD", "author_id": 2033691, "author_profile": "https://Stackoverflow.com/users/2033691", "pm_score": 1, "selected": false, "text": "Create FUNCTION [dbo].[fnGetBusinessDays]\n(\n @PromiseDate date,\n @ReceivedDate date\n)\nRETURNS integer\nAS\nBEGIN\n DECLARE @days integer\n\n SELECT @days = \n Case when @PromiseDate > @ReceivedDate Then\n DATEDIFF(d,@PromiseDate,@ReceivedDate) + \n ABS(DATEDIFF(wk,@PromiseDate,@ReceivedDate)) * 2 +\n CASE \n WHEN DATENAME(dw, @PromiseDate) <> 'Saturday' AND DATENAME(dw, @ReceivedDate) = 'Saturday' THEN 1 \n WHEN DATENAME(dw, @PromiseDate) = 'Saturday' AND DATENAME(dw, @ReceivedDate) <> 'Saturday' THEN -1 \n ELSE 0\n END +\n (Select COUNT(*) FROM CompanyHolidays \n WHERE HolidayDate BETWEEN @ReceivedDate AND @PromiseDate \n AND DATENAME(dw, HolidayDate) <> 'Saturday' AND DATENAME(dw, HolidayDate) <> 'Sunday')\n Else\n DATEDIFF(d,@PromiseDate,@ReceivedDate) -\n ABS(DATEDIFF(wk,@PromiseDate,@ReceivedDate)) * 2 -\n CASE \n WHEN DATENAME(dw, @PromiseDate) <> 'Saturday' AND DATENAME(dw, @ReceivedDate) = 'Saturday' THEN 1 \n WHEN DATENAME(dw, @PromiseDate) = 'Saturday' AND DATENAME(dw, @ReceivedDate) <> 'Saturday' THEN -1 \n ELSE 0\n END -\n (Select COUNT(*) FROM CompanyHolidays \n WHERE HolidayDate BETWEEN @PromiseDate and @ReceivedDate \n AND DATENAME(dw, HolidayDate) <> 'Saturday' AND DATENAME(dw, HolidayDate) <> 'Sunday')\n End\n\n\n RETURN (@days)\n\nEND\n" }, { "answer_id": 18538037, "author": "user2733766", "author_id": 2733766, "author_profile": "https://Stackoverflow.com/users/2733766", "pm_score": 2, "selected": false, "text": "DECLARE @RAWDAYS INT\n\n SELECT @RAWDAYS = DATEDIFF(day, @StartDate, @EndDate )--+1\n -( 2 * DATEDIFF( week, @StartDate, @EndDate ) )\n + CASE WHEN DATENAME(dw, @StartDate) = 'Saturday' THEN 1 ELSE 0 END\n - CASE WHEN DATENAME(dw, @EndDate) = 'Saturday' THEN 1 ELSE 0 END \n\n SELECT @RAWDAYS - COUNT(*) \n FROM HOLIDAY NumberOfBusinessDays\n WHERE [Holiday_Date] BETWEEN @StartDate+1 AND @EndDate \n" }, { "answer_id": 20149314, "author": "Danimal111", "author_id": 1197405, "author_profile": "https://Stackoverflow.com/users/1197405", "pm_score": 5, "selected": false, "text": "--Changing current database to the Master database allows function to be shared by everyone.\nUSE MASTER\nGO\n--If the function already exists, drop it.\nIF EXISTS\n(\n SELECT *\n FROM dbo.SYSOBJECTS\n WHERE ID = OBJECT_ID(N'[dbo].[fn_WorkDays]')\n AND XType IN (N'FN', N'IF', N'TF')\n)\n\nDROP FUNCTION [dbo].[fn_WorkDays]\nGO\n CREATE FUNCTION dbo.fn_WorkDays\n--Presets\n--Define the input parameters (OK if reversed by mistake).\n(\n @StartDate DATETIME,\n @EndDate DATETIME = NULL --@EndDate replaced by @StartDate when DEFAULTed\n)\n\n--Define the output data type.\nRETURNS INT\n\nAS\n--Calculate the RETURN of the function.\nBEGIN\n --Declare local variables\n --Temporarily holds @EndDate during date reversal.\n DECLARE @Swap DATETIME\n\n --If the Start Date is null, return a NULL and exit.\n IF @StartDate IS NULL\n RETURN NULL\n\n --If the End Date is null, populate with Start Date value so will have two dates (required by DATEDIFF below).\n IF @EndDate IS NULL\n SELECT @EndDate = @StartDate\n\n --Strip the time element from both dates (just to be safe) by converting to whole days and back to a date.\n --Usually faster than CONVERT.\n --0 is a date (01/01/1900 00:00:00.000)\n SELECT @StartDate = DATEADD(dd,DATEDIFF(dd,0,@StartDate), 0),\n @EndDate = DATEADD(dd,DATEDIFF(dd,0,@EndDate) , 0)\n\n --If the inputs are in the wrong order, reverse them.\n IF @StartDate > @EndDate\n SELECT @Swap = @EndDate,\n @EndDate = @StartDate,\n @StartDate = @Swap\n\n --Calculate and return the number of workdays using the input parameters.\n --This is the meat of the function.\n --This is really just one formula with a couple of parts that are listed on separate lines for documentation purposes.\n RETURN (\n SELECT\n --Start with total number of days including weekends\n (DATEDIFF(dd,@StartDate, @EndDate)+1)\n --Subtact 2 days for each full weekend\n -(DATEDIFF(wk,@StartDate, @EndDate)*2)\n --If StartDate is a Sunday, Subtract 1\n -(CASE WHEN DATENAME(dw, @StartDate) = 'Sunday'\n THEN 1\n ELSE 0\n END)\n --If EndDate is a Saturday, Subtract 1\n -(CASE WHEN DATENAME(dw, @EndDate) = 'Saturday'\n THEN 1\n ELSE 0\n END)\n --Subtract all holidays\n -(Select Count(*) from [DB04\\DB04].[Gateway].[dbo].[tblHolidays]\n where [HolDate] between @StartDate and @EndDate )\n )\n END \nGO\n-- Test Script\n/*\ndeclare @EndDate datetime= dateadd(m,2,getdate())\nprint @EndDate\nselect [Master].[dbo].[fn_WorkDays] (getdate(), @EndDate)\n*/\n" }, { "answer_id": 21098589, "author": "Mário Meyrelles", "author_id": 692083, "author_profile": "https://Stackoverflow.com/users/692083", "pm_score": 1, "selected": false, "text": "CREATE TABLE Calendar\n(\n dt SMALLDATETIME PRIMARY KEY, \n IsWorkDay BIT\n);\n\n--fill the rows with normal days, weekends and holidays.\n\n\ncreate function AddWorkingDays (@initialDate smalldatetime, @numberOfDays int)\n returns smalldatetime as \n\n begin\n declare @result smalldatetime\n set @result = \n (\n select t.dt from\n (\n select dt, ROW_NUMBER() over (order by dt) as daysAhead from calendar \n where dt > @initialDate\n and IsWorkDay = 1\n ) t\n where t.daysAhead = @numberOfDays\n )\n\n return @result\n end\n" }, { "answer_id": 22358571, "author": "Brian", "author_id": 3411807, "author_profile": "https://Stackoverflow.com/users/3411807", "pm_score": 2, "selected": false, "text": " DECLARE \n @StartDate date = '2014-01-01',\n @EndDate date = '2014-01-31'; \n SELECT \n COUNT(*) As NumberOfWeekDays\n FROM dbo.Calendar\n WHERE CalendarDate BETWEEN @StartDate AND @EndDate\n AND IsWorkDay = 1;\n DECLARE \n @StartDate datetime = '2014-01-01',\n @EndDate datetime = '2014-01-31'; \n SELECT \n SUM(CASE WHEN DATEPART(dw, DATEADD(dd, Number-1, @StartDate)) BETWEEN 2 AND 6 THEN 1 ELSE 0 END) As NumberOfWeekDays\n FROM dbo.Numbers\n WHERE Number <= DATEDIFF(dd, @StartDate, @EndDate) + 1 -- Number table starts at 1, we want a 0 base\n" }, { "answer_id": 22428919, "author": "user3424126", "author_id": 3424126, "author_profile": "https://Stackoverflow.com/users/3424126", "pm_score": 0, "selected": false, "text": "CREATE FUNCTION [dbo].[fnGetCountWorkingBusinessDays]\n(\n @StartDate as DATETIME,\n @EndDate as DATETIME\n)\nRETURNS INT\nAS\nBEGIN\n DECLARE @res int\n\nSET @StartDate = CASE \n WHEN DATENAME(dw, @StartDate) = 'Saturday' THEN DATEADD(dd, 2, DATEDIFF(dd, 0, @StartDate))\n WHEN DATENAME(dw, @StartDate) = 'Sunday' THEN DATEADD(dd, 1, DATEDIFF(dd, 0, @StartDate))\n ELSE @StartDate END\n\nSET @EndDate = CASE \n WHEN DATENAME(dw, @EndDate) = 'Saturday' THEN DATEADD(dd, 0, DATEDIFF(dd, 0, @EndDate))\n WHEN DATENAME(dw, @EndDate) = 'Sunday' THEN DATEADD(dd, -1, DATEDIFF(dd, 0, @EndDate))\n ELSE @EndDate END\n\n\nSET @res =\n (DATEDIFF(hour, @StartDate, @EndDate) / 24)\n - (DATEDIFF(wk, @StartDate, @EndDate) * 2)\n\nSET @res = CASE WHEN @res < 0 THEN 0 ELSE @res END\n\n RETURN @res\nEND\n\nGO\n" }, { "answer_id": 37956058, "author": "Igor Krupitsky", "author_id": 1781849, "author_profile": "https://Stackoverflow.com/users/1781849", "pm_score": 0, "selected": false, "text": "CREATE FUNCTION dbo.fn_WorkDays(@StartDate DATETIME, @EndDate DATETIME= NULL )\nRETURNS INT \nAS\nBEGIN\n DECLARE @Days int\n SET @Days = 0\n\n IF @EndDate = NULL\n SET @EndDate = EOMONTH(@StartDate) --last date of the month\n\n WHILE DATEDIFF(dd,@StartDate,@EndDate) >= 0\n BEGIN\n IF DATENAME(dw, @StartDate) <> 'Saturday' \n and DATENAME(dw, @StartDate) <> 'Sunday' \n and Not ((Day(@StartDate) = 1 And Month(@StartDate) = 1)) --New Year's Day.\n and Not ((Day(@StartDate) = 4 And Month(@StartDate) = 7)) --Independence Day.\n BEGIN\n SET @Days = @Days + 1\n END\n\n SET @StartDate = DATEADD(dd,1,@StartDate)\n END\n\n RETURN @Days\nEND\n select dbo.fn_WorkDays('1/1/2016', '9/25/2016')\n select dbo.fn_WorkDays(StartDate, EndDate) \nfrom table1\n" }, { "answer_id": 38065346, "author": "shawnt00", "author_id": 1322268, "author_profile": "https://Stackoverflow.com/users/1322268", "pm_score": 2, "selected": false, "text": "@@datefirst datediff(day, <start>, <end>) + 1 - datediff(week, <start>, <end>) * 2\n /* if start is a Sunday, adjust by -1 */\n + case when datepart(weekday, <start>) = 8 - @@datefirst then -1 else 0 end\n /* if end is a Saturday, adjust by -1 */\n + case when datepart(weekday, <end>) = (13 - @@datefirst) % 7 + 1 then -1 else 0 end\n datediff(week, ...) @@datefirst datediff(day, <start>, <end>) + 1 - datediff(week, <start>, <end>) * 2\n + case when datepart(weekday, dateadd(day, @@datefirst, <start>)) = 1 then -1 else 0 end\n + case when datepart(weekday, dateadd(day, @@datefirst, <end>)) = 7 then -1 else 0 end\n date +1" }, { "answer_id": 40405616, "author": "pix1985", "author_id": 1166604, "author_profile": "https://Stackoverflow.com/users/1166604", "pm_score": 0, "selected": false, "text": "Create Function dbo.DateDiff_WeekDays \n(\n@StartDate DateTime,\n@EndDate DateTime\n)\nReturns Int\nAs\n\nBegin \n\nDeclare @Result Int = 0\n\nWhile @StartDate <= @EndDate\nBegin \n If DateName(DW, @StartDate) not in ('Saturday','Sunday')\n Begin\n Set @Result = @Result +1\n End\n Set @StartDate = DateAdd(Day, +1, @StartDate)\nEnd\n\nReturn @Result\n" }, { "answer_id": 44820540, "author": "AliceF", "author_id": 3810105, "author_profile": "https://Stackoverflow.com/users/3810105", "pm_score": 3, "selected": false, "text": "CREATE FUNCTION [dbo].[fn_GetTotalWorkingDaysUsingLoop]\n(@DateFrom DATE,\n@DateTo   DATE\n)\nRETURNS INT\nAS\n     BEGIN\n         DECLARE @TotWorkingDays INT= 0;\n         WHILE @DateFrom <= @DateTo\n             BEGIN\n                 IF DATENAME(WEEKDAY, @DateFrom) IN('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday')\n                     BEGIN\n                         SET @TotWorkingDays = @TotWorkingDays + 1;\n                 END;\n                 SET @DateFrom = DATEADD(DAY, 1, @DateFrom);\n             END;\n         RETURN @TotWorkingDays;\n     END;\nGO\n" }, { "answer_id": 45841283, "author": "Baseline9", "author_id": 4657998, "author_profile": "https://Stackoverflow.com/users/4657998", "pm_score": 0, "selected": false, "text": "DATEDIFF DATEFIRST SET DATEFIRST 1\nSELECT\n,(DATEDIFF(DD, [StartDate], [EndDate])) \n-(DATEDIFF(wk, [StartDate], [EndDate])) \n-(DATEDIFF(wk, DATEADD(dd,-@@DATEFIRST,[StartDate]), DATEADD(dd,-@@DATEFIRST,[EndDate]))) AS [WorkingDays] \nFROM /*Your Table*/ \n" }, { "answer_id": 48802311, "author": "umbersar", "author_id": 364084, "author_profile": "https://Stackoverflow.com/users/364084", "pm_score": 0, "selected": false, "text": "declare @date1 as datetime = '19900101'\ndeclare @date2 as datetime = '19900120'\n\nselect sum(case when DATENAME(DW,currentDate) not in ('Saturday', 'Sunday') then 1 else 0 end) as noOfWorkDays\nfrom dbo.GetNums(0,DATEDIFF(day,@date1, @date2)-1) as Num\ncross apply (select DATEADD(day,n,@date1)) as Dates(currentDate)\n" }, { "answer_id": 51104858, "author": "Wolfgang Kais", "author_id": 6777839, "author_profile": "https://Stackoverflow.com/users/6777839", "pm_score": 1, "selected": false, "text": "DECLARE @StartDate DATETIME\nDECLARE @EndDate DATETIME\nSET @StartDate = '2018/01/01'\nSET @EndDate = '2019/01/01'\n\nSELECT DATEDIFF(Day, @StartDate, @EndDate) -- Total Days\n - (DATEDIFF(Day, 0, @EndDate)/7 - DATEDIFF(Day, 0, @StartDate)/7) -- Sundays\n - (DATEDIFF(Day, -1, @EndDate)/7 - DATEDIFF(Day, -1, @StartDate)/7) -- Saturdays\n" }, { "answer_id": 51192099, "author": "adrianm", "author_id": 157224, "author_profile": "https://Stackoverflow.com/users/157224", "pm_score": 2, "selected": false, "text": "SELECT DATEDIFF(day, @StartDate, @EndDate) /* all midnights passed */\n - DATEDIFF(week, @StartDate, @EndDate) /* remove sunday midnights */\n - DATEDIFF(week, DATEADD(day, 1, @StartDate), DATEADD(day, 1, @EndDate)) /* remove saturday midnights */\n" }, { "answer_id": 56942465, "author": "Gary", "author_id": 795047, "author_profile": "https://Stackoverflow.com/users/795047", "pm_score": 1, "selected": false, "text": "CREATE FUNCTION dbo.ufn_CalculateBusinessDays(\n@StartDate DATE,\n@EndDate DATE = NULL)\n\nRETURNS INT\nAS\n\nBEGIN\nDECLARE @TotalBusinessDays INT = 0;\nDECLARE @TestDate DATE = @StartDate;\n\n\nIF @EndDate IS NULL\n RETURN NULL;\n\nWHILE @TestDate < @EndDate\nBEGIN\n DECLARE @Month INT = DATEPART(MM, @TestDate);\n DECLARE @Day INT = DATEPART(DD, @TestDate);\n DECLARE @DayOfWeek INT = DATEPART(WEEKDAY, @TestDate) - 1; --Monday = 1, Tuesday = 2, etc.\n DECLARE @DayOccurrence INT = (@Day - 1) / 7 + 1; --Nth day of month (3rd Monday, for example)\n\n --Increment business day counter if not a weekend or holiday\n SELECT @TotalBusinessDays += (\n SELECT CASE\n --Saturday OR Sunday\n WHEN @DayOfWeek IN (6,7) THEN 0\n --New Year's Day\n WHEN @Month = 1 AND @Day = 1 THEN 0\n --MLK Jr. Day\n WHEN @Month = 1 AND @DayOfWeek = 1 AND @DayOccurrence = 3 THEN 0\n --G. Washington's Birthday\n WHEN @Month = 2 AND @DayOfWeek = 1 AND @DayOccurrence = 3 THEN 0\n --Memorial Day\n WHEN @Month = 5 AND @DayOfWeek = 1 AND @Day BETWEEN 25 AND 31 THEN 0\n --Independence Day\n WHEN @Month = 7 AND @Day = 4 THEN 0\n --Labor Day\n WHEN @Month = 9 AND @DayOfWeek = 1 AND @DayOccurrence = 1 THEN 0\n --Columbus Day\n WHEN @Month = 10 AND @DayOfWeek = 1 AND @DayOccurrence = 2 THEN 0\n --Veterans Day\n WHEN @Month = 11 AND @Day = 11 THEN 0\n --Thanksgiving\n WHEN @Month = 11 AND @DayOfWeek = 4 AND @DayOccurrence = 4 THEN 0\n --Christmas\n WHEN @Month = 12 AND @Day = 25 THEN 0\n ELSE 1\n END AS Result);\n\n SET @TestDate = DATEADD(dd, 1, @TestDate);\nEND\n\nRETURN @TotalBusinessDays;\nEND\n" }, { "answer_id": 64725325, "author": "Igor Krupitsky", "author_id": 1781849, "author_profile": "https://Stackoverflow.com/users/1781849", "pm_score": 2, "selected": false, "text": "create FUNCTION [dbo].[ShiftHolidayToWorkday](@date date)\nRETURNS date\nAS\nBEGIN\n IF DATENAME( dw, @Date ) = 'Saturday'\n SET @Date = DATEADD(day, - 1, @Date)\n\n ELSE IF DATENAME( dw, @Date ) = 'Sunday'\n SET @Date = DATEADD(day, 1, @Date)\n\n RETURN @date\nEND\nGO\n\ncreate FUNCTION [dbo].[GetHoliday](@date date)\nRETURNS varchar(50)\nAS\nBEGIN\n declare @s varchar(50)\n\n SELECT @s = CASE\n WHEN dbo.ShiftHolidayToWorkday(CONVERT(varchar, [Year] ) + '-01-01') = @date THEN 'New Year'\n WHEN dbo.ShiftHolidayToWorkday(CONVERT(varchar, [Year]+1) + '-01-01') = @date THEN 'New Year'\n WHEN dbo.ShiftHolidayToWorkday(CONVERT(varchar, [Year] ) + '-07-04') = @date THEN 'Independence Day'\n WHEN dbo.ShiftHolidayToWorkday(CONVERT(varchar, [Year] ) + '-12-25') = @date THEN 'Christmas Day'\n --WHEN dbo.ShiftHolidayToWorkday(CONVERT(varchar, [Year]) + '-12-31') = @date THEN 'New Years Eve'\n --WHEN dbo.ShiftHolidayToWorkday(CONVERT(varchar, [Year]) + '-11-11') = @date THEN 'Veteran''s Day'\n\n WHEN [Month] = 1 AND [DayOfMonth] BETWEEN 15 AND 21 AND [DayName] = 'Monday' THEN 'Martin Luther King Day'\n WHEN [Month] = 5 AND [DayOfMonth] >= 25 AND [DayName] = 'Monday' THEN 'Memorial Day'\n WHEN [Month] = 9 AND [DayOfMonth] <= 7 AND [DayName] = 'Monday' THEN 'Labor Day'\n WHEN [Month] = 11 AND [DayOfMonth] BETWEEN 22 AND 28 AND [DayName] = 'Thursday' THEN 'Thanksgiving Day'\n WHEN [Month] = 11 AND [DayOfMonth] BETWEEN 23 AND 29 AND [DayName] = 'Friday' THEN 'Day After Thanksgiving'\n ELSE NULL END\n FROM (\n SELECT\n [Year] = YEAR(@date),\n [Month] = MONTH(@date),\n [DayOfMonth] = DAY(@date),\n [DayName] = DATENAME(weekday,@date)\n ) c\n\n RETURN @s\nEND\nGO\n\ncreate FUNCTION [dbo].GetHolidays(@year int)\nRETURNS TABLE \nAS\nRETURN ( \n select dt, dbo.GetHoliday(dt) as Holiday\n from (\n select dateadd(day, number, convert(varchar,@year) + '-01-01') dt\n from master..spt_values \n where type='p' \n ) d\n where year(dt) = @year and dbo.GetHoliday(dt) is not null\n)\n\ncreate proc UpdateHolidaysTable\nas\n\nif not exists(select TABLE_NAME from INFORMATION_SCHEMA.TABLES where TABLE_NAME = 'Holidays')\n create table Holidays(dt date primary key clustered, Holiday varchar(50))\n\ndeclare @year int\nset @year = 1990\n\nwhile @year < year(GetDate()) + 20\nbegin\n insert into Holidays(dt, Holiday)\n select a.dt, a.Holiday\n from dbo.GetHolidays(@year) a\n left join Holidays b on b.dt = a.dt\n where b.dt is null\n\n set @year = @year + 1\nend\n\ncreate FUNCTION [dbo].[GetWorkDays](@StartDate DATE = NULL, @EndDate DATE = NULL)\nRETURNS INT \nAS\nBEGIN\n IF @StartDate IS NULL OR @EndDate IS NULL\n RETURN 0\n\n IF @StartDate >= @EndDate \n RETURN 0\n\n DECLARE @Days int\n SET @Days = 0\n\n IF year(@StartDate) * 100 + datepart(week, @StartDate) = year(@EndDate) * 100 + datepart(week, @EndDate) \n --same week\n select @Days = (DATEDIFF(dd, @StartDate, @EndDate))\n - (CASE WHEN DATENAME(dw, @StartDate) = 'Sunday' THEN 1 ELSE 0 END)\n - (CASE WHEN DATENAME(dw, @EndDate) = 'Saturday' THEN 1 ELSE 0 END)\n - (select count(*) from Holidays where dt between @StartDate and @EndDate)\n ELSE\n --diff weeks\n select @Days = (DATEDIFF(dd, @StartDate, @EndDate) + 1)\n - (DATEDIFF(wk, @StartDate, @EndDate) * 2)\n - (CASE WHEN DATENAME(dw, @StartDate) = 'Sunday' THEN 1 ELSE 0 END)\n - (CASE WHEN DATENAME(dw, @EndDate) = 'Saturday' THEN 1 ELSE 0 END)\n - (select count(*) from Holidays where dt between @StartDate and @EndDate)\n \n RETURN @Days\nEND\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252519", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28419/" ]
252,539
<p>I have an app where I create many uiviews and add them to the self.view of the UIViewController. My app is running really slowly. I am releasing all of my objects and have no memory leaks (I ran the performance tool). Can anyone tell me what could be making my app so slow? (code is below)</p> <p>[EDIT] The array has around 30 items. [/EndEdit]</p> <p>Thanks so much!</p> <p>Here is the code for the loadView method of my UIViewController:</p> <pre><code>- (void)loadView { UIView *contentView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]]; contentView.backgroundColor = [UIColor whiteColor]; self.view = contentView; [contentView release]; int length = 0; for(NSString *item in arrayTips) { length++; [item release]; } int index = 0; for(NSString *item in arrayTitles) { SingleFlipView *backView = [[SingleFlipView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]]; backView.userInteractionEnabled = YES; backView.backgroundColor = [UIColor whiteColor]; [backView setViewIndex:index]; [backView setLastViewIndex:length]; CGRect labelFrame = CGRectMake(10.0f, 0.0f, 300.0f, 30.0f); UILabel *backLabel = [[UILabel alloc] initWithFrame:labelFrame]; backLabel.textAlignment = UITextAlignmentCenter; backLabel.userInteractionEnabled = YES; backLabel.text = item; backLabel.font = [UIFont fontWithName:@"Georgia" size:24.0f]; backLabel.textColor = [UIColor blackColor]; backLabel.backgroundColor = [UIColor whiteColor]; CGRect textFrame = CGRectMake(10.0f, 30.0f, 300.0f, 110.0f); UITextView *tbxView = [[UITextView alloc] initWithFrame:textFrame]; tbxView.textAlignment = UITextAlignmentCenter; tbxView.userInteractionEnabled = YES; tbxView.editable = FALSE; tbxView.text = [arrayTips objectAtIndex:index]; tbxView.font = [UIFont fontWithName:@"Arial" size:14.0f]; tbxView.textColor = [UIColor blackColor]; tbxView.backgroundColor = [UIColor whiteColor]; //CGRect labelFrame = CGRectMake(10.0f, 0.0f, 84.0f, 30.0f); UIImage *nextTip = [[UIImage imageNamed:@"NextTip.png"] retain]; UIImageView *nextTipView = [ [ UIImageView alloc ] initWithImage:nextTip]; nextTipView.frame = CGRectMake(230.0f, -10.0f, 84.0f, 30.0f); nextTipView.userInteractionEnabled = YES; UIImageView *view = [[ UIImageView alloc ] init]; view.userInteractionEnabled = YES; if(self.sexString == @"Men") { UIImage *imgTip = [[UIImage imageNamed:@"feet_small.jpg"] retain]; view.image = imgTip; view.frame = CGRectMake(0.0f, 110.0f, 416.0f, 228.0f); //59*161 [imgTip release]; } [backView addSubview:view]; [backView addSubview:tbxView]; [backView addSubview:backLabel]; //[backView addSubview:nextTipView]; [self.view addSubview:backView]; [backView release]; [backLabel release]; [nextTip release]; [nextTipView release]; [tbxView release]; [view release]; index++; [item release]; } } </code></pre>
[ { "answer_id": 252566, "author": "Ben Gottlieb", "author_id": 6694, "author_profile": "https://Stackoverflow.com/users/6694", "pm_score": 2, "selected": false, "text": "[item release] item for(NSString *item in arrayTips)..." } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252539", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23695/" ]
252,548
<p>When upgrading MySQL, I first create a backup of the database. Then I will uninstall the current version installed, and delete all the files that were left by the installer. Then I install the latest GA version, and restore the created back-up, using the MySQL Administrator.</p> <p>Is there a better way of doing an upgrade of the MySQL. Because I have to create again all the users that are allowed to connect to the database.</p> <p>The installation of the MySQL is used in a college enrollment system, a client server system I have developed using VB.Net and MySQL. I can only do the update at night because i know no one is connected to the database.</p>
[ { "answer_id": 252587, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 3, "selected": true, "text": "mysql.user mysql.db select concat('show grants for ',quote(user),'@',quote(host),';') from mysql.user\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252548", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26087/" ]
252,552
<p>When should unions be used? Why do we need them?</p>
[ { "answer_id": 252561, "author": "LeopardSkinPillBoxHat", "author_id": 22489, "author_profile": "https://Stackoverflow.com/users/22489", "pm_score": 5, "selected": false, "text": "union {\n int a;\n int b;\n int c;\n} myUnion;\n" }, { "answer_id": 252568, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 8, "selected": false, "text": "union\n{\n int i;\n float f;\n} u;\n\n// Convert floating-point bits to integer:\nu.f = 3.14159f;\nprintf(\"As integer: %08x\\n\", u.i);\n enum Type { INTS, FLOATS, DOUBLE };\nstruct S\n{\n Type s_type;\n union\n {\n int s_ints[2];\n float s_floats[2];\n double s_double;\n };\n};\n\nvoid do_something(struct S *s)\n{\n switch(s->s_type)\n {\n case INTS: // do something with s->s_ints\n break;\n\n case FLOATS: // do something with s->s_floats\n break;\n\n case DOUBLE: // do something with s->s_double\n break;\n }\n}\n struct S" }, { "answer_id": 252580, "author": "Xiaofu", "author_id": 31967, "author_profile": "https://Stackoverflow.com/users/31967", "pm_score": 3, "selected": false, "text": "typedef union MyUnion MYUNION;\nunion MyUnion\n{\n int MyInt;\n float MyFloat;\n};\n MYUNION u;\nu.MyInt = 10;\n u.MyFloat = 1.0;\n" }, { "answer_id": 252725, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 4, "selected": false, "text": "set a to b times 7.\n #define #define ELEM_SYM_SET 0\n#define ELEM_SYM_TO 1\n#define ELEM_SYM_TIMES 2\n#define ELEM_SYM_FULLSTOP 3\n#define ELEM_VARIABLE 100\n#define ELEM_CONSTANT 101\n typedef struct {\n int typ;\n union {\n char *str;\n int val;\n }\n} tElem;\n tElem e;\ne.typ = ELEM_SYM_SET;\n tElem e;\ne.typ = ELEM_VARIABLE;\ne.str = strdup (\"b\"); // make sure you free this later\n tElem e;\ne.typ = ELEM_CONSTANT;\ne.val = 7;\n float flt struct ratnl {int num; int denom;} str val 0x1010 +-----------+\n0x1010 | |\n0x1011 | typ |\n0x1012 | |\n0x1013 | |\n +-----+-----+\n0x1014 | | |\n0x1015 | str | val |\n0x1016 | | |\n0x1017 | | |\n +-----+-----+\n +-------+\n0x1010 | |\n0x1011 | typ |\n0x1012 | |\n0x1013 | |\n +-------+\n0x1014 | |\n0x1015 | str |\n0x1016 | |\n0x1017 | |\n +-------+\n0x1018 | |\n0x1019 | val |\n0x101A | |\n0x101B | |\n +-------+\n" }, { "answer_id": 252778, "author": "kgiannakakis", "author_id": 24054, "author_profile": "https://Stackoverflow.com/users/24054", "pm_score": 7, "selected": false, "text": "typedef union\n{\n struct {\n unsigned char byte1;\n unsigned char byte2;\n unsigned char byte3;\n unsigned char byte4;\n } bytes;\n unsigned int dword;\n} HW_Register;\nHW_Register reg;\n reg.dword = 0x12345678;\nreg.bytes.byte3 = 4;\n typedef union\n{\n struct {\n unsigned char b1:1;\n unsigned char b2:1;\n unsigned char b3:1;\n unsigned char b4:1;\n unsigned char reserved:4;\n } bits;\n unsigned char byte;\n} HW_RegisterB;\nHW_RegisterB reg;\n x = reg.bits.b2;\n" }, { "answer_id": 7228241, "author": "sharptooth", "author_id": 57428, "author_profile": "https://Stackoverflow.com/users/57428", "pm_score": 1, "selected": false, "text": "VARIANT" }, { "answer_id": 7228278, "author": "Mu Qiao", "author_id": 665901, "author_profile": "https://Stackoverflow.com/users/665901", "pm_score": 1, "selected": false, "text": "union data {\n int data;\n struct {\n unsigned char higher;\n unsigned char lower;\n } parts;\n};\n union _Obj {\n union _Obj* _M_free_list_link;\n char _M_client_data[1]; /* The client sees this. */\n};\n" }, { "answer_id": 7228285, "author": "Mario", "author_id": 409744, "author_profile": "https://Stackoverflow.com/users/409744", "pm_score": 3, "selected": false, "text": "struct variant {\n int type;\n double number;\n char *string;\n};\n variant struct variant {\n int type;\n union {\n double number;\n char *string;\n } value;\n};\n" }, { "answer_id": 7228287, "author": "phoxis", "author_id": 702361, "author_profile": "https://Stackoverflow.com/users/702361", "pm_score": 5, "selected": false, "text": "grep union /usr/include/* union struct man elf struct _mydata {\n int which_one;\n union _data {\n int a;\n float b;\n char c;\n } foo;\n} bar;\n\nswitch (bar.which_one)\n{\n case INTEGER : /* access bar.foo.a;*/ break;\n case FLOATING : /* access bar.foo.b;*/ break;\n case CHARACTER: /* access bar.foo.c;*/ break;\n}\n" }, { "answer_id": 7228299, "author": "Zoneur", "author_id": 817831, "author_profile": "https://Stackoverflow.com/users/817831", "pm_score": 2, "selected": false, "text": "typedef union\n{\n unsigned char color[4];\n int new_color;\n} u_color;\n" }, { "answer_id": 7228308, "author": "bb-generation", "author_id": 367777, "author_profile": "https://Stackoverflow.com/users/367777", "pm_score": 5, "selected": false, "text": " Connection\n / | \\\n Network USB VirtualConnection\n struct Connection\n{\n int type;\n union\n {\n struct Network network;\n struct USB usb;\n struct Virtual virtual;\n }\n};\n" }, { "answer_id": 7228357, "author": "Snips", "author_id": 451544, "author_profile": "https://Stackoverflow.com/users/451544", "pm_score": 6, "selected": false, "text": "typedef union {\n unsigned char control_byte;\n struct {\n unsigned int nibble : 4;\n unsigned int nmi : 1;\n unsigned int enabled : 1;\n unsigned int fired : 1;\n unsigned int control : 1;\n };\n} ControlRegister;\n" }, { "answer_id": 18875939, "author": "dhein", "author_id": 2003898, "author_profile": "https://Stackoverflow.com/users/2003898", "pm_score": 0, "selected": false, "text": "uint32_t array[2] *((uint16_t*) &array[1]) union un\n{\n uint16_t array16[4];\n uint32_t array32[2];\n}\n" }, { "answer_id": 19055852, "author": "Adam Lewis", "author_id": 157744, "author_profile": "https://Stackoverflow.com/users/157744", "pm_score": 3, "selected": false, "text": "typedef union\n{\n UINT8 buffer[PACKET_SIZE]; // Where the packet size is large enough for\n // the entire set of fields (including the payload)\n\n struct\n {\n UINT8 size;\n UINT8 cmd;\n UINT8 payload[PAYLOAD_SIZE];\n UINT8 crc;\n } fields;\n\n}PACKET_T;\n\n// This should be called every time a new byte of data is ready \n// and point to the packet's buffer:\n// packet_builder(packet.buffer, new_data);\n\nvoid packet_builder(UINT8* buffer, UINT8 data)\n{\n static UINT8 received_bytes = 0;\n\n // All range checking etc removed for brevity\n\n buffer[received_bytes] = data;\n received_bytes++;\n\n // Using the struc only way adds lots of logic that relates \"byte 0\" to size\n // \"byte 1\" to cmd, etc...\n}\n\nvoid packet_handler(PACKET_T* packet)\n{\n // Process the fields in a readable manner\n if(packet->fields.size > TOO_BIG)\n {\n // handle error...\n }\n\n if(packet->fields.cmd == CMD_X)\n {\n // do stuff..\n }\n}\n" }, { "answer_id": 43527061, "author": "supercat", "author_id": 363751, "author_profile": "https://Stackoverflow.com/users/363751", "pm_score": 2, "selected": false, "text": "struct x {int x_mode; int q; float x_f};\nstruct y {int y_mode; int q; int y_l};\nstruct z {int z_mode; char name[20];};\n q struct x struct y T* U* T U U* T U T* T* U* U* T U" }, { "answer_id": 69955782, "author": "Kerim FIRAT", "author_id": 2499808, "author_profile": "https://Stackoverflow.com/users/2499808", "pm_score": 2, "selected": false, "text": "union _Union{\n int a;\n double b;\n char c;\n};\n union _Union{\nint a;\ndouble b;\nchar c;\n};\n\nint main() {\n union _Union uni;\n uni.a = 44;\n uni.b = 144.5;\n printf(\"a:%d\\n\",uni.a);\n printf(\"b:%lf\\n\",uni.b);\n return 0;\n }\n union _Union{\n char name[15];\n int id;\n};\n\n\nint main(){\n union _Union uni;\n char choice;\n printf(\"YOu can enter name or id value.\");\n printf(\"Do you want to enter the name(y or n):\");\n scanf(\"%c\",&choice);\n if(choice == 'Y' || choice == 'y'){\n printf(\"Enter name:\");\n scanf(\"%s\",uni.name);\n printf(\"\\nName:%s\",uni.name);\n }else{\n printf(\"Enter Id:\");\n scanf(\"%d\",&uni.id);\n printf(\"\\nId:%d\",uni.id);\n }\nreturn 0;\n}\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252552", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
252,559
<p>What is meant by redundant function? What is the difference between a redundant function &amp; an inline function? </p>
[ { "answer_id": 252736, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 1, "selected": false, "text": "function Foo(x) { return x * x / 2; }\nfunction Bar(x) { return Math.sqr(x) * 0.5; }\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
252,575
<p>Can we call functions using function pointer? if yes how?</p>
[ { "answer_id": 252581, "author": "Adam Liss", "author_id": 29157, "author_profile": "https://Stackoverflow.com/users/29157", "pm_score": 4, "selected": false, "text": "\n// Functions that will be executed via pointer.\nint add(int i, int j) { return i+j; }\nint subtract(int i, int j) {return i-j; }\n\n// Enum selects one of the functions\ntypedef enum {\n ADD,\n SUBTRACT\n} OP;\n\n// Calculate the sum or difference of two ints.\nint math(int i, int j, OP op)\n{\n int (*func)(int i, int j); // Function pointer.\n\n // Set the function pointer based on the specified operation.\n switch (op)\n {\n case ADD: func = add; break;\n case SUBTRACT: func = subtract; break;\n default:\n // Handle error\n }\n\n return (*func)(i, j); // Call the selected function.\n}\n\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
252,588
<p>On large files (~200+ MB), I get the 503 error when I read the stream.</p> <pre><code>ftp = (FtpWebRequest)WebRequest.Create(new Uri(address.AbsoluteUri + @"/" + file.Name)); ftp.Credentials = new NetworkCredential(username, password); ftp.Method = WebRequestMethods.Ftp.DownloadFile; response = (FtpWebResponse)ftp.GetResponse(); </code></pre> <p>Any clues on what I'm doing wrong or a better practice for larger files?</p>
[ { "answer_id": 264122, "author": "John Lemp", "author_id": 12915, "author_profile": "https://Stackoverflow.com/users/12915", "pm_score": 3, "selected": true, "text": "ftp.KeepAlive = false;\n" }, { "answer_id": 39368278, "author": "mrrrk", "author_id": 155791, "author_profile": "https://Stackoverflow.com/users/155791", "pm_score": 0, "selected": false, "text": ".EnableSsl var ftp = WebRequest.Create(uri) as FtpWebRequest;\n if (ftp != null) {\n ftp.EnableSsl = true; // <- the new bit\n ftp.Credentials = myCredentials;\n ftp.KeepAlive = false; // <- you may or may not want this\n }\n return ftp;\n System.Net.ServicePointManager.ServerCertificateValidationCallback +=\n (sender, certificate, chain, sslPolicyErrors) => true;\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252588", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4068/" ]
252,599
<p>We are developing a desktop application(visual basic 6.0).We have our own logging framework. What are good practices? When we have a web application, then we can control the level of logging. How to go about in a desktop app?</p>
[ { "answer_id": 252614, "author": "Adam Liss", "author_id": 29157, "author_profile": "https://Stackoverflow.com/users/29157", "pm_score": 3, "selected": false, "text": "syslog" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252599", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
252,611
<p>I need to be able to lock down the valid characters in a textbox, I presently have a regex which I can check each character against such as </p> <blockquote> <p>[A-Za-z]</p> </blockquote> <p>would lock down to just Alpha characters. </p> <pre><code>protected override void OnKeyPress(KeyPressEventArgs e) { if (e.KeyChar == (char)Keys.Back) { base.OnKeyPress(e); return; } if (String.IsNullOrEmpty(this._ValidCharExpression)) { base.OnKeyPress(e); } else { bool isValidChar = Regex.Match(e.KeyChar.ToString(),this._ValidCharExpression).Success; if (isValidChar) { base.OnKeyPress(e); } else { e.Handled = true; } } } </code></pre> <p>I had placed the regex code in the OnKeyPress code, but I wat to allow all special keys, such as Ctrl-V, Ctrl-C and Backspace to be allowed.</p> <p>As you can see I have the backspace key being handled. However, Ctrl-V, for example cannot see the V key because it runs once for the ctrl key but does not see any modifiers keys.</p> <p>What is the best way to handle this situation?</p>
[ { "answer_id": 304014, "author": "benPearce", "author_id": 4490, "author_profile": "https://Stackoverflow.com/users/4490", "pm_score": 0, "selected": false, "text": "protected override void OnKeyDown(KeyEventArgs e)\n {\n Keys keyCode = (Keys)e.KeyValue;\n base.OnKeyDown(e);\n if ((e.Modifiers == Keys.Control) ||\n (e.Modifiers == Keys.Control) ||\n (keyCode == Keys.Back) ||\n (keyCode == Keys.Delete))\n {\n this._handleKey = true;\n }\n else\n {\n // check if the key is valid and set the flag\n this._handleKey = Regex.Match(key.ToString(), this._ValidCharExpression).Success;\n }\n }\n\n\n\n\nprotected override void OnKeyPress(KeyPressEventArgs e)\n {\n if (this._handleKey)\n {\n base.OnKeyPress(e);\n this._handleKey = false;\n }\n else\n {\n e.Handled = true;\n }\n }\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252611", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4490/" ]
252,615
<p>I have got the following problem since the server has safe mode turned on, and directories are being created under different users:</p> <ol> <li>I upload my script to the server, it shows as belonging to 'user1'. All it is doing is making a new directory when a new user is created so it can store files in it.</li> <li>New directory is created, but it belongs to 'apache' user.</li> <li>'user1' and 'apache' are different users; and safe mode is turned on. So the php script cannot write to that newly created directory.</li> <li>Now I have a problem!</li> </ol> <p>One solution is to turn off safe mode. Also, a coworker suggested that there are settings that can be changed to ensure the directories are under the same user as the script. So I am looking to see if latter can be done.</p> <p>But I have to ask. Is there a programatical solution for my problem?</p> <p>I am leaning to a 'no', as safe mode was implemented to solve it at the php level. Also the actual problem may seem like the directory being created under a different user, so a programatic fix might just be a band-aid fix.</p>
[ { "answer_id": 252645, "author": "mlambie", "author_id": 17453, "author_profile": "https://Stackoverflow.com/users/17453", "pm_score": 0, "selected": false, "text": "php_value safe_mode = Off\n" }, { "answer_id": 252646, "author": "Luis Melgratti", "author_id": 17032, "author_profile": "https://Stackoverflow.com/users/17032", "pm_score": 3, "selected": true, "text": " function FtpMkdir($path, $newDir) {\n $path = 'mainwebsite_html/'.$path;\n $server='ftp.myserver.com'; // ftp server\n $connection = ftp_connect($server); // connection\n\n\n // login to ftp server\n $user = \"user@myserver.com\";\n $pass = \"password\";\n $result = ftp_login($connection, $user, $pass);\n\n // check if connection was made\n if ((!$connection) || (!$result)) {\n return false;\n exit();\n } else {\n ftp_chdir($connection, $path); // go to destination dir\n if(ftp_mkdir($connection, $newDir)) { // create directory\n ftp_site($connection, \"CHMOD 777 $newDir\") or die(\"FTP SITE CMD failed.\");\n return $newDir;\n } else {\n return false;\n }\n\n ftp_close($connection); // close connection\n }\n\n } \n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/131/" ]
252,624
<p>My users want data from my application in Excel. The data resides in a SQL Server database but I don't want the users to have direct access to the database, I would rather provide them a web service to get the data. What is the best way to move data from SQL Server to Excel via a web service?</p>
[ { "answer_id": 252648, "author": "Dested", "author_id": 11137, "author_profile": "https://Stackoverflow.com/users/11137", "pm_score": 2, "selected": false, "text": " public static void CreateExcelFromDataTable(string filename, DataTable dt) {\n\n DataGrid grid = new DataGrid();\n grid.HeaderStyle.Font.Bold = true;\n grid.DataSource = dt;\n grid.DataMember = dt.TableName;\n\n grid.DataBind();\n\n // render the DataGrid control to a file\n\n using (StreamWriter sw = new StreamWriter(filename)) {\n using (HtmlTextWriter hw = new HtmlTextWriter(sw)) {\n grid.RenderControl(hw);\n }\n }\n }\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252624", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
252,626
<p>I've got the following url route and i'm wanting to make sure that a segment of the route will only accept numbers. as such, i can provide some regex which checks the word.</p> <p>/page/{currentPage}</p> <p>so.. can someone give me a regex which matches when the word is a number (any int) greater than 0 (ie. 1 &lt;-> int.max).</p>
[ { "answer_id": 252634, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 3, "selected": false, "text": "/([1-9][0-9]*)/\n [0-9]+" }, { "answer_id": 252641, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 0, "selected": false, "text": "string testString = @\"/page/100\";\nstring pageNumber = Regex.Match(testString, \"/page/([1-9][0-9]*)\").Groups[1].Value;\n" }, { "answer_id": 252688, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 6, "selected": true, "text": "/^[1-9][0-9]*$/\n /([1-9][0-9]*)/ // Will match -1 and foo1bar\n#[1-9]+# // Will not match 10, same problems as the first\n[1-9] // Will only match one digit, same problems as first\n" }, { "answer_id": 252730, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 0, "selected": false, "text": "/\\b([1-9][0-9]*)$/ /\\b([1-9][0-9]{0,2})$/" }, { "answer_id": 253592, "author": "Markus Jarderot", "author_id": 22364, "author_profile": "https://Stackoverflow.com/users/22364", "pm_score": 0, "selected": false, "text": "/page/ ^(?!.*?/page/([0-9]*[^0-9/]|0*/))\n (?! )" }, { "answer_id": 253604, "author": "Axeman", "author_id": 11289, "author_profile": "https://Stackoverflow.com/users/11289", "pm_score": 1, "selected": false, "text": "/\\/page\\/(0*[1-9][0-9]*)/ or \"Perl-compatible\" /\\/page\\/(0*[1-9]\\d*)/\n - ^ $ /(^|[^0-9-])(0*[1-9][0-9]*)([^0-9]|$)/\n \\b /(?<![\\d-])(0*[1-9]\\d*)\\b/\n ^ (?<![\\d-])" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252626", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30674/" ]
252,644
<p>Here is one of my header file which consists of a union template with 4 different structures.</p> <pre><code>#define MAX 3 union family { struct name /*for taking the name and gender of original member*/ { unsigned char *namess; unsigned int gender; union family *ptr_ancestor; /*this is a pointer to his ancestors details*/ }names; struct male /*for taking the above person's 3 male ancestors details if he is male*/ { unsigned char husb_names[3][20]; unsigned char wife_names[3][20]; unsigned int wife_status[3]; }male_ancestor; struct unmarry /*for taking the above person's 3 female parental ancestors if she is female and unmarried*/ { unsigned int mar; unsigned char parental_fem[3][20]; unsigned int marit_status[3]; }fem_un; struct marry /*for taking 3 parental-in-laws details if she is female and married*/ { unsigned int mar; unsigned char in_law_fem[3][20]; unsigned int in_marit_status[3]; }fem_marr; }; extern union family original[MAX]; /*for original person*/ extern union family ancestor_male[MAX]; /*used if he is male for storing his male ancestor details*/ extern union family ancestor_female[MAX]; /*used if she is female*/ extern int x; </code></pre> <p>My aim is to get a person name and gender and store the person's any 3 male/female ancestors according to the person's gender and marital status as follows..</p> <p>I mean that <code>MAX</code> will have 3 members and each will be having 3 ancestors. These ancestors will be determined by the gender the corresponding member like the following conditions:</p> <ul> <li>if male then use <code>struct male</code></li> <li>if female unmarried use <code>struct unmarry</code></li> <li>if female married use <code>struct marry</code></li> </ul> <p><code>struct name</code> is for the member name and gender for whom we have to take ancestors and point the <code>*ptr_ancestor</code> to that corresponding ancestor array (ancestormale or ancestorfemale).</p> <p>The object in memory is a union. Ok. My program will have an array of unions, in fact. Each element of the array may be using a different structure in the union. Here we should be careful in assigning the pointer or else we may loose our older person records at run time.</p> <p>If possible please tell me how to get the details of 1st element ie. <code>original[0]</code> even after taking the <code>original[1]</code>. Here I am just getting the last element of the array, and all previous records are gone at run time. I am not using any other data structures or files.</p> <p>My environment is Turbo C on Windows.</p>
[ { "answer_id": 252667, "author": "Adam Liss", "author_id": 29157, "author_profile": "https://Stackoverflow.com/users/29157", "pm_score": 2, "selected": false, "text": "// Define an array of 20 employees, each identified either by name or ID.\nunion ID {\n char name[10]; // ID may be a name up to 10 chars...\n int serialNum; // ... or it may be a serial number.\n} employees[20];\n\n// Store some data.\nemployees[0].serialNum = 123;\nstrcpy(employees[1].name, \"Manoj\");\n struct union struct union employees[] char int name char serialNum int" }, { "answer_id": 252720, "author": "Matthew Smith", "author_id": 20889, "author_profile": "https://Stackoverflow.com/users/20889", "pm_score": 3, "selected": true, "text": "struct family {\n struct name { \n int gender;\n int married;\n blah\n } names;\n union {\n struct male { blah } male_ancestor;\n struct female_unmarried { blah } female_unmarried_ancestor;\n struct female_married { blah } female_married_ancestor;\n };\n}\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252644", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31116/" ]
252,660
<p>How can I delete the session information from my browser by using javascript? Is it possible to do?</p>
[ { "answer_id": 252675, "author": "Ady", "author_id": 31395, "author_profile": "https://Stackoverflow.com/users/31395", "pm_score": 1, "selected": false, "text": "var d = new Date();\ndocument.cookie = \"cookiename=1;expires=\" + d.toGMTString() + \";\" + \";\";\n" }, { "answer_id": 252697, "author": "andyk", "author_id": 26721, "author_profile": "https://Stackoverflow.com/users/26721", "pm_score": 1, "selected": false, "text": "var cookie_date = new Date ( ); // now\ncookie_date.setTime ( cookie_date.getTime() - 1 ); // one second before now.\n// empty cookie's value and set the expiry date to a time in the past.\ndocument.cookie = \"logged_in=;\n expires=\" + cookie_date.toGMTString();\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252660", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
252,662
<p>I need some information about localization. I am using .net 2.0 with C# 2.0 which takes care of most of the localization related issues. However, I need to manually draw the alphabets corresponding to the current culture on the screen in one particular screen.</p> <p>This would be similar to the Contacts screen in Microsoft Outlook (Address Cards view or Detailed Address Cards View under Contacts), and so it needs a the column of buttons at the right end, one for each alphabet. </p> <p>I am trying to emulate that, but I don't want to ask the user to choose the script. If the current culture is say, Chinese, I want to draw Chinese alphabets. When the user changes the culture info to English (and when he restarts the application) I want to draw English alphabets instead. Hope you understand where I am going with this query. </p> <p>I can determine the culture of the current user (Application.CurrentCulture or System.Globalization.CultureInfo.CurrentCulture will give the culture related information). I also have all the scripts to render the alphabets. However, the problem is that I don't know how to map the culture info to the name of a script. </p> <p>In other words, is there a way to determine the script name corresponding to a culture? Or is it possible to determine the range of Unicode character values corresponding to a culture? Either of them would allow me to render the alphabets on the button properly.</p> <p>Any suggestions or guidance regarding this is truly appreciated. If there is something fundamentally wrong with my approach (or with what I am trying to achieve), please point out that as well. Thanks for your time. </p> <p>PS: I know the easiest solution is to either configure the script name as part of user preferences or display a list of languages for the user to choose from (a la Contact in Outlook 2007). But I am just trying to see whether I can render the alphabets corresponding to the culture without the user having to do anything.</p>
[ { "answer_id": 265586, "author": "Serge Wautier", "author_id": 12379, "author_profile": "https://Stackoverflow.com/users/12379", "pm_score": 0, "selected": false, "text": "GetLocaleInfoW(MAKELCID(wLangId, SORT_DEFAULT), LOCALE_FONTSIGNATURE, wcBuf, MAXWCBUF);\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252662", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32990/" ]
252,665
<p>I need to get all the <em>cookies</em> stored in my browser using JavaScript. How can it be done? </p>
[ { "answer_id": 252684, "author": "Codeslayer", "author_id": 4021, "author_profile": "https://Stackoverflow.com/users/4021", "pm_score": 4, "selected": false, "text": "document.cookie" }, { "answer_id": 252727, "author": "Franci Penov", "author_id": 17028, "author_profile": "https://Stackoverflow.com/users/17028", "pm_score": 6, "selected": false, "text": "HttpOnly document.cookie name=value" }, { "answer_id": 252959, "author": "aemkei", "author_id": 28150, "author_profile": "https://Stackoverflow.com/users/28150", "pm_score": 7, "selected": false, "text": "document.cookie secret=do%20not%20tell%you;last_visit=1225445171794\n var getCookies = function(){\n var pairs = document.cookie.split(\";\");\n var cookies = {};\n for (var i=0; i<pairs.length; i++){\n var pair = pairs[i].split(\"=\");\n cookies[(pair[0]+'').trim()] = unescape(pair.slice(1).join('='));\n }\n return cookies;\n}\n var myCookies = getCookies();\nalert(myCookies.secret); // \"do not tell you\"\n" }, { "answer_id": 56052470, "author": "Prabu samvel", "author_id": 7194437, "author_profile": "https://Stackoverflow.com/users/7194437", "pm_score": 2, "selected": false, "text": "let c = document.cookie.split(\";\").reduce( (ac, cv, i) => Object.assign(ac, {[cv.split('=')[0]]: cv.split('=')[1]}), {});\n\nconsole.log(c);\n" }, { "answer_id": 56071867, "author": "Netanel R", "author_id": 7323168, "author_profile": "https://Stackoverflow.com/users/7323168", "pm_score": 2, "selected": false, "text": "export const getAllCookies = () => document.cookie.split(';').reduce((ac, str) => Object.assign(ac, {[str.split('=')[0].trim()]: str.split('=')[1]}), {});\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
252,671
<p>Has anyone ever seen the storage class <code>auto</code> explicitly used in C/C++? If so, in what situation?</p>
[ { "answer_id": 252686, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 2, "selected": false, "text": "auto auto" }, { "answer_id": 12573433, "author": "Jive Dadson", "author_id": 445296, "author_profile": "https://Stackoverflow.com/users/445296", "pm_score": 1, "selected": false, "text": "c_srgb find_in_book(const c_HVC &HVC) {\n auto b = munsell.mun_to_rgb_book.find(HVC);\n if( b != munsell.mun_to_rgb_book.end()) {\n c_srgb f = b->second;\n return f;\n } else {\n c_srgb ret;\n ret.r=ret.g=ret.b=0;\n return ret;\n }\n}\n c_srgb find_in_book(const c_HVC &HVC) {\nstd::_Tree_iterator<std::_Tree_val<std::_Tmap_traits<dj::color::c_HVC,dj::color::c_srgb,std::less<dj::color::c_HVC>,std::allocator<std::pair<const dj::color::c_HVC,dj::color::c_srgb>>,false>>> b = munsell.mun_to_rgb_book.find(HVC);\n if( b != munsell.mun_to_rgb_book.end()) {\n c_srgb f = b->second;\n return f;\n } else {\n c_srgb ret;\n ret.r=ret.g=ret.b=0;\n return ret;\n }\n}\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252671", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2079/" ]
252,689
<p>We had a performance issue with DataGridViews where the redraw was horridly slow and found the solution <a href="https://stackoverflow.com/questions/118528/horrible-redraw-performance-of-the-datagridview-on-one-of-my-two-screens">Here</a> to create a derived type and enable double buffering on the control. (Derived type is necessary since the DoubleBuffered property is protected)</p> <p>It doesn't seem like there's any drawback to having the DoubleBuffered property set to true.</p>
[ { "answer_id": 10277205, "author": "Dawid Moś", "author_id": 665695, "author_profile": "https://Stackoverflow.com/users/665695", "pm_score": 5, "selected": false, "text": "typeof(DataGridView).InvokeMember(\n \"DoubleBuffered\", \n BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.SetProperty,\n null, \n myDataGridViewObject, \n new object[] { true });\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252689", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12685/" ]
252,691
<p>I am hacking up a tagging application for emacs. I have got a tag cloud/weighted list successfully displaying on a buffer, but i am running into a snag. I need to be able to properly word-wrap the buffer, but I haven't a clue where to start.</p> <p>The font I am using is a variable width font. On top of that, each tag is going to be in a different size, depending on how many times it shows up on the buffer. Finally, the window that displays the tagcloud could be in a window that is 200 pixels wide, or the full screen width.</p> <p>I really have no idea where to start. I tried longlines mode on the tagcloud buffer, but that didn't work.</p> <p>Source code is at: <a href="http://emacswiki.org/cgi-bin/emacs/free-tagging.el" rel="nofollow noreferrer">http://emacswiki.org/cgi-bin/emacs/free-tagging.el</a></p>
[ { "answer_id": 255361, "author": "Alex Coventry", "author_id": 1941213, "author_profile": "https://Stackoverflow.com/users/1941213", "pm_score": 3, "selected": true, "text": "posn-at-point posn-at-x-y" }, { "answer_id": 256015, "author": "Matt Curtis", "author_id": 17221, "author_profile": "https://Stackoverflow.com/users/17221", "pm_score": 0, "selected": false, "text": "(fill-paragraph) (fill-region)" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11052/" ]
252,703
<p>What's the difference between the list methods <code>append()</code> and <code>extend()</code>?</p>
[ { "answer_id": 252704, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 7, "selected": false, "text": "append extend >>> a = [1, 2, 3]\n>>> a.append([4, 5, 6])\n>>> a\n[1, 2, 3, [4, 5, 6]]\n" }, { "answer_id": 252705, "author": "Harley Holcombe", "author_id": 1057, "author_profile": "https://Stackoverflow.com/users/1057", "pm_score": 9, "selected": false, "text": "append extend >>> xs = ['A', 'B']\n>>> xs\n['A', 'B']\n\n>>> xs.append(\"D\")\n>>> xs\n['A', 'B', 'D']\n\n>>> xs.append([\"E\", \"F\"])\n>>> xs\n['A', 'B', 'D', ['E', 'F']]\n\n>>> xs.insert(2, \"C\")\n>>> xs\n['A', 'B', 'C', 'D', ['E', 'F']]\n\n>>> xs.extend([\"G\", \"H\"])\n>>> xs\n['A', 'B', 'C', 'D', ['E', 'F'], 'G', 'H']\n" }, { "answer_id": 252711, "author": "kender", "author_id": 4172, "author_profile": "https://Stackoverflow.com/users/4172", "pm_score": 13, "selected": true, "text": "append >>> x = [1, 2, 3]\n>>> x.append([4, 5])\n>>> print(x)\n[1, 2, 3, [4, 5]]\n extend >>> x = [1, 2, 3]\n>>> x.extend([4, 5])\n>>> print(x)\n[1, 2, 3, 4, 5]\n" }, { "answer_id": 12045242, "author": "Erik", "author_id": 1080125, "author_profile": "https://Stackoverflow.com/users/1080125", "pm_score": 6, "selected": false, "text": "for item in iterator:\n a_list.append(item)\n a_list.extend(iterator)\n" }, { "answer_id": 16510635, "author": "kiriloff", "author_id": 1141493, "author_profile": "https://Stackoverflow.com/users/1141493", "pm_score": 5, "selected": false, "text": "extend() list2d = [[1,2,3],[4,5,6], [7], [8,9]]\n >>>\n[1, 2, 3, 4, 5, 6, 7, 8, 9]\n itertools.chain.from_iterable() def from_iterable(iterables):\n # chain.from_iterable(['ABC', 'DEF']) --> A B C D E F\n for it in iterables:\n for element in it:\n yield element\n import itertools\nlist2d = [[1,2,3],[4,5,6], [7], [8,9]]\nmerged = list(itertools.chain.from_iterable(list2d))\n extend() merged = []\nmerged.extend(itertools.chain.from_iterable(list2d))\nprint(merged)\n>>>\n[1, 2, 3, 4, 5, 6, 7, 8, 9]\n" }, { "answer_id": 16511403, "author": "Chaitanya", "author_id": 202507, "author_profile": "https://Stackoverflow.com/users/202507", "pm_score": 5, "selected": false, "text": "append(object) x = [20]\n# List passed to the append(object) method is treated as a single object.\nx.append([21, 22, 23])\n# Hence the resultant list length will be 2\nprint(x)\n--> [20, [21, 22, 23]]\n extend(list) x = [20]\n# The parameter passed to extend(list) method is treated as a list.\n# Eventually it is two lists being concatenated.\nx.extend([21, 22, 23])\n# Here the resultant list's length is 4\nprint(x)\n--> [20, 21, 22, 23]\n" }, { "answer_id": 18442908, "author": "denfromufa", "author_id": 2230844, "author_profile": "https://Stackoverflow.com/users/2230844", "pm_score": 5, "selected": false, "text": "l1=range(10)\n\nl1+[11]\n\n[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11]\n\nl2=range(10,1,-1)\n\nl1+l2\n\n[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 9, 8, 7, 6, 5, 4, 3, 2]\n += append extend += append extend" }, { "answer_id": 19707477, "author": "CodyChan", "author_id": 1528712, "author_profile": "https://Stackoverflow.com/users/1528712", "pm_score": 6, "selected": false, "text": "append() x = [1, 2, 3]\nx.append([4, 5])\nx.append('abc')\nprint(x)\n# gives you\n[1, 2, 3, [4, 5], 'abc']\n extend() x = [1, 2, 3]\nx.extend([4, 5])\nx.extend('abc')\nprint(x)\n# gives you\n[1, 2, 3, 4, 5, 'a', 'b', 'c']\n" }, { "answer_id": 24632188, "author": "skdev75", "author_id": 3138785, "author_profile": "https://Stackoverflow.com/users/3138785", "pm_score": 5, "selected": false, "text": "append extend + >>> x = [1,2,3]\n>>> x\n[1, 2, 3]\n>>> x = x + [4,5,6] # Extend\n>>> x\n[1, 2, 3, 4, 5, 6]\n>>> x = x + [[7,8]] # Append\n>>> x\n[1, 2, 3, 4, 5, 6, [7, 8]]\n" }, { "answer_id": 26397913, "author": "Shiv", "author_id": 4144205, "author_profile": "https://Stackoverflow.com/users/4144205", "pm_score": 4, "selected": false, "text": "extend list1 = [123, 456, 678]\nlist2 = [111, 222]\n append result = [123, 456, 678, [111, 222]]\n extend result = [123, 456, 678, 111, 222]\n" }, { "answer_id": 28119966, "author": "Russia Must Remove Putin", "author_id": 541136, "author_profile": "https://Stackoverflow.com/users/541136", "pm_score": 9, "selected": false, "text": "append extend append list.append my_list.append(object) \n my_list >>> my_list\n['foo', 'bar']\n>>> my_list.append('baz')\n>>> my_list\n['foo', 'bar', 'baz']\n >>> another_list = [1, 2, 3]\n>>> my_list.append(another_list)\n>>> my_list\n['foo', 'bar', 'baz', [1, 2, 3]]\n #^^^^^^^^^--- single item at the end of the list.\n extend list.extend my_list.extend(iterable)\n >>> my_list\n['foo', 'bar']\n>>> another_list = [1, 2, 3]\n>>> my_list.extend(another_list)\n>>> my_list\n['foo', 'bar', 1, 2, 3]\n >>> my_list.extend('baz')\n>>> my_list\n['foo', 'bar', 1, 2, 3, 'b', 'a', 'z']\n __add__ + __iadd__ += + += list my_list + another_list my_list += another_list my_list = my_list + another_list += append /* This over-allocates proportional to the list size, making room\n * for additional growth. The over-allocation is mild, but is\n * enough to give linear-time amortized behavior over a long\n * sequence of appends() in the presence of a poorly-performing\n * system realloc().\n def append(alist, iterable):\n for item in iterable:\n alist.append(item)\n \ndef extend(alist, iterable):\n alist.extend(iterable)\n import timeit\n\n>>> min(timeit.repeat(lambda: append([], \"abcdefghijklmnopqrstuvwxyz\")))\n2.867846965789795\n>>> min(timeit.repeat(lambda: extend([], \"abcdefghijklmnopqrstuvwxyz\")))\n0.8060121536254883\n extend append def append_one(a_list, element):\n a_list.append(element)\n\ndef extend_one(a_list, element):\n \"\"\"creating a new list is semantically the most direct\n way to create an iterable to give to extend\"\"\"\n a_list.extend([element])\n\nimport timeit\n >>> min(timeit.repeat(lambda: append_one([], 0)))\n0.2082819009956438\n>>> min(timeit.repeat(lambda: extend_one([], 0)))\n0.2397019260097295\n extend extend append append" }, { "answer_id": 37787163, "author": "The Gr8 Adakron", "author_id": 5866942, "author_profile": "https://Stackoverflow.com/users/5866942", "pm_score": 4, "selected": false, "text": ">> a = [1, 2, 3, 4]\n>> a.append(5)\n>> print(a)\n>> a = [1, 2, 3, 4, 5]\n >> a = [1, 2, 3, 4]\n>> a.append([5, 6])\n>> print(a)\n>> a = [1, 2, 3, 4, [5, 6]]\n >> a = [1, 2, 3, 4]\n>> b = [5, 6, 7, 8]\n>> a.extend(b)\n>> print(a)\n>> a = [1, 2, 3, 4, 5, 6, 7, 8]\n >> a = [1, 2, 3, 4]\n>> a.extend([5, 6])\n>> print(a)\n>> a = [1, 2, 3, 4, 5, 6]\n" }, { "answer_id": 39256397, "author": "tessie", "author_id": 2813483, "author_profile": "https://Stackoverflow.com/users/2813483", "pm_score": 2, "selected": false, "text": "extend(L) L >>> a\n[1, 2, 3]\na.extend([4]) #is eqivalent of a[len(a):] = [4]\n>>> a\n[1, 2, 3, 4]\na = [1, 2, 3]\n>>> a\n[1, 2, 3]\n>>> a[len(a):] = [4]\n>>> a\n[1, 2, 3, 4]\n" }, { "answer_id": 42171373, "author": "Crabime", "author_id": 5531783, "author_profile": "https://Stackoverflow.com/users/5531783", "pm_score": 3, "selected": false, "text": "Info extend for Info extend append extend" }, { "answer_id": 46804939, "author": "PythonProgrammi", "author_id": 6464947, "author_profile": "https://Stackoverflow.com/users/6464947", "pm_score": 6, "selected": false, "text": ">>> a = [1,2]\n>>> a.append(3)\n>>> a\n[1,2,3]\n >>> a.append([4,5])\n>>> a\n>>> [1,2,3,[4,5]]\n >>> a = [1,2]\n>>> a.extend([3])\n>>> a\n[1,2,3]\n >>> a.extend([4,5,6])\n>>> a\n[1,2,3,4,5,6]\n >>> x = [1,2]\n>>> x.append(3)\n>>> x\n[1,2,3]\n >>> x = [1,2]\n>>> x.extend([3])\n>>> x\n[1,2,3]\n >>> x = [1,2]\n>>> x.append([3,4])\n>>> x\n[1,2,[3,4]]\n >>> z = [1,2] \n>>> z.extend([3,4])\n>>> z\n[1,2,3,4]\n" }, { "answer_id": 47631056, "author": "AbstProcDo", "author_id": 7301792, "author_profile": "https://Stackoverflow.com/users/7301792", "pm_score": 3, "selected": false, "text": "l1 = ['a', 'b', 'c']\nl2 = ['d', 'e', 'f']\nl1.append(l2)\nl1\n['a', 'b', 'c', ['d', 'e', 'f']]\n l1 # Reset l1 = ['a', 'b', 'c']\nl1.extend(l2)\nl1\n['a', 'b', 'c', 'd', 'e', 'f']\n list_methods = {'Add': {'extend', 'append', 'insert'},\n 'Remove': {'pop', 'remove', 'clear'}\n 'Sort': {'reverse', 'sort'},\n 'Search': {'count', 'index'},\n 'Copy': {'copy'},\n }\n" }, { "answer_id": 48036819, "author": "kmario23", "author_id": 2956066, "author_profile": "https://Stackoverflow.com/users/2956066", "pm_score": 4, "selected": false, "text": "append extend append extend append extend list(iterable) append extend None lis = [1, 2, 3]\n\n# 'extend' is equivalent to this\nlis = lis + list(iterable)\n\n# 'append' simply appends its argument as the last element to the list\n# as long as the argument is a valid Python object\nlist.append(object)\n" }, { "answer_id": 49591233, "author": "ilias iliadis", "author_id": 2362556, "author_profile": "https://Stackoverflow.com/users/2362556", "pm_score": 0, "selected": false, "text": "append extend str append extend append extend def append_o(a_list, element):\n a_list.append(element)\n print('append:', end = ' ')\n for item in a_list:\n print(item, end = ',')\n print()\n\ndef extend_o(a_list, element):\n a_list.extend(element)\n print('extend:', end = ' ')\n for item in a_list:\n print(item, end = ',')\n print()\nappend_o(['ab'],'cd')\n\nextend_o(['ab'],'cd')\nappend_o(['ab'],['cd', 'ef'])\nextend_o(['ab'],['cd', 'ef'])\nappend_o(['ab'],['cd'])\nextend_o(['ab'],['cd'])\n append: ab,cd,\nextend: ab,c,d,\nappend: ab,['cd', 'ef'],\nextend: ab,cd,ef,\nappend: ab,['cd'],\nextend: ab,cd,\n" }, { "answer_id": 51375427, "author": "vivek", "author_id": 3257783, "author_profile": "https://Stackoverflow.com/users/3257783", "pm_score": 0, "selected": false, "text": "my_list = [1,2,3,4]\n my_list.append(5)\n Example: my_list = [1,2,3,4]\nmy_list[4, 'a']\nmy_list\n[1,2,3,4,'a']\n a = [1,2]\nb = [3]\na.append(b)\nprint (a)\n[1,2,[3]]\n a = [1,2]\nb = [3]\na.extend(b)\nprint (a)\n[1,2,3]\n a = [1]\nb = [2]\nc = [3]\na.extend(b+c)\nprint (a)\n[1,2,3]\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15055/" ]
252,729
<p>i'm trying to make the following routes .. and currently i'm going about this in a <em>really</em> long way.. ie. one route instance for EACH route.</p> <p>this is what i'm after... (assuming i'm doing a 'stackoverflow website')</p> <pre><code>/ &lt;-- root site /page/{page} &lt;-- root site, but to the page of questions. /tag/{tag}/page/{page} &lt;-- as above, but the questions are filtered by tag /question/ask &lt;-- this page :P /question/{subject} &lt;-- reading about a question </code></pre> <p>(and no.. i'm most definitely not doing a stackoverflow website :) )</p> <p>cheers!</p> <p>(gawd i find dis all so confusing at times).</p>
[ { "answer_id": 260131, "author": "Haacked", "author_id": 598, "author_profile": "https://Stackoverflow.com/users/598", "pm_score": 3, "selected": true, "text": "routes.MapRoute(\"page-tag\", \"tag/{tag}/page/{page}\", new {controller=\"question\", action=\"FilterByTag\"});\n public class QuestionController : Controller {\n public ActionResult FilterByTag(string tag, int page) {\n //...\n }\n}\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252729", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30674/" ]
252,735
<p>I have made a bunch of changes to a number of files in a project. Every commit (usually at the file level) was accompanied by a comment of what was changed. </p> <p>Is there a way to get a list from CVS of these comments on changes since the last tagged version?</p> <p>Bonus if I can do this via the eclipse CVS plugin.</p> <p><strong>UPDATE</strong>: I'd love to accept an answer here, but unfortunately none of the answers are what I am looking for. Frankly I don' think it is actually possible, which is a pity really as this could be a great way to create a change list between versions (Assuming all commits are made at a sensible granularity and contain meaningful comments).</p>
[ { "answer_id": 252801, "author": "Louis Gerbarg", "author_id": 30506, "author_profile": "https://Stackoverflow.com/users/30506", "pm_score": 3, "selected": false, "text": "cvs log -rVERSION_1_0:\n" }, { "answer_id": 254100, "author": "Alex B", "author_id": 6180, "author_profile": "https://Stackoverflow.com/users/6180", "pm_score": 3, "selected": false, "text": "cvs log cvs2cl.pl --delta dev_release_1_2_3:dev_release_1_6_8\n cvs2cl.pl --delta dev_release_1_2_3:HEAD\n" }, { "answer_id": 5271307, "author": "Nate", "author_id": 119114, "author_profile": "https://Stackoverflow.com/users/119114", "pm_score": 2, "selected": false, "text": "cvs -q log -NS -rVERSION_3_0::HEAD\n cvs -q log -NS -rVERSION_3_0::HEAD | egrep -v \"RCS file: |revision |date:|Working file:|head:|branch:|locks:|access list:|keyword substitution:|total revisions: |============|-------------\"\n" }, { "answer_id": 9982491, "author": "ag_choc", "author_id": 1308855, "author_profile": "https://Stackoverflow.com/users/1308855", "pm_score": 3, "selected": false, "text": "cvs -q log -SN -rtag1:::tag2 \n cvs -q log -SN -dfromdate<todate \n cvs -H" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252735", "https://Stackoverflow.com", "https://Stackoverflow.com/users/939/" ]
252,748
<p>How should I use array of function pointers in C?</p> <p>How can I initialize them?</p>
[ { "answer_id": 252750, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 8, "selected": false, "text": "int sum(int a, int b);\nint subtract(int a, int b);\nint mul(int a, int b);\nint div(int a, int b);\n\nint (*p[4]) (int x, int y);\n\nint main(void)\n{\n int result;\n int i, j, op;\n\n p[0] = sum; /* address of sum() */\n p[1] = subtract; /* address of subtract() */\n p[2] = mul; /* address of mul() */\n p[3] = div; /* address of div() */\n[...]\n result = (*p[op]) (i, j); // op being the index of one of the four functions\n" }, { "answer_id": 252752, "author": "Manoj Doubts", "author_id": 31116, "author_profile": "https://Stackoverflow.com/users/31116", "pm_score": 6, "selected": false, "text": "void fun1()\n{\n\n}\n\nvoid fun2()\n{\n\n}\n\nvoid fun3()\n{\n\n}\n\nvoid (*func_ptr[3])() = {fun1, fun2, fun3};\n\nmain()\n{\n int option;\n\n\n printf(\"\\nEnter function number you want\");\n printf(\"\\nYou should not enter other than 0 , 1, 2\"); /* because we have only 3 functions */\n scanf(\"%d\",&option);\n\n if((option>=0)&&(option<=2))\n { \n (*func_ptr[option])();\n }\n\n return 0;\n}\n (*func_ptr[option])(argu1);\n fun1 fun2 fun3" }, { "answer_id": 252755, "author": "Friedrich", "author_id": 15068, "author_profile": "https://Stackoverflow.com/users/15068", "pm_score": 2, "selected": false, "text": "\nstatic void\ngtk_button_class_init (GtkButtonClass *klass)\n{\n GObjectClass *gobject_class;\n GtkObjectClass *object_class;\n GtkWidgetClass *widget_class;\n GtkContainerClass *container_class;\n\n gobject_class = G_OBJECT_CLASS (klass);\n object_class = (GtkObjectClass*) klass;\n widget_class = (GtkWidgetClass*) klass;\n container_class = (GtkContainerClass*) klass;\n\n gobject_class->constructor = gtk_button_constructor;\n gobject_class->set_property = gtk_button_set_property;\n gobject_class->get_property = gtk_button_get_property;\n\n \nstruct _GtkObjectClass\n{\n GInitiallyUnownedClass parent_class;\n\n /* Non overridable class methods to set and get per class arguments */\n void (*set_arg) (GtkObject *object,\n GtkArg *arg,\n guint arg_id);\n void (*get_arg) (GtkObject *object,\n GtkArg *arg,\n guint arg_id);\n\n /* Default signal handler for the ::destroy signal, which is\n * invoked to request that references to the widget be dropped.\n * If an object class overrides destroy() in order to perform class\n * specific destruction then it must still invoke its superclass'\n * implementation of the method after it is finished with its\n * own cleanup. (See gtk_widget_real_destroy() for an example of\n * how to do this).\n */\n void (*destroy) (GtkObject *object);\n};\n struct function_table {\n char *name;\n void (*some_fun)(int arg1, double arg2);\n};\n\nvoid function1(int arg1, double arg2)....\n\n\nstruct function_table my_table [] = {\n {\"function1\", function1},\n...\n" }, { "answer_id": 10700827, "author": "Rasmi Ranjan Nayak", "author_id": 1105805, "author_profile": "https://Stackoverflow.com/users/1105805", "pm_score": 4, "selected": false, "text": "#ifndef NEW_FUN_H_\n#define NEW_FUN_H_\n\n#include <stdio.h>\n\ntypedef int speed;\nspeed fun(int x);\n\nenum fp {\n f1, f2, f3, f4, f5\n};\n\nvoid F1();\nvoid F2();\nvoid F3();\nvoid F4();\nvoid F5();\n#endif\n #include \"New_Fun.h\"\n\nspeed fun(int x)\n{\n int Vel;\n Vel = x;\n return Vel;\n}\n\nvoid F1()\n{\n printf(\"From F1\\n\");\n}\n\nvoid F2()\n{\n printf(\"From F2\\n\");\n}\n\nvoid F3()\n{\n printf(\"From F3\\n\");\n}\n\nvoid F4()\n{\n printf(\"From F4\\n\");\n}\n\nvoid F5()\n{\n printf(\"From F5\\n\");\n}\n #include <stdio.h>\n#include \"New_Fun.h\"\n\nint main()\n{\n int (*F_P)(int y);\n void (*F_A[5])() = { F1, F2, F3, F4, F5 }; // if it is int the pointer incompatible is bound to happen\n int xyz, i;\n\n printf(\"Hello Function Pointer!\\n\");\n F_P = fun;\n xyz = F_P(5);\n printf(\"The Value is %d\\n\", xyz);\n //(*F_A[5]) = { F1, F2, F3, F4, F5 };\n for (i = 0; i < 5; i++)\n {\n F_A[i]();\n }\n printf(\"\\n\\n\");\n F_A[f1]();\n F_A[f2]();\n F_A[f3]();\n F_A[f4]();\n return 0;\n}\n Function Pointer." }, { "answer_id": 23903167, "author": "M.M", "author_id": 1505939, "author_profile": "https://Stackoverflow.com/users/1505939", "pm_score": 3, "selected": false, "text": "typedef int FUNC(int, int);\n\nFUNC sum, subtract, mul, div;\nFUNC *p[4] = { sum, subtract, mul, div };\n\nint main(void)\n{\n int result;\n int i = 2, j = 3, op = 2; // 2: mul\n\n result = p[op](i, j); // = 6\n}\n\n// maybe even in another file\nint sum(int a, int b) { return a+b; }\nint subtract(int a, int b) { return a-b; }\nint mul(int a, int b) { return a*b; }\nint div(int a, int b) { return a/b; }\n" }, { "answer_id": 37553002, "author": "Jay Medina", "author_id": 5166605, "author_profile": "https://Stackoverflow.com/users/5166605", "pm_score": 0, "selected": false, "text": "#include <stdio.h>\n\nchar * func1(char *a) {\n *a = 'b';\n return a;\n}\n\nchar * func2(char *a) {\n *a = 'c';\n return a;\n}\n\nint main() {\n char a = 'a';\n /* declare array of function pointers\n * the function pointer types are char * name(char *)\n * A pointer to this type of function would be just\n * put * before name, and parenthesis around *name:\n * char * (*name)(char *)\n * An array of these pointers is the same with [x]\n */\n char * (*functions[2])(char *) = {func1, func2};\n printf(\"%c, \", a);\n /* the functions return a pointer, so I need to deference pointer\n * Thats why the * in front of the parenthesis (in case it confused you)\n */\n printf(\"%c, \", *(*functions[0])(&a)); \n printf(\"%c\\n\", *(*functions[1])(&a));\n\n a = 'a';\n /* creating 'name' for a function pointer type\n * funcp is equivalent to type char *(*funcname)(char *)\n */\n typedef char *(*funcp)(char *);\n /* Now the declaration of the array of function pointers\n * becomes easier\n */\n funcp functions2[2] = {func1, func2};\n\n printf(\"%c, \", a);\n printf(\"%c, \", *(*functions2[0])(&a));\n printf(\"%c\\n\", *(*functions2[1])(&a));\n\n return 0;\n}\n" }, { "answer_id": 38639669, "author": "nimig18", "author_id": 3398381, "author_profile": "https://Stackoverflow.com/users/3398381", "pm_score": 1, "selected": false, "text": "#include <iostream>\nusing namespace std;\n\n#define DBG_PRINT(x) do { std::printf(\"Line:%-4d\" \" %15s = %-10d\\n\", __LINE__, #x, x); } while(0);\n\nvoid F0(){ printf(\"Print F%d\\n\", 0); }\nvoid F1(){ printf(\"Print F%d\\n\", 1); }\nvoid F2(){ printf(\"Print F%d\\n\", 2); }\nvoid F3(){ printf(\"Print F%d\\n\", 3); }\nvoid F4(){ printf(\"Print F%d\\n\", 4); }\nvoid (*fArrVoid[N_FUNC])() = {F0, F1, F2, F3, F4};\n\nint Sum(int a, int b){ return(a+b); }\nint Sub(int a, int b){ return(a-b); }\nint Mul(int a, int b){ return(a*b); }\nint Div(int a, int b){ return(a/b); }\nint (*fArrArgs[4])(int a, int b) = {Sum, Sub, Mul, Div};\n\nint main(){\n for(int i = 0; i < 5; i++) (*fArrVoid[i])();\n printf(\"\\n\");\n\n DBG_PRINT((*fArrArgs[0])(3,2))\n DBG_PRINT((*fArrArgs[1])(3,2))\n DBG_PRINT((*fArrArgs[2])(3,2))\n DBG_PRINT((*fArrArgs[3])(3,2))\n\n return(0);\n}\n" }, { "answer_id": 41374829, "author": "arun kumar", "author_id": 6164885, "author_profile": "https://Stackoverflow.com/users/6164885", "pm_score": 0, "selected": false, "text": "void one( int a, int b){ printf(\" \\n[ ONE ] a = %d b = %d\",a,b);}\nvoid two( int a, int b){ printf(\" \\n[ TWO ] a = %d b = %d\",a,b);}\nvoid three( int a, int b){ printf(\"\\n [ THREE ] a = %d b = %d\",a,b);}\nvoid four( int a, int b){ printf(\" \\n[ FOUR ] a = %d b = %d\",a,b);}\nvoid five( int a, int b){ printf(\" \\n [ FIVE ] a = %d b = %d\",a,b);}\nvoid(*p[2][2])(int,int) ;\nint main()\n{\n int i,j;\n printf(\"multidimensional array with function pointers\\n\");\n\n p[0][0] = one; p[0][1] = two; p[1][0] = three; p[1][1] = four;\n for ( i = 1 ; i >=0; i--)\n for ( j = 0 ; j <2; j++)\n (*p[i][j])( (i, i*j);\n return 0;\n}\n" }, { "answer_id": 42070849, "author": "Leonardo", "author_id": 7523957, "author_profile": "https://Stackoverflow.com/users/7523957", "pm_score": 1, "selected": false, "text": "void calculation(double result[] ){ //do the calculation on result\n\n result[0] = 10+5;\n result[1] = 10 +6;\n .....\n}\n\nint main(){\n\n double result[10] = {0}; //this is the vector of the results\n\n calculation(result); //this will modify result\n}\n" }, { "answer_id": 50664636, "author": "Peter Hirt", "author_id": 9863121, "author_profile": "https://Stackoverflow.com/users/9863121", "pm_score": 2, "selected": false, "text": "//! Define:\n#define F_NUM 3\nint (*pFunctions[F_NUM])(void * arg);\n\n//! Initialise:\nint someFunction(void * arg) {\n int a= *((int*)arg);\n return a*a;\n}\n\npFunctions[0]= someFunction;\n\n//! Use:\nint someMethod(int idx, void * arg, int * result) {\n int done= 0;\n if (idx < F_NUM && pFunctions[idx] != NULL) {\n *result= pFunctions[idx](arg);\n done= 1;\n }\n return done;\n}\n\nint x= 2;\nint z= 0;\nsomeMethod(0, (void*)&x, &z);\nassert(z == 4);\n" }, { "answer_id": 66448238, "author": "Alex Hajnal", "author_id": 13481837, "author_profile": "https://Stackoverflow.com/users/13481837", "pm_score": 3, "selected": false, "text": "int func1(int arg) { return arg + 1; }\nint func2(int arg) { return arg + 2; }\nint func3(int arg) { return arg + 3; }\nint func4(int arg) { return arg + 4; }\nint func5(int arg) { return arg + 5; }\nint func6(int arg) { return arg + 6; }\nint func7(int arg) { return arg + 7; }\nint func8(int arg) { return arg + 8; }\nint func9(int arg) { return arg + 9; }\nint func10(int arg) { return arg + 10; }\n\nint (*jump_table[10])(int) = { func1, func2, func3, func4, func5, \n func6, func7, func8, func9, func10 };\n \nint main(void) {\n int index = 2;\n int argument = 42;\n int result = (*jump_table[index])(argument);\n // result is 45\n}\n int int MyClass::myStaticMethod MyClass::myInstanceMethod instance.myInstanceMethod class MyClass {\npublic:\n static int myStaticMethod(int foo) { return foo + 17; }\n int myInstanceMethod(int bar) { return bar + 17; }\n}\n\nMyClass instance;\n" }, { "answer_id": 68300143, "author": "sra js", "author_id": 15193066, "author_profile": "https://Stackoverflow.com/users/15193066", "pm_score": -1, "selected": false, "text": "#include <iostream>\nusing namespace std;\n \nint sum (int , int);\nint prod (int , int);\n \nint main()\n{\n int (*p[2])(int , int ) = {sum,prod};\n \n cout << (*p[0])(2,3) << endl;\n cout << (*p[1])(2,3) << endl;\n}\n \nint sum (int a , int b)\n{\n return a+b;\n}\n \nint prod (int a, int b)\n{\n return a*b;\n}\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
252,766
<p>How can I add line numbers to a range of lines in a file opened in Vim? Not as in <code>:set nu</code>—this just <em>displays</em> line numbers—but actually have them be prepended to each line in the file?</p>
[ { "answer_id": 252770, "author": "Jerub", "author_id": 14648, "author_profile": "https://Stackoverflow.com/users/14648", "pm_score": 5, "selected": false, "text": "cat -n cat -n :%!cat -n\n :!cat -n\n :'<,'>!cat -n\n control-v x" }, { "answer_id": 252774, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 3, "selected": false, "text": ":%!cat -n\n :%!awk '{print NR,$0}'\n fu! LineIt()\n exe \":s/^/\".line(\".\").\"/\"\nendf\n exe \"s/^/\".nr2char(line(\".\")).\"/\" \n :g/^/exe \":s/^/\".line(\".\").\"^I/\"\n :set printoptions=number:y :set printoptions=number:n set printoptions=number:y vimrc" }, { "answer_id": 252777, "author": "Martin v. Löwis", "author_id": 33006, "author_profile": "https://Stackoverflow.com/users/33006", "pm_score": 5, "selected": false, "text": "nl :%!nl\n" }, { "answer_id": 253041, "author": "Luc Hermitte", "author_id": 15934, "author_profile": "https://Stackoverflow.com/users/15934", "pm_score": 8, "selected": true, "text": ":%s/^/\\=line('.')/\n V :'<,'>s/^/\\=(line('.')-line(\"'<\")+42)/\n . :'<,'>s/^/\\=(line('.')-line(\"'<\")+42).' --> '/\n printf 0001, 0002 1, 2 :%s/^/\\=printf('%04d', line('.'))/\n :h :s |subreplace-special| |submatch()|" }, { "answer_id": 256296, "author": "Brian Carper", "author_id": 23070, "author_profile": "https://Stackoverflow.com/users/23070", "pm_score": 2, "selected": false, "text": ":s :g" }, { "answer_id": 4674574, "author": "Lance Roberts", "author_id": 13295, "author_profile": "https://Stackoverflow.com/users/13295", "pm_score": 2, "selected": false, "text": ":%s/^[0-9]*//\n NR :%!awk '{print 1000+NR*10,$0}'\n" }, { "answer_id": 52234354, "author": "kmario23", "author_id": 2956066, "author_profile": "https://Stackoverflow.com/users/2956066", "pm_score": 0, "selected": false, "text": ":%s/^/\\=line('.').' '/\n ^ %s :%s/^/\\=line('.').' '/igc\n" }, { "answer_id": 72854071, "author": "Antonio", "author_id": 6266107, "author_profile": "https://Stackoverflow.com/users/6266107", "pm_score": 0, "selected": false, "text": "CTRL-V G I 0 CTRL-V g CTRL-A" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31641/" ]
252,780
<p>I have seen many programs consisting of structures like the one below</p> <pre><code>typedef struct { int i; char k; } elem; elem user; </code></pre> <p>Why is it needed so often? Any specific reason or applicable area?</p>
[ { "answer_id": 252783, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 6, "selected": false, "text": "typedef struct struct elem\n{\n int i;\n char k;\n};\nelem user; // compile error!\nstruct elem user; // this is correct\n" }, { "answer_id": 252810, "author": "unwind", "author_id": 28169, "author_profile": "https://Stackoverflow.com/users/28169", "pm_score": 10, "selected": true, "text": "struct typedef struct {\n int x, y;\n} Point;\n\nPoint point_new(int x, int y)\n{\n Point a;\n a.x = x;\n a.y = y;\n return a;\n}\n typedef struct typedef struct Point Point;\n\nPoint * point_new(int x, int y);\n struct struct Point\n{\n int x, y;\n};\n\nPoint * point_new(int x, int y)\n{\n Point *p;\n if((p = malloc(sizeof *p)) != NULL)\n {\n p->x = x;\n p->y = y;\n }\n return p;\n}\n typedef struct" }, { "answer_id": 252867, "author": "philsquared", "author_id": 32136, "author_profile": "https://Stackoverflow.com/users/32136", "pm_score": 3, "selected": false, "text": "struct MyStruct\n{\n int i;\n};\n\n// The following is legal in C++:\nMyStruct obj;\nobj.i = 7;\n" }, { "answer_id": 254250, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 7, "selected": false, "text": "struct s\n {\n ...\n };\n s x; /* error in C */\ns *p; /* error in C */\n struct s x; /* OK */\nstruct s *p; /* OK */\n struct s s;\n struct s\n {\n ...\n };\ntypedef struct s S;\n S x;\nS *p;\n S S; // error\n typedef struct\n {\n ...\n } S;\n typedef typedef typedef" }, { "answer_id": 699528, "author": "cschol", "author_id": 2386, "author_profile": "https://Stackoverflow.com/users/2386", "pm_score": 6, "selected": false, "text": "enum EnumDef\n{\n FIRST_ITEM,\n SECOND_ITEM\n};\n\nstruct StructDef\n{\n enum EnuumDef MyEnum;\n unsigned int MyVar;\n} MyStruct;\n typedef \n{\n FIRST_ITEM,\n SECOND_ITEM\n} EnumDef;\n\ntypedef struct\n{\n EnuumDef MyEnum; /* compiler error (unknown type) */\n unsigned int MyVar;\n} StructDef;\nStrructDef MyStruct; /* compiler error (unknown type) */\n" }, { "answer_id": 2392856, "author": "doccpu", "author_id": 287771, "author_profile": "https://Stackoverflow.com/users/287771", "pm_score": -1, "selected": false, "text": "struct a\n{\n int i;\n};\n\nstruct b\n{\n struct a;\n int i;\n int j;\n};\n struct b\n{\n struct a\n {\n int i;\n };\n int i;\n int j;\n}\n typedef struct a A; //anticipated declaration for member declaration\n\ntypedef struct a //Implemented declaration\n{\n A* b; // member declaration\n}A;\n" }, { "answer_id": 4566358, "author": "Jerry Hicks", "author_id": 558731, "author_profile": "https://Stackoverflow.com/users/558731", "pm_score": 8, "selected": false, "text": "#ifndef FOO_H\n#define FOO_H 1\n\n#define FOO_DEF (0xDEADBABE)\n\nstruct bar; /* forward declaration, defined in bar.h*/\n\nstruct foo {\n struct bar *bar;\n};\n\n#endif\n FOO_DEF foo struct foo *foo;\n\nprintf(\"foo->bar = %p\", foo->bar);\n" }, { "answer_id": 18105888, "author": "Yu Hao", "author_id": 1009479, "author_profile": "https://Stackoverflow.com/users/1009479", "pm_score": 5, "selected": false, "text": "typedef vps_t a;\n struct virtual_container *a;\n typedef unsigned long myflags_t;\n" }, { "answer_id": 18173698, "author": "user1533288", "author_id": 1533288, "author_profile": "https://Stackoverflow.com/users/1533288", "pm_score": 4, "selected": false, "text": "typedef typedef struct Tag{\n...members...\n}Type;\n Type myType struct Tag myTagType struct Type myType Tag myTagType typedef Type *Type_ptr;\n Type_ptr var1, var2;\nstruct Tag *myTagType1, myTagType2;\n var1 var2 myTagType1 myTagType2 typedef struct MyWriter_t{\n MyPipe super;\n MyQueue relative;\n uint32_t flags;\n...\n}MyWriter;\n void my_writer_func(MyPipe *s)\n{\n MyWriter *self = (MyWriter *) s;\n uint32_t myFlags = self->flags;\n...\n}\n flags MyPipe (struct MyWriter_ *) s; typedef #define X char[10] or\ntypedef char Y[10]\n unsigned X x; but not\nunsigned Y y;\n volatile const" }, { "answer_id": 35103707, "author": "natersoz", "author_id": 138264, "author_profile": "https://Stackoverflow.com/users/138264", "pm_score": 1, "selected": false, "text": "struct bar;\nstruct foo;\n\nstruct foo {\n struct bar *b;\n};\n\nstruct bar {\n struct foo *f;\n};\n typedef struct foo foo_t;\ntypedef struct bar bar_t;\n" }, { "answer_id": 37758915, "author": "RichardGeerify", "author_id": 6449990, "author_profile": "https://Stackoverflow.com/users/6449990", "pm_score": 1, "selected": false, "text": "struct complex{ int real_part, img_part }COMPLEX;\n\nmain(){\n\n struct KOMPLEKS number; // number type is now a struct type\n number.real_part = 3;\n number.img_part = -1;\n printf(\"Number: %d.%d i \\n\",number.real_part, number.img_part);\n\n}\n typedef struct complex{int real_part, img_part; }COMPLEX;\n//now COMPLEX is the new name for this structure and if I want to use it without\n// a keyword like in the first example 'struct complex number'.\n\nmain(){\n\nCOMPLEX number; // number is now the same type as in the first example\nnumber.real_part = 1;\nnumber.img)part = 5;\nprintf(\"%d %d \\n\", number.real_part, number.img_part);\n\n}\n" }, { "answer_id": 49199821, "author": "Asif", "author_id": 8638742, "author_profile": "https://Stackoverflow.com/users/8638742", "pm_score": 3, "selected": false, "text": "struct point\n {\n int x, y;\n };\n point struct point\n {\n int x, y;\n } first_point, second_point;\n struct point\n {\n int x, y;\n };\nstruct point first_point, second_point;\n struct point typedef typedef typedef struct point\n {\n int x, y;\n } Points;\n\nPoints first_point, second_point;\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252780", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31116/" ]
252,782
<p>What is the purpose of the <code>strdup()</code> function in C?</p>
[ { "answer_id": 252786, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 4, "selected": false, "text": "strdup() s1 free()" }, { "answer_id": 252802, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 10, "selected": true, "text": "char *strdup(const char *src) {\n char *dst = malloc(strlen (src) + 1); // Space for length plus nul\n if (dst == NULL) return NULL; // No memory\n strcpy(dst, src); // Copy the characters\n return dst; // Return the new string\n}\n errno ENOMEM NULL errno ENOMEM malloc strdup ENOMEM strndup N2912 str C11 7.1.3 Reserved identifiers string.h C11 7.31.13 String handling <string.h> str mem wcs <string.h> if (d == NULL) return NULL; if (d == NULL) {\n errno = ENOMEM;\n return NULL;\n}\n strcpy memcpy char *strdup(const char *src) {\n size_t len = strlen(src) + 1; // String plus '\\0'\n char *dst = malloc(len); // Allocate space\n if (dst == NULL) return NULL; // No memory\n memcpy (dst, src, len); // Copy the block\n return dst; // Return the new string\n}\n" }, { "answer_id": 252977, "author": "Chris Young", "author_id": 9417, "author_profile": "https://Stackoverflow.com/users/9417", "pm_score": 6, "selected": false, "text": "strdup()" }, { "answer_id": 1809465, "author": "Patrick Schlüter", "author_id": 146377, "author_profile": "https://Stackoverflow.com/users/146377", "pm_score": 6, "selected": false, "text": "char * strdup(const char * s)\n{\n size_t len = 1+strlen(s);\n char *p = malloc(len);\n\n return p ? memcpy(p, s, len) : NULL;\n}\n strcpy() \\0 strlen()" }, { "answer_id": 17339998, "author": "Karshit", "author_id": 2527523, "author_profile": "https://Stackoverflow.com/users/2527523", "pm_score": 2, "selected": false, "text": "char *strdup (const char *s)\n{\n char *p = malloc (strlen (s) + 1); // allocate memory\n if (p != NULL)\n strcpy (p,s); // copy string\n return p; // return the memory\n}\n" }, { "answer_id": 27525141, "author": "Sujay Kumar", "author_id": 2895956, "author_profile": "https://Stackoverflow.com/users/2895956", "pm_score": 2, "selected": false, "text": "strdup strndup char *strdup(const char *str);\nchar *strndup(const char *str, size_t len);\n str free NULL errno ENOMEM len str" }, { "answer_id": 34061716, "author": "Md. Al Amin Bhuiyan", "author_id": 4636819, "author_profile": "https://Stackoverflow.com/users/4636819", "pm_score": 1, "selected": false, "text": "strcpy(ptr2, ptr1);\n while(*ptr2++ = *ptr1++);\n ptr2 = strdup(ptr1);\n ptr2 = malloc(strlen(ptr1) + 1);\nif (ptr2 != NULL) strcpy(ptr2, ptr1);\n strdup strcpy" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252782", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31116/" ]
252,785
<p>What is the difference between <code>IQueryable&lt;T&gt;</code> and <code>IEnumerable&lt;T&gt;</code>?</p> <hr> <p>See also <a href="https://stackoverflow.com/questions/2433306/whats-the-difference-between-iqueryable-and-ienumerable?rq=1">What's the difference between IQueryable and IEnumerable</a> that overlaps with this question.</p>
[ { "answer_id": 252789, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 8, "selected": false, "text": "IQueryable<T> Expression IEnumerable<T> IQueryable<T> IEnumerable<T> IQueryable<T> IEnumerable<T> IQueryable<T> IEnumerable IQueryable IObservable IQbservable IQUERYABLE<T>" }, { "answer_id": 252857, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 8, "selected": false, "text": "IQueryable<T> IEnumerable<T> IEnumerable<T> IQueryable<T> IEnumerable<T> GetEnumerator() Enumerator<T> MoveNext() IQueryable<T> IEnumerable<T> IQueryable<T> IQueryProvider.Execute() IQueryProvider.CreateQuery() IQueryable" }, { "answer_id": 23359554, "author": "Shivprasad Koirala", "author_id": 993672, "author_profile": "https://Stackoverflow.com/users/993672", "pm_score": 8, "selected": false, "text": "IQueryable IEnumerable IEnumerable IQueryable IEnumerable LINQ IEnumerable Where EmpId 2 EmpEntities ent = new EmpEntities();\nIEnumerable<Employee> emp = ent.Employees; \nIEnumerable<Employee> temp = emp.Where(x => x.Empid == 2).ToList<Employee>();\n IEnumerable EmpId 2 IEnumerable IQueryable EmpEntities ent = new EmpEntities();\nIQueryable<Employee> emp = ent.Employees;\nIQueryable<Employee> temp = emp.Where(x => x.Empid == 2).ToList<Employee>();\n IQueryable IEnumerable IEnumerable" }, { "answer_id": 25664959, "author": "Ian Ringrose", "author_id": 57159, "author_profile": "https://Stackoverflow.com/users/57159", "pm_score": 4, "selected": false, "text": "ToList() ToArray() IQueryable<T> q.Where(x.name = \"a\").ToList()\n" }, { "answer_id": 43624239, "author": "RBT", "author_id": 465053, "author_profile": "https://Stackoverflow.com/users/465053", "pm_score": 4, "selected": false, "text": "CREATE TABLE [dbo].[Employee]([PersonId] [int] NOT NULL PRIMARY KEY,[Salary] [int] NOT NULL)\n INSERT INTO [EfTest].[dbo].[Employee] ([PersonId],[Salary])VALUES(1, 20)\nINSERT INTO [EfTest].[dbo].[Employee] ([PersonId],[Salary])VALUES(2, 30)\nINSERT INTO [EfTest].[dbo].[Employee] ([PersonId],[Salary])VALUES(3, 40)\nINSERT INTO [EfTest].[dbo].[Employee] ([PersonId],[Salary])VALUES(4, 50)\nINSERT INTO [EfTest].[dbo].[Employee] ([PersonId],[Salary])VALUES(5, 60)\nGO\n using (var efContext = new EfTestEntities())\n{\n IQueryable<int> employees = from e in efContext.Employees select e.Salary;\n employees = employees.Take(2);\n\n foreach (var item in employees)\n {\n Console.WriteLine(item);\n }\n}\n SELECT TOP (2) [c].[Salary] AS [Salary] FROM [dbo].[Employee] AS [c]\n Top (2) using (var efContext = new EfTestEntities())\n{\n IEnumerable<int> employees = from e in efContext.Employees select e.Salary;\n employees = employees.Take(2);\n\n foreach (var item in employees)\n {\n Console.WriteLine(item);\n }\n}\n SELECT [Extent1].[Salary] AS [Salary] FROM [dbo].[Employee] AS [Extent1]\n" }, { "answer_id": 55631618, "author": "VikrantMore", "author_id": 4373895, "author_profile": "https://Stackoverflow.com/users/4373895", "pm_score": 4, "selected": false, "text": "IEnumerable IQueryable IQueryable IEnumerable IQueryable IEnumerable IQueryable IEnumerable IQueryable IEnumerable IEnumerable System.Collections IEnumerable IEnumerable IEnumerable IQueryable System.Linq IQueryable IQueryable IQueryable IEnumerable IQueryable" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
252,800
<p>I have the need to display a nested set structure in HTML. I am doing it with the following partial:</p> <pre><code>&lt;ul&lt;%= ' id="tree"' if depth == 0 %&gt;&gt; &lt;% items.each do |item| %&gt; &lt;li id="node_&lt;%= item.id %&gt;"&gt;&lt;a&gt;&lt;%= item.name %&gt;&lt;/a&gt; &lt;% if item.has_children? %&gt; &lt;%= render :partial =&gt; 'tree_level', :locals =&gt; {:items =&gt; item.children, :depth =&gt; depth + 1} %&gt; &lt;% end %&gt; &lt;/li&gt; &lt;% end %&gt; &lt;/ul&gt; </code></pre> <p>Is this the best place to have the code? I "feel" like there should be a <code>to_html</code> method on the object which dumps the entire tree structure for me, though this works.</p>
[ { "answer_id": 252829, "author": "Jarek", "author_id": 33013, "author_profile": "https://Stackoverflow.com/users/33013", "pm_score": 2, "selected": false, "text": "def render_node(node)\n res = \"<ul>\"\n ...\n node.items.each {|n| res << render_node(n)}\n ...\n res << \"</ul>\"\n res\nend\n <%=render_node ProjectTree.new%>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252800", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17453/" ]
252,811
<p>Does anyone know of a simple method for solving this?</p> <p>I have a table which consists of start times for events and the associated durations. I need to be able to split the event durations into thirty minute intervals. So for example if an event starts at 10:45:00 and the duration is 00:17:00 then the returned set should allocate 15 minutes to the 10:30:00 interval and 00:02:00 minutes to the 11:00:00 interval.</p> <p>I'm sure I can figure out a clumsy approach but would like something a little simpler. This must come up quite often I'd imagine but Google is being unhelpful today.</p> <p>Thanks,</p> <p>Steve</p>
[ { "answer_id": 252854, "author": "Ady", "author_id": 31395, "author_profile": "https://Stackoverflow.com/users/31395", "pm_score": 2, "selected": false, "text": "create table #interval_lookup (\n from_date datetime,\n to_date datetime\n)\n\ndeclare @time datetime\nset @time = '00:00:00'\n\nwhile @time < '2 Jan 1900'\n begin\n insert into #interval_lookup values (@time, dateadd(minute, 30, @time))\n set @time = dateadd(minute, 30, @time)\n end\n\ndeclare @search_from datetime\ndeclare @search_to datetime\n\nset @search_from = '10:45:00'\nset @search_to = dateadd(minute, 17, @search_from) \n\nselect\n from_date as interval,\n case\n when from_date <= @search_from and \n @search_from < to_date and \n from_date <= @search_to and \n @search_to < to_date \n then datediff(minute, @search_from, @search_to)\n when from_date <= @search_from and \n @search_from < to_date \n then datediff(minute, @search_from, to_date)\n when from_date <= @search_to and \n @search_to < to_date then \n datediff(minute, from_date, @search_to)\n else 30\n end as duration\nfrom\n #interval_lookup\nwhere\n to_date > @search_from\n and from_date <= @search_to\n" }, { "answer_id": 252887, "author": "Bartek Szabat", "author_id": 23774, "author_profile": "https://Stackoverflow.com/users/23774", "pm_score": 2, "selected": false, "text": "ALTER FUNCTION dbo.TVF_TimeRange_Split_To_Grid\n(\n @eventStartTime datetime\n , @eventDurationMins float\n , @intervalMins int\n)\nRETURNS @retTable table\n(\n intervalStartTime datetime\n ,intervalEndTime datetime\n ,eventDurationInIntervalMins float\n)\nAS\nBEGIN\n\n declare @eventMinuteOfDay int\n set @eventMinuteOfDay = datepart(hour,@eventStartTime)*60+datepart(minute,@eventStartTime)\n\n declare @intervalStartMinute int\n set @intervalStartMinute = @eventMinuteOfDay - @eventMinuteOfDay % @intervalMins\n\n declare @intervalStartTime datetime\n set @intervalStartTime = dateadd(minute,@intervalStartMinute,cast(floor(cast(@eventStartTime as float)) as datetime))\n\n declare @intervalEndTime datetime\n set @intervalEndTime = dateadd(minute,@intervalMins,@intervalStartTime)\n\n declare @eventDurationInIntervalMins float\n\n while (@eventDurationMins>0)\n begin\n\n set @eventDurationInIntervalMins = cast(@intervalEndTime-@eventStartTime as float)*24*60\n if @eventDurationMins<@eventDurationInIntervalMins \n set @eventDurationInIntervalMins = @eventDurationMins\n\n insert into @retTable\n select @intervalStartTime,@intervalEndTime,@eventDurationInIntervalMins\n\n set @eventDurationMins = @eventDurationMins - @eventDurationInIntervalMins\n set @eventStartTime = @intervalEndTime\n\n set @intervalStartTime = @intervalEndTime\n set @intervalEndTime = dateadd(minute,@intervalMins,@intervalEndTime)\n end\n\n RETURN \nEND\nGO\n select getdate()\nselect * from dbo.TVF_TimeRange_Split_To_Grid(getdate(),23,30)\n 2008-10-31 11:28:12.377\n\nintervalStartTime intervalEndTime eventDurationInIntervalMins\n----------------------- ----------------------- ---------------------------\n2008-10-31 11:00:00.000 2008-10-31 11:30:00.000 1,79372222222222\n2008-10-31 11:30:00.000 2008-10-31 12:00:00.000 21,2062777777778\n select input.eventName, result.* from\n(\n select \n 'first' as eventName\n ,cast('2008-10-03 10:45' as datetime) as startTime\n ,17 as durationMins\n union all\n select \n 'second' as eventName\n ,cast('2008-10-05 11:00' as datetime) as startTime\n ,17 as durationMins\n union all\n select \n 'third' as eventName\n ,cast('2008-10-05 12:00' as datetime) as startTime\n ,100 as durationMins\n) input\ncross apply dbo.TVF_TimeRange_Split_To_Grid(input.startTime,input.durationMins,30) result\n eventName intervalStartTime intervalEndTime eventDurationInIntervalMins\n--------- ----------------------- ----------------------- ---------------------------\nfirst 2008-10-03 10:30:00.000 2008-10-03 11:00:00.000 15\nfirst 2008-10-03 11:00:00.000 2008-10-03 11:30:00.000 2\nsecond 2008-10-05 11:00:00.000 2008-10-05 11:30:00.000 17\nthird 2008-10-05 12:00:00.000 2008-10-05 12:30:00.000 30\nthird 2008-10-05 12:30:00.000 2008-10-05 13:00:00.000 30\nthird 2008-10-05 13:00:00.000 2008-10-05 13:30:00.000 30\nthird 2008-10-05 13:30:00.000 2008-10-05 14:00:00.000 10\n\n(7 row(s) affected)\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252811", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
252,817
<p>Just out of curiosity:</p> <p>I know I can tell the compiler if I want a value to be interpreted as a certain numeric type, e.g. as Integer (32 bit signed), this way appending an "I" (type character) to the constant value:</p> <pre><code>Private Function GetTheAnswerAsInteger() As Integer Return 42I End Function </code></pre> <p>There's also "S" for Short, "D" for Decimal, etc.</p> <p>But what is the <strong>suffix for Byte</strong>? Hint: it's not the obvious one "B"...</p>
[ { "answer_id": 20710408, "author": "Yuriy Galanter", "author_id": 961695, "author_profile": "https://Stackoverflow.com/users/961695", "pm_score": 3, "selected": false, "text": "Imports System.Runtime.CompilerServices\n\nModule IntegerExtensions\n\n <Extension()> _\n Public Function B(ByVal iNumber As Integer) As Byte\n Return Convert.ToByte(iNumber)\n End Function\n\nEnd Module\n Private Function GetTheAnswerAsByte() As Byte\n\n Return 42.B\n\nEnd Function\n" }, { "answer_id": 27761006, "author": "Erti-Chris Eelmaa", "author_id": 1936622, "author_profile": "https://Stackoverflow.com/users/1936622", "pm_score": 3, "selected": false, "text": "Public Const MyByte As Byte = 4UB;\nPublic Const MyByte2 As SByte = 4SB;\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252817", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6461/" ]
252,820
<p>Is it possible to have something like a <code>JTextArea</code> which will color some keywords based on some mappings I have ?</p>
[ { "answer_id": 252833, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 3, "selected": true, "text": "JTextArea SyntaxHighlighter JTextPane" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31610/" ]
252,848
<p>I tried this step:</p> <p>Select the menu options "Project > New Build Phase > New Run Script Build Phase", and enter the following script (don't forget to replace /Users/youruser/bin by the correct path to gen_entitlements.py) :</p> <pre><code>export CODESIGN_ALLOCATE=/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/codesign_allocate if [ "${PLATFORM_NAME}" == "iphoneos" ]; then /Users/youruser/bin/gen_entitlements.py "my.company.${PROJECT_NAME}" "${BUILT_PRODUCTS_DIR}/${WRAPPER_NAME}/${PROJECT_NAME}.xcent"; codesign -f -s "iPhone developer" --resource-rules "${BUILT_PRODUCTS_DIR}/${WRAPPER_NAME}/ResourceRules.plist" \ --entitlements "${BUILT_PRODUCTS_DIR}/${WRAPPER_NAME}/${PROJECT_NAME}.xcent" "${BUILT_PRODUCTS_DIR}/${WRAPPER_NAME}/" fi </code></pre> <p>(from <a href="http://www.246tnt.com/iPhone/#xcode" rel="noreferrer">link</a>)</p> <p>Now I want to remove this script from my project. How do I remove the "Run Script Build Phase" build phase from Xcode?</p>
[ { "answer_id": 48738485, "author": "Lance Samaria", "author_id": 4833705, "author_profile": "https://Stackoverflow.com/users/4833705", "pm_score": 1, "selected": false, "text": "Build Phases Run Script X X Delete" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252848", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16066/" ]
252,856
<pre><code>div#thing { position: absolute; top: 0px; z-index: 2; margin: 0 auto; } &lt;div id="thing"&gt; &lt;p&gt;text text text with no fixed size, variable font&lt;/p&gt; &lt;/div&gt; </code></pre> <p>The div is at the top, but I can't center it with <code>&lt;center&gt;</code> or <code>margin: 0 auto</code>;</p>
[ { "answer_id": 252872, "author": "JacobE", "author_id": 30056, "author_profile": "https://Stackoverflow.com/users/30056", "pm_score": 8, "selected": true, "text": "div div#thing {\n position: absolute;\n top: 0px;\n z-index: 2;\n width:400px;\n margin-left:-200px;\n left:50%;\n}\n" }, { "answer_id": 447113, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "div#thing { text-align:center; }\n" }, { "answer_id": 13806288, "author": "Matheus Oliveira", "author_id": 1892416, "author_profile": "https://Stackoverflow.com/users/1892416", "pm_score": 7, "selected": false, "text": "div#thing\n{\n position: absolute;\n width:400px;\n right: 0;\n left: 0;\n margin: auto;\n}\n" }, { "answer_id": 37922145, "author": "dalvallana", "author_id": 1371913, "author_profile": "https://Stackoverflow.com/users/1371913", "pm_score": -1, "selected": false, "text": "div#wrapper {\n position: absolute;\n width: 100%;\n text-align: center;\n}\n" }, { "answer_id": 38314913, "author": "Usman Shaukat", "author_id": 1121145, "author_profile": "https://Stackoverflow.com/users/1121145", "pm_score": 0, "selected": false, "text": "div#thing \n{ \n position: absolute; \n top: 0px; \n z-index: 2; \n left:0;\n right:0;\n }\n\ndiv#thing-body\n{\n text-align:center;\n}\n <div id=\"thing\">\n <div id=\"thing-child\">\n <p>text text text with no fixed size, variable font</p>\n </div>\n</div>\n" }, { "answer_id": 38973078, "author": "Michael Giovanni Pumo", "author_id": 695749, "author_profile": "https://Stackoverflow.com/users/695749", "pm_score": 5, "selected": false, "text": "// Horizontal example.\ndiv#thing {\n position: absolute;\n left: 50%;\n transform: translateX(-50%);\n}\n // Vertical example.\ndiv#thing {\n position: absolute;\n top: 50%;\n transform: translateY(-50%);\n}\n" }, { "answer_id": 56915604, "author": "Armin", "author_id": 9683034, "author_profile": "https://Stackoverflow.com/users/9683034", "pm_score": 3, "selected": false, "text": "div#thing {\n position: absolute;\n left: 50%;\n top: 50%;\n transform: translate(-50%, -50%);\n}\n" }, { "answer_id": 58612513, "author": "Aliaksei", "author_id": 7605505, "author_profile": "https://Stackoverflow.com/users/7605505", "pm_score": 0, "selected": false, "text": "#thing {\n position: absolute;\n width: 50vw;\n right: 25vw;\n}\n" }, { "answer_id": 61340445, "author": "panwar", "author_id": 5259876, "author_profile": "https://Stackoverflow.com/users/5259876", "pm_score": 1, "selected": false, "text": ".contentBlock {\n width: {define width}\n width: 400px;\n position: absolute;\n left: 0;\n right: 0;\n margin-left: auto;\n margin-right: auto;\n \n}" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21559/" ]
252,865
<p>"We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil." (Donald Knuth). My SQL tables are unlikely to contain more than a few thousand rows each (and those are the big ones!). SQL Server Database Engine Tuning Advisor dismisses the amount of data as irrelevant. So I shouldn't even think about putting explicit indexes on these tables. Correct?</p>
[ { "answer_id": 252952, "author": "Timothy Khouri", "author_id": 11917, "author_profile": "https://Stackoverflow.com/users/11917", "pm_score": 3, "selected": false, "text": "SELECT * FROM MySmallTable <-- No worries... Index won't help\n\nSELECT\n *\nFROM\n MyBigTable INNER JOIN MySmallTable ON... <-- Ahh, now I'm glad I have my index.\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252865", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15354/" ]
252,882
<p>There are a couple of questions similar to this on stack overflow but not quite the same.</p> <p>I want to open, or create, a local group on a win xp computer and add members to it, domain, local and well known accounts. I also want to check whether a user is already a member so that I don't add the same account twice, and presumably get an exception.</p> <p>So far I started using the DirectoryEntry object with the <code>WinNT://</code> provider. This is going ok but I'm stuck on how to get a list of members of a group?</p> <p>Anyone know how to do this? Or provide a better solution than using DirectoryEntry?</p>
[ { "answer_id": 252890, "author": "Tim Robinson", "author_id": 32133, "author_profile": "https://Stackoverflow.com/users/32133", "pm_score": 1, "selected": false, "text": "\"member\" DirectoryEntry" }, { "answer_id": 252892, "author": "splattne", "author_id": 6461, "author_profile": "https://Stackoverflow.com/users/6461", "pm_score": 3, "selected": false, "text": "using System.DirectoryServices;\n\nArrayList GetADGroupUsers(string groupName)\n{ \n SearchResult result;\n DirectorySearcher search = new DirectorySearcher();\n search.Filter = String.Format(\"(cn={0})\", groupName);\n search.PropertiesToLoad.Add(\"member\");\n result = search.FindOne();\n\n ArrayList userNames = new ArrayList();\n if (result != null)\n {\n for (int counter = 0; counter < \n result.Properties[\"member\"].Count; counter++)\n {\n string user = (string)result.Properties[\"member\"][counter];\n userNames.Add(user);\n }\n }\n return userNames;\n}\n" }, { "answer_id": 313799, "author": "Kepboy", "author_id": 21429, "author_profile": "https://Stackoverflow.com/users/21429", "pm_score": 6, "selected": true, "text": "Public Function MembersOfGroup(ByVal GroupName As String) As List(Of DirectoryEntry)\n Dim members As New List(Of DirectoryEntry)\n Try\n Using search As New DirectoryEntry(\"WinNT://./\" & GroupName & \",group\")\n For Each member As Object In DirectCast(search.Invoke(\"Members\"), IEnumerable)\n Dim memberEntry As New DirectoryEntry(member)\n members.Add(memberEntry)\n Next\n End Using\n Catch ex As Exception\n MessageBox.Show(ex.ToString)\n End Try\n Return members\nEnd Function\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252882", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21429/" ]
252,891
<p>Am I allowed to place <code>&lt;noscript&gt;</code> in the <code>&lt;head&gt;</code>?</p>
[ { "answer_id": 8595670, "author": "Kevin C.", "author_id": 193494, "author_profile": "https://Stackoverflow.com/users/193494", "pm_score": 4, "selected": false, "text": "<head> <link>" }, { "answer_id": 58421249, "author": "Luke", "author_id": 1716905, "author_profile": "https://Stackoverflow.com/users/1716905", "pm_score": 1, "selected": false, "text": "<noscript> <head>" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21559/" ]
252,893
<p>How do you change the CLASSPATH of a Java process from within the Java process?</p> <hr> <p>Before you ask me "Why would you want to do that?" I'll explain it shortly. </p> <blockquote> <p>When you have a Clojure REPL running it is common to need more jars in your CLASSPATH to load a <a href="http://clojure.org" rel="noreferrer">Clojure</a> source file, and I'd like to do it without having to restart Clojure itself (which is not really an option when using it on Slime on Emacs).</p> </blockquote> <p>That's the reason but I don't want this question tagged as some-weird-language some-weird-editor and be disregarded by the majority of Java developers that may have the answer.</p>
[ { "answer_id": 252967, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 7, "selected": true, "text": "java.lang.ClassLoader java.net.URLClassLoader URLClassLoader (URLClassLoader) getClass().getClassLoader() (URLClassLoader) ClassLoader.getSystemClassLoader() URLClassLoader URL[] url={new URL(\"file://foo\")};\nURLClassLoader loader = new URLClassLoader(url);\n ClassLoader currentThreadClassLoader\n = Thread.currentThread().getContextClassLoader();\n\n// Add the conf dir to the classpath\n// Chain the current thread classloader\nURLClassLoader urlClassLoader\n = new URLClassLoader(new URL[]{new File(\"mtFile\").toURL()},\n currentThreadClassLoader);\n\n// Replace the thread classloader - assumes\n// you have permissions to do so\nThread.currentThread().setContextClassLoader(urlClassLoader);\n public void addURL(URL url) throws Exception {\n URLClassLoader classLoader\n = (URLClassLoader) ClassLoader.getSystemClassLoader();\n Class clazz= URLClassLoader.class;\n\n // Use reflection\n Method method= clazz.getDeclaredMethod(\"addURL\", new Class[] { URL.class });\n method.setAccessible(true);\n method.invoke(classLoader, new Object[] { url });\n}\n\naddURL(new File(\"conf\").toURL());\n\n// This should work now!\nThread.currentThread().getContextClassLoader().getResourceAsStream(\"context.xml\");\n" }, { "answer_id": 19293096, "author": "Akhi Youngisthan", "author_id": 2834852, "author_profile": "https://Stackoverflow.com/users/2834852", "pm_score": -1, "selected": false, "text": "String s=\"java -classpath abcd/ \"+pgmname+\" \"+filename; \nProcess pro2 = Runtime.getRuntime().exec(s); \nBufferedReader in = new BufferedReader(new InputStreamReader(pro2.getInputStream()));\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252893", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6068/" ]
252,897
<p>I am developing an application that needs to use regini (because of legacy reasons) to insert something into the registry. I have been trying to do this in such a way the the user of the application is not aware of this. I have written the following code:</p> <pre><code>System.Diagnostics.ProcessStartInfo pi = new ProcessStartInfo(); pi.FileName = @"c:\windows\system32\regini.exe"; pi.Arguments = name; pi.WorkingDirectory = Utils.AppSettings.WorkingDirectory.ToString(); pi.WindowStyle = ProcessWindowStyle.Hidden; pi.RedirectStandardError = true; pi.RedirectStandardOutput = true; pi.UseShellExecute = false; Process p = new Process(); p.StartInfo = pi; p.EnableRaisingEvents = true; p.Start(); </code></pre> <p>Unfortunately, I still see the 'command' window pop-up every time this code is executed. I was under the impression that </p> <pre><code>pi.WindowStyle = ProcessWindowStyle.Hidden; </code></pre> <p>would prevent that. How can I prevent regini from opening its own command window? </p>
[ { "answer_id": 253098, "author": "splattne", "author_id": 6461, "author_profile": "https://Stackoverflow.com/users/6461", "pm_score": 3, "selected": true, "text": "pi.CreateNoWindow = true;\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252897", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32522/" ]
252,906
<p>Anyone got an idea how to get from an Xserver the list of all open windows?</p>
[ { "answer_id": 252911, "author": "Alnitak", "author_id": 6782, "author_profile": "https://Stackoverflow.com/users/6782", "pm_score": 8, "selected": true, "text": "xwininfo -tree -root\n XQueryTree Xlib" }, { "answer_id": 1017932, "author": "Marten", "author_id": 125739, "author_profile": "https://Stackoverflow.com/users/125739", "pm_score": 4, "selected": false, "text": "_NET_CLIENT_LIST xprop -root|grep ^_NET_CLIENT_LIST\n" }, { "answer_id": 61784442, "author": "Christian Reall-Fluharty", "author_id": 11411686, "author_profile": "https://Stackoverflow.com/users/11411686", "pm_score": 4, "selected": false, "text": "xprop _NET_WM_NAME $ xprop -root _NET_CLIENT_LIST |\n pcregrep -o1 '# (.*)' |\n sed 's/, /\\n/g' |\n xargs -I{} -n1 xprop -id {} _NET_WM_NAME\n wmctrl $ wmctrl -l\n python-xlib #!/usr/bin/env python\nfrom Xlib.display import Display\nfrom Xlib.X import AnyPropertyType\n\ndisplay = Display()\nroot = display.screen().root\n\n_NET_CLIENT_LIST = display.get_atom('_NET_CLIENT_LIST')\n_NET_WM_NAME = display.get_atom('_NET_WM_NAME')\n\nclient_list = root.get_full_property(\n _NET_CLIENT_LIST,\n property_type=AnyPropertyType,\n).value\n\nfor window_id in client_list:\n window = display.create_resource_object('window', window_id)\n window_name = window.get_full_property(\n _NET_WM_NAME,\n property_type=AnyPropertyType,\n ).value\n print(window_name)\n EWMH #!/usr/bin/env python\nfrom ewmh import EWMH\n\nwindow_manager_manager = EWMH()\nclient_list = window_manager_manager.getClientList()\n\nfor window in client_list:\n print(window_manager_manager.getWmName(window))\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252906", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4172/" ]
252,907
<p>I have two PHP scripts, both using the same session by calling <code>session_name('MySessID')</code>.</p> <p>When the first script calls the second script using curl, the second script hangs when <code>session_start()</code> is called.</p> <p>Why would this happend?</p>
[ { "answer_id": 252958, "author": "Jrgns", "author_id": 6681, "author_profile": "https://Stackoverflow.com/users/6681", "pm_score": 4, "selected": true, "text": "session_commit" }, { "answer_id": 470333, "author": "Tom", "author_id": 42754, "author_profile": "https://Stackoverflow.com/users/42754", "pm_score": 2, "selected": false, "text": "// IMPORTANT (OR ELSE INFINITE LOOP) - close current sessions or the next page will wait FOREVER for a write lock.\nsession_write_close();\n\n// We can't use GET because we can't display the password in the URL.\n$host = $_SERVER['HTTP_HOST'];\n$uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\\\');\n$url = \"http://$host$uri/formPage2.php?\";\n\n$ch = curl_init();\ncurl_setopt($ch, CURLOPT_URL,$url); //append URL\ncurl_setopt($ch, CURLOPT_POST,TRUE);//We are using method POST\ncurl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($_REQUEST, '', \"&\"));//append parameters \n\ncurl_exec($ch); // results will be outputted to the browser directly\ncurl_close($ch);\nexit();\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252907", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6681/" ]
252,915
<p>How to send array in Httpservice in Adobe Flex3</p>
[ { "answer_id": 435524, "author": "bartv", "author_id": 51371, "author_profile": "https://Stackoverflow.com/users/51371", "pm_score": 3, "selected": false, "text": "var service:HTTPService = new HTTPService();\nservice.useProxy = true;\nservice.destination = \"myservicet\";\nservice.resultFormat = HTTPService.RESULT_FORMAT_XML;\n\nvar fields:Array = [\"categories\", \"organisation\"];\nvar params:Object = new Object();\nparams.q = \"stackoverflow\";\nparams.rows = 0;\nparams.facet = \"true\";\nparams[\"facet.field\"] = fields;\nservice.send(params);\n" }, { "answer_id": 1013842, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "var fields:Array = [\"categories\", \"organisation\"];\nvar params:Object = {};\nparams.q = \"stackoverflow\";\nparams.rows = 0;\nparams.facet = \"true\";\nparams[\"facet.field[]\"] = fields;\nservice.send(params);\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252915", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33016/" ]
252,917
<p>I feel that using GetEnumerator() and casting IEnumerator.Current is expensive. Any better suggestions?<br/><br/> I'm open to using a different data structure if it offers similiar capabilities with better performance.</p> <p><strong>After thought:</strong><br/> Would a generic stack be a better idea so that the cast isn't necessary?</p>
[ { "answer_id": 252944, "author": "Timothy Khouri", "author_id": 11917, "author_profile": "https://Stackoverflow.com/users/11917", "pm_score": 3, "selected": false, "text": "Stack<MyClass> stacky = new Stack<MyClass>();\n\nforeach (MyClass item in stacky)\n{\n // this is as fast as you're going to get.\n}\n" }, { "answer_id": 252946, "author": "Pop Catalin", "author_id": 4685, "author_profile": "https://Stackoverflow.com/users/4685", "pm_score": 2, "selected": false, "text": "IEnumerable<T> IEnumerator<T>" }, { "answer_id": 252968, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 4, "selected": false, "text": "Stack<T> Stack<T> stack = null;\n while (stack.Count > 0)\n {\n T value = stack.Pop();\n // process value\n }\n" }, { "answer_id": 35052908, "author": "Rob Bennet", "author_id": 317960, "author_profile": "https://Stackoverflow.com/users/317960", "pm_score": 1, "selected": false, "text": "var enumerator = stack.GetEnumerator();\n\nwhile(enumerator.MoveNext ()) {\n // do stuff with enumerator value using enumerator.Current\n enumerator.Current = blah\n}\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252917", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17540/" ]
252,921
<p>Magento shopping cart is built on the Zend Framework in PHP. This is the first time I've dealt with the Zend framework and I'm having the following difficulty...</p> <p>I'm creating a custom module that will allow users to upload images whenever they purchase products. </p> <p>I can overload the addAction() method whenever a user attempts to add a product to their cart. I can also create a custom module which presents the form to the user and accepts the file(s). However I'm not sure how to insert the code to run my module into my overloaded method:</p> <pre><code>&lt;?php require_once 'Mage/Checkout/controllers/CartController.php'; class Company_SpecialCheckout_Checkout_CartController extends Mage_Checkout_CartController { # Overloaded addAction public function addAction() { # when user tries to add to cart, request images from them # ********* # *** what do i do in here to display a custom block ???? ### # *** and allow addAction to continue only if successfully validated form input ### # ********* parent::addAction(); } } </code></pre> <p>I suspect my difficulties come from my lack of knowledge of the Zend MVC way of doing things. I've studied all the Magento documentation/wikis/forum threads from top to bottom.</p>
[ { "answer_id": 258573, "author": "Simon", "author_id": 33036, "author_profile": "https://Stackoverflow.com/users/33036", "pm_score": 2, "selected": false, "text": " <?PHP\nrequire_once 'Mage/Checkout/controllers/CartController.php';\nclass Company_SpecialCheckout_Checkout_CartController extends Mage_Checkout_CartController {\n\n public function indexAction()\n {\n die('test');\n }\n}\n <?xml version=\"1.0\"?>\n<config>\n <modules>\n <Company_SpecialCheckout>\n <version>0.1.0</version>\n </Company_SpecialCheckout>\n </modules>\n <global>\n <rewrite>\n <Company_SpecialCheckout_Checkout_Cart>\n <from><![CDATA[#^/checkout/cart#]]></from>\n <to>/SpecialCheckout/checkout_cart</to>\n </Company_SpecialCheckout_Checkout_Cart>\n </rewrite>\n </global>\n <frontend>\n <routers>\n <Company_SpecialCheckout>\n <use>standard</use>\n <args>\n <module>Company_SpecialCheckout</module>\n <frontName>SpecialCheckout</frontName>\n </args>\n </Company_SpecialCheckout>\n </routers>\n </frontend>\n</config>\n <?xml version=\"1.0\"?>\n<config>\n <modules>\n <Company_SpecialCheckout>\n <active>true</active>\n <codePool>local</codePool>\n </Company_SpecialCheckout>\n </modules>\n</config>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252921", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17492/" ]
252,924
<p>This is a simple one. I want to replace a sub-string with another sub-string on client-side using Javascript.</p> <p>Original string is <code>'original READ ONLY'</code></p> <p>I want to replace the <code>'READ ONLY'</code> with <code>'READ WRITE'</code></p> <p>Any quick answer please? Possibly with a javascript code snippet...</p>
[ { "answer_id": 252928, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 4, "selected": false, "text": "<script type=\"text/javascript\">\n\nvar str1=\"Visit Microsoft!\";\nvar str2 = str1.replace(/microsoft/i, \"W3Schools\"); //Will work, per the i modifier \n\nvar str3 = \"original READ ONLY\";\nvar str4 = str3.replace(\"ONLY\", \"WRITE\"); //Will also work\n\n</script>\n" }, { "answer_id": 252930, "author": "rogeriopvl", "author_id": 28388, "author_profile": "https://Stackoverflow.com/users/28388", "pm_score": 2, "selected": false, "text": "stringObject.replace(findstring,newstring)\n" }, { "answer_id": 252939, "author": "Andrew Bullock", "author_id": 28543, "author_profile": "https://Stackoverflow.com/users/28543", "pm_score": 2, "selected": false, "text": "<script type=\"text/javascript\">\n\nvar str = \"this is a String\";\n\ndocument.write(str.replace(/\\s/g, \"_\"));\n\nwould print: this_is_a_string\n\ndocument.write(str.replace(/s/gi, \"f\"));\n\nwould print \"thif if a ftring\"\n\n</script>\n" }, { "answer_id": 253029, "author": "bobince", "author_id": 18936, "author_profile": "https://Stackoverflow.com/users/18936", "pm_score": 6, "selected": true, "text": "String.replace() function string_replace(haystack, find, sub) {\n return haystack.split(find).join(sub);\n}\n find" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252924", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13370/" ]
252,945
<p>I am creating a plugin for Eclipse 3.4. I created a plug-in development project using the application with a view. Now I am trying to create a <code>TextViewer</code> the documentation says that it is located in <code>org.eclipse.jface.text.TextViewer</code>. But, this whole package is missing and eclipse cannot locate <code>TextViewer</code> class to import. I want to know why is this package/class missing? Also if it is really gone what took <code>TextViewer</code>'s place?</p>
[ { "answer_id": 253132, "author": "McDowell", "author_id": 304, "author_profile": "https://Stackoverflow.com/users/304", "pm_score": 3, "selected": false, "text": "Require-Bundle: org.eclipse.ui,\n org.eclipse.core.runtime,\n org.eclipse.jface.text\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5004/" ]
252,955
<p>Is there a way to "stream" a set of results (eg. a DataTable) from a BackgroundWorker to a DataGridView. What I want to do is to query data, and fill the results in a DataGridView <strong>as they come</strong> (like query grid results in SQL Server Management Studio). My first thought was to use a BackgroundWorker (to avoid the UI freeze effect), but there would still be a perceivable "lag" as the BackgroundWorker is loading the results.</p> <p>What would be the best way to go about this?</p>
[ { "answer_id": 257554, "author": "Timothy Khouri", "author_id": 11917, "author_profile": "https://Stackoverflow.com/users/11917", "pm_score": 1, "selected": false, "text": "myDataGridView.Rows[rowNumber].SetValues(valuesFromNewPage);\n" }, { "answer_id": 426226, "author": "Coderer", "author_id": 26286, "author_profile": "https://Stackoverflow.com/users/26286", "pm_score": 1, "selected": false, "text": "myBindingSource[n] = newItem;\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18731/" ]
252,957
<p>I know we can do like mget *.xml which will download all xml files. But how is it possible that we using mget with certain file name patterns. can we do something like *SS.xml which mean it will download all files ending with SS.xml?</p>
[ { "answer_id": 252960, "author": "Alnitak", "author_id": 6782, "author_profile": "https://Stackoverflow.com/users/6782", "pm_score": 1, "selected": false, "text": "mget" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252957", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
252,962
<p>We have a file that has a 64 bit integer as a string in it. How do we scanf() or otherwise parse this numeric string into an unsigned 64 bit integer type in C++ ? </p> <p>We are aware of things like %lld etc., but a lot of ways to do this parse seem to break compiles under different compilers and stdlibs. The code should compile under gcc and the Microsoft C++ compiler (of course full compliance with standards would be a plus)</p>
[ { "answer_id": 252965, "author": "Alnitak", "author_id": 6782, "author_profile": "https://Stackoverflow.com/users/6782", "pm_score": 1, "selected": false, "text": "scanf() strtoull()" }, { "answer_id": 252979, "author": "unwind", "author_id": 28169, "author_profile": "https://Stackoverflow.com/users/28169", "pm_score": 2, "selected": false, "text": "strtoull() _strtoui64() _wcstoui64() _tcstoui64()" }, { "answer_id": 253053, "author": "xtofl", "author_id": 6610, "author_profile": "https://Stackoverflow.com/users/6610", "pm_score": 2, "selected": false, "text": " using namespace std;\n\n // construct a number -- generate test data\n long long llOut = 0x1000000000000000;\n stringstream sout;\n // write the number\n sout << llOut;\n string snumber = sout.str();\n // construct an istream containing a number\n stringstream sin( snumber );\n\n // read the number -- the crucial bit\n long long llIn(0);\n sin >> llIn;\n" }, { "answer_id": 253062, "author": "RobH", "author_id": 25488, "author_profile": "https://Stackoverflow.com/users/25488", "pm_score": 2, "selected": false, "text": "std::fstream fstm( \"file.txt\" );\n__int64 foo;\nfstm >> foo;\n" }, { "answer_id": 253128, "author": "KTC", "author_id": 12868, "author_profile": "https://Stackoverflow.com/users/12868", "pm_score": 4, "selected": true, "text": "#if (__cplusplus > 199711L) || defined(__GNUG__)\n typedef unsigned long long uint_64_t;\n#elif defined(_MSC_VER) || defined(__BORLANDC__) \n typedef unsigned __int64 uint_64_t;\n#else\n#error \"Please define uint_64_t\"\n#endif\n\nuint_64_t foo;\n\nstd::fstream fstm( \"file.txt\" );\nfstm >> foo;\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252962", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19734/" ]
252,963
<p>How can I use Hyperlink button in gridview. I mean when I run my program,all data is displayed in gridview,but I want hyperlink in gridview, so that when I will click in hyperlink it will show the select path which is in gridview : if there is pdf file path and I just click on this hyper link then I can see the pdf file.</p> <p>Can you tell me how can I do this? </p>
[ { "answer_id": 252984, "author": "Eoin Campbell", "author_id": 30155, "author_profile": "https://Stackoverflow.com/users/30155", "pm_score": 1, "selected": false, "text": "<asp:TemplateField HeaderText=\"Link\" SortExpression=\"PdfUrl\">\n <itemtemplate>\n <asp:HyperLink runat=\"server\" ID=\"hlkPDF\" NavigateURL='<%# DataBinder.Eval(Container.DataItem, \"PdfUrl\") %>' />\n </itemtemplate>\n</asp:TemplateField> \n" }, { "answer_id": 674300, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<asp:SqlDataSource ID=\"SqlDataSource1\" runat=\"server\" \n ConnectionString=\"<%$ ConnectionStrings:BlissConnectionString %>\" \n SelectCommand=\"SELECT * FROM [Customers] WHERE CustomerID = @ID\">\n <SelectParameters>\n <asp:QueryStringParameter Name=\"ID\" QueryStringField=\"ID\" />\n </SelectParameters>\n</asp:SqlDataSource>\n<br />\n<asp:DetailsView ID=\"DetailsView1\" runat=\"server\" AutoGenerateRows=\"False\" \n DataKeyNames=\"CustomerID\" DataSourceID=\"SqlDataSource1\" Height=\"50px\" \n Width=\"125px\">\n <Fields>\n <asp:BoundField DataField=\"CustomerID\" HeaderText=\"CustomerID\" \n InsertVisible=\"False\" ReadOnly=\"True\" SortExpression=\"CustomerID\" />\n <asp:BoundField DataField=\"CustomerName\" HeaderText=\"CustomerName\" \n SortExpression=\"CustomerName\" />\n <asp:BoundField DataField=\"CustomerAddress\" HeaderText=\"CustomerAddress\" \n SortExpression=\"CustomerAddress\" />\n <asp:BoundField DataField=\"CustomerPhone\" HeaderText=\"CustomerPhone\" \n SortExpression=\"CustomerPhone\" />\n <asp:BoundField DataField=\"CustomerEmail\" HeaderText=\"CustomerEmail\" \n SortExpression=\"CustomerEmail\" />\n </Fields>\n</asp:DetailsView>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
252,972
<p>Please forgive my long question. I have an idea for a design that I could use some comments on. Is it a good idea to do this? And what are the pit falls I should be aware of? Are there other similar implementations that are better?</p> <p><strong>My situation is as follows:</strong><br> I am working on a rewrite of a windows forms application that connects to a SQL 2008 (earlier it was SQL 2005) server. The application is an "expert-system" for an engineering company where we store structured data about constructions. We have control of all installations of the client software, we have no external customers or users, they are all internal to the company, and they are all be trusted not to do anything malicious to the software or database.</p> <p>The current design doesn't have too many tables (about 10 - 20) but some of them have millions of records that belong to several hundred constructions. The systems performance has been ok so far, but it is starting to degrade as we are pushing the limits of the design. </p> <p>As part of the rewrite I am considering splitting the database into one master database and several "child" databases where each describes one construction. Each child database should be of identical design. This should eliminate the performance problems we are seeing today since the data stored in each database would be less than one percent of the total data amount. </p> <p>My concern is that instead of maintaining one database we will now get hundreds of databases that must be kept up to date. The system is constantly evolving as the companys requirements change (you know how it is), and while we try to look forward to reduce the number of changes the changes will come. So we will need a system where we keep track of all database changes done to the system so they can be applied to the child databases. Updating the client application won't be a problem, we have good control of that aspect.</p> <p>I am thinking of a change tracing system where we store database scripts for all changes in a table in the master database. We can then give each change a version number and we can store a current version number in each child database. When the client program connects to a child database we can then check the version number of the database against the current version number of the master database and if there are patches with version numbers greater than the version number of the child database we run these and update the child database to the latest version. </p> <p>As I see it this should work well. Any changes to the system will first be tested and validated before committed as a new version of the database. The change will then be applied to the database the first time a user opens it. I suppose we would open the database in exclusive mode while applying the changes, but as long as the changes aren't too frequent this should not be a problem.</p> <p>So what do you think? Will this work? Have any of you done something similar? Should we scrap the solution and go for the monolithic system instead?</p>
[ { "answer_id": 253024, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": true, "text": "def change103(...):\n \"Create new table.\"\ndef change104(...):\n \"\"\"Transfer data from old table to new table and make\n complicated changes in the process.\n \"\"\"\ndef change105(...):\n \"Drop old table\"\ndef change106(...):\n \"Rename new table to old table\"\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252972", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30366/" ]
252,974
<p>I would like to hear some opinions about using the isolated storage in Silverlight for storing sensitive data. For example, is it OK to store an authentication token (some GUID that identifies a server-side session) in this storage, or is it better to use cookies?</p> <p>The isolated storage gives an advantage over cookies in that it is shared across browsers, but it might be more difficult to handle expiry, and there might be some other issues (security?) that I am not aware of.</p> <p>So... what are your opinions? Or do you know any great articles about the topic?</p> <p>Thanks, Jacob</p>
[ { "answer_id": 253024, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": true, "text": "def change103(...):\n \"Create new table.\"\ndef change104(...):\n \"\"\"Transfer data from old table to new table and make\n complicated changes in the process.\n \"\"\"\ndef change105(...):\n \"Drop old table\"\ndef change106(...):\n \"Rename new table to old table\"\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252974", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30056/" ]
252,976
<p>How can I create a query for a full outer join across a M2M relationchip using the django QuerySet API?</p> <p>It that is not supported, some hint about creating my own manager to do this would be welcome.</p> <p><strong>Edited to add:</strong> @S.Lott: Thanks for the enlightenment. The need for the OUTER JOIN comes from the application. It has to generate a report showing the data entered, even if it still incomplete. I was not aware of the fact that the result would be a new class/model. Your hints will help me quite a bit.</p>
[ { "answer_id": 253057, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 5, "selected": true, "text": "for obj in Model1.objects.all():\n if obj.model2_set().count() == 0:\n # process (obj, None) -- no Model2 association\n else:\n for obj2 in obj.model2_set.all():\n # process (obj, obj2) -- the \"inner join\" result\n for obj2 in Model2.objects.all():\n if obj2.model1_set().count() == 0:\n # process (None, obj2) -- no Model1 association\n if someObj.anObj2attribute is None Model1 Model2 if errorList1 = Model1.objects.filter( status=\"Incomplete\" )\nerrorList2 = Model2.objects.filter( status=\"Incomplete\" )\n <table>\n <tr><th>Model1</th><th>Model2</th></tr>\n {% for e1 in errorList1 %}\n <tr><td>e1</td><td>NULL</td></tr>\n {% endfor %}\n {% for e2 in errorList2 %}\n <tr><td>NULL</td><td>e2</td></tr>\n {% endfor %}\n</table>\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252976", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11527/" ]
252,988
<p>How to get all the database names and corresponding table names together ?</p>
[ { "answer_id": 253003, "author": "Hapkido", "author_id": 27646, "author_profile": "https://Stackoverflow.com/users/27646", "pm_score": 0, "selected": false, "text": "SELECT Name FROM master.sys.databases\n SELECT %DatabaseName%, Name FROM %DatabaseName%.SysObjects WHERE type = 'U'\n CREATE PROCEDURE sp_GetDatabasesTables \nAS\nBEGIN\n-- SET NOCOUNT ON added to prevent extra result sets from\n-- interfering with SELECT statements.\nSET NOCOUNT ON;\nCREATE TABLE #schema ( DatabaseName VarChar(50), TableName VarChar(50) );\nDECLARE @DatabaseName varchar(50);\nDECLARE cursorDatabase CURSOR FOR\n SELECT Name FROM master.sys.databases WHERE Name NOT IN ('tempdb'); -- add any table you want to filter here\n\nOPEN cursorDatabase;\n\n-- Perform the first fetch.\nFETCH NEXT FROM cursorDatabase INTO @DatabaseName;\n\n-- Check @@FETCH_STATUS to see if there are any more rows to fetch.\nWHILE @@FETCH_STATUS = 0\nBEGIN\n EXEC ('INSERT INTO #schema (DatabaseName, TableName) SELECT ''' + @DatabaseName + ''' AS DatabaseName, Name As TableName FROM ' + @DatabaseName + '.sys.SysObjects WHERE type = ''U'';');\n FETCH NEXT FROM cursorDatabase INTO @DatabaseName;\nEND\n\nCLOSE cursorDatabase;\nDEALLOCATE cursorDatabase;\nSELECT * FROM #schema\nEND\n" }, { "answer_id": 253042, "author": "Timothy Khouri", "author_id": 11917, "author_profile": "https://Stackoverflow.com/users/11917", "pm_score": 1, "selected": false, "text": "CREATE TABLE #dbs ( DatabaseName VARCHAR(256), TableName VARCHAR(256) )\n\nEXEC sp_msforeachdb 'INSERT INTO #dbs\n SELECT ''?'', [name] FROM dbo.SysObjects WHERE XType = ''U'''\n\nSELECT * FROM #dbs\nDROP TABLE #dbs\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/252988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
253,013
<p>We use a simple object model for our low level networking code at work where struct pointers are passed around to functions which are pretending to be methods. I've inherited most of this code which was written by consultants with passable C/C++ experience at best and I've spent many late nights trying to refactor code into something that would resemble a reasonable structure.</p> <p>Now I would like to bring the code under unit testing but considering the object model we have chosen I have no idea how to mock objects. See the example below:</p> <p>Sample header (foo.h):</p> <pre><code>#ifndef FOO_H_ #define FOO_H_ typedef struct Foo_s* Foo; Foo foo_create(TcpSocket tcp_socket); void foo_destroy(Foo foo); int foo_transmit_command(Foo foo, enum Command command); #endif /* FOO_H_ */ </code></pre> <p>Sample source (foo.c):</p> <pre><code>struct Foo_s { TcpSocket tcp_socket; }; Foo foo_create(TcpSocket tcp_socket) { Foo foo = NULL; assert(tcp_socket != NULL); foo = malloc(sizeof(struct Foo_s)); if (foo == NULL) { goto fail; } memset(foo, 0UL, sizeof(struct Foo_s)); foo-&gt;tcp_socket = tcp_socket; return foo; fail: foo_destroy(foo); return NULL; } void foo_destroy(Foo foo) { if (foo != NULL) { tcp_socket_destroy(foo-&gt;tcp_socket); memset(foo, 0UL, sizeof(struct Foo_s)); free(foo); } } int foo_transmit_command(Foo foo, enum Command command) { size_t len = 0; struct FooCommandPacket foo_command_packet = {0}; assert(foo != NULL); assert((Command_MIN &lt;= command) &amp;&amp; (command &lt;= Command_MAX)); /* Serialize command into foo_command_packet struct */ ... len = tcp_socket_send(foo-&gt;tcp_socket, &amp;foo_command_packet, sizeof(foo_command_packet)); if (len &lt; sizeof(foo_command_packet)) { return -1; } return 0; } </code></pre> <p>In the example above I would like to mock the <em>TcpSocket</em> object so that I can bring <em>"foo_transmit_command"</em> under unit testing but I'm not sure how to go about this without inheritance. I don't really want to redesign the code to use vtables unless I really have to. Maybe there is a better approach to this than mocking?</p> <p>My testing experience comes mainly from C++ and I'm a bit afraid that I might have painted myself into a corner here. I would highly appreciate any recommendations from more experienced testers.</p> <p>Edit:<br> Like Richard Quirk pointed out it is really the call to <em>"tcp_socket_send"</em> that I want to override and I would prefer to do it without removing the real tcp_socket_send symbol from the library when linking the test since it is called by other tests in the same binary.</p> <p>I'm starting to think that there is no obvious solution to this problem..</p>
[ { "answer_id": 253119, "author": "qrdl", "author_id": 28494, "author_profile": "https://Stackoverflow.com/users/28494", "pm_score": 0, "selected": false, "text": "struct Foo_s this" }, { "answer_id": 253265, "author": "Ilya", "author_id": 6807, "author_profile": "https://Stackoverflow.com/users/6807", "pm_score": 3, "selected": true, "text": "tcp_socket_send tcp_socket_send_moc tcp_socket_send tcp_socket_send_moc #define tcp_socket_send tcp_socket_send_moc\n" }, { "answer_id": 8345978, "author": "Martin", "author_id": 1076006, "author_profile": "https://Stackoverflow.com/users/1076006", "pm_score": 1, "selected": false, "text": "int mock_foo_transmit_command(Foo foo, enum Command command) {\n VALIDATE(foo, a);\n VALIDATE(command, b);\n}\n\nvoid test(void) {\n EXPECT_VALIDATE(foo_transmit_command, mock_foo_transmit_command);\n foo_transmit_command(a, b);\n}\n" }, { "answer_id": 33489442, "author": "donfiguerres", "author_id": 4097451, "author_profile": "https://Stackoverflow.com/users/4097451", "pm_score": 0, "selected": false, "text": "#define tcp_socket_send tcp_socket_send_moc\n#include \"your_source_code.c\"\n\nint tcp_socket_send_moc(...)\n{ ... }\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/253013", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22247/" ]
253,026
<p>I used a class which derives from <code>CListBox</code>, and create it with following:</p> <pre><code>style:WS_CHILD|WS_VISIBLE |LBS_OWNERDRAWFIXED | WS_VSCROLL | WS_HSCROLL </code></pre> <p>I expect the ListBox's item to be have a fixed size, not affected by the size of the list box. So I override the MeasureItem() method, in which I specify the item's size like below:</p> <pre><code>void CMyListBox::MeasureItem(LPMEASUREITEMSTRUCT lpMIS) { lpMIS-&gt;itemHeight = ALBUM_ITEM_HEIGHT; lpMIS-&gt;itemWidth = ALBUM_ITEM_WIDTH; } </code></pre> <p>But the item's size changes according to the List box's size changing. is there anything wrong with my approach?</p>
[ { "answer_id": 253201, "author": "Stu Mackellar", "author_id": 28591, "author_profile": "https://Stackoverflow.com/users/28591", "pm_score": 0, "selected": false, "text": "MSDN CListBox::MeasureItem LBS_OWNERDRAWVARIABLE LBS_OWNERDRAWFIXED MeasureItem" }, { "answer_id": 1125905, "author": "macbirdie", "author_id": 5049, "author_profile": "https://Stackoverflow.com/users/5049", "pm_score": 1, "selected": false, "text": "WM_MEASUREITEM *_OWNERDRAWFIXED OnMeasureItem()" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/253026", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26404/" ]
253,030
<p>If you want to some code to execute based on two or more conditions which is the best way to format that if statement ?</p> <p>first example:-</p> <pre><code>if(ConditionOne &amp;&amp; ConditionTwo &amp;&amp; ConditionThree) { Code to execute } </code></pre> <p>Second example:-</p> <pre><code>if(ConditionOne) { if(ConditionTwo ) { if(ConditionThree) { Code to execute } } } </code></pre> <p>which is easiest to understand and read bearing in mind that each condition may be a long function name or something.</p>
[ { "answer_id": 253047, "author": "Torbjørn", "author_id": 22621, "author_profile": "https://Stackoverflow.com/users/22621", "pm_score": 5, "selected": false, "text": "if(MyChecksAreOk()) { Code to execute }\n\n...\n\nprivate bool MyChecksAreOk()\n{ \n return ConditionOne && ConditionTwo && ConditionThree;\n}\n" }, { "answer_id": 253049, "author": "Eoin Campbell", "author_id": 30155, "author_profile": "https://Stackoverflow.com/users/30155", "pm_score": 7, "selected": false, "text": "bool a, b, c;\n\nif( a && b && c )\n{\n //This is neat & readable\n}\n if( VeryLongConditionMethod(a) &&\n VeryLongConditionMethod(b) &&\n VeryLongConditionMethod(c))\n{\n //This is still readable\n}\n bool aa = FirstVeryLongConditionMethod(a) && SecondVeryLongConditionMethod(a);\nbool bb = FirstVeryLongConditionMethod(b) && SecondVeryLongConditionMethod(b);\nbool cc = FirstVeryLongConditionMethod(c) && SecondVeryLongConditionMethod(c);\n\nif( aa && bb && cc)\n{\n //This is again neat & readable\n //although you probably need to sanity check your method names ;)\n}\n else if( a )\n{\n if( b )\n {\n }\n else\n {\n //Do Something Else B\n }\n}\nelse\n{\n //Do Something Else A\n}\n" }, { "answer_id": 253056, "author": "David Santamaria", "author_id": 24097, "author_profile": "https://Stackoverflow.com/users/24097", "pm_score": 4, "selected": false, "text": "if(ConditionOneThatIsTooLongAndProbablyWillUseAlmostOneLine\n && ConditionTwoThatIsLongAsWell\n && ConditionThreeThatAlsoIsLong) { \n //Code to execute \n}\n" }, { "answer_id": 253168, "author": "interstar", "author_id": 8482, "author_profile": "https://Stackoverflow.com/users/8482", "pm_score": 3, "selected": false, "text": "if user.hasPermission(Admin()) {\n if (x >= 0) && (x < 100) {\n // do something\n }\n}\n" }, { "answer_id": 255234, "author": "Brad Gilbert", "author_id": 1337, "author_profile": "https://Stackoverflow.com/users/1337", "pm_score": 0, "selected": false, "text": "{\n ( VeryLongCondition_1 ) or last;\n ( VeryLongCondition_2 ) or last;\n ( VeryLongCondition_3 ) or last;\n ( VeryLongCondition_4 ) or last;\n ( VeryLongCondition_5 ) or last;\n ( VeryLongCondition_6 ) or last;\n\n # Guarded code goes here\n}\n" }, { "answer_id": 28644944, "author": "CodeDriller", "author_id": 2830887, "author_profile": "https://Stackoverflow.com/users/2830887", "pm_score": -1, "selected": false, "text": "if( $format_bool &&\n (\n ( isset( $column_info['native_type'] )\n && stripos( $column_info['native_type'], 'bool' ) !== false\n )\n || ( isset( $column_info['driver:decl_type'] )\n && stripos( $column_info['driver:decl_type'], 'bool' ) !== false\n )\n || ( isset( $column_info['pdo_type'] )\n && $column_info['pdo_type'] == PDO::PARAM_BOOL\n )\n )\n)\n if() if() {...}" }, { "answer_id": 43506817, "author": "Sean", "author_id": 7892369, "author_profile": "https://Stackoverflow.com/users/7892369", "pm_score": 4, "selected": false, "text": "if ( ( single conditional expression A )\n && ( single conditional expression B )\n && ( single conditional expression C )\n )\n{\n opAllABC();\n}\nelse\n{\n opNoneABC();\n}\n // disable any single conditional test with just a pre-pended '//'\n// set a break point before any individual test\n// syntax '(1 &&' and '(0 ||' usually never creates any real code\nif ( 1\n && ( single conditional expression A )\n && ( single conditional expression B )\n && ( 0\n || ( single conditional expression C )\n || ( single conditional expression D )\n )\n )\n{\n ... ;\n}\n\nelse\n{\n ... ;\n}\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/253030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
253,036
<p>I have WPF ListBox which is bound to a ObservableCollection, when the collection changes, all items update their position.</p> <p>The new position is stored in the collection but the UI does not update. So I added the following:</p> <pre><code> void scenarioItems_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { ToolboxListItem.UpdatePositions(); lstScenario.ItemsSource = null; lstScenario.ItemsSource = ToolboxListItem.ScenarioItems; this.lstScenario.SelectedIndex = e.NewStartingIndex; } </code></pre> <p>By setting the ItemsSource to null and then binding it again, the UI is updated,</p> <p>but this is probably very bad coding :p</p> <p>Suggestions?</p>
[ { "answer_id": 253298, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": 7, "selected": true, "text": "List<MyCustomType>() void On_MyObjProperty_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)\n{\n MyListBox.Items.Refresh();\n}\n" }, { "answer_id": 1851824, "author": "rolling", "author_id": 225348, "author_profile": "https://Stackoverflow.com/users/225348", "pm_score": 4, "selected": false, "text": "ObservableCollection<> List<> ObservableCollection<> List<> INotifyCollectionChange ListBox private ObservableCollection<StringWrapper> m_AppLog;\nObservableCollection<StringWrapper> Log { get { return m_AppLog; } }\n // notify bound objects\nOnPropertyChanged(\"Log\");\n ObservableCollection public void AddToLog(string message) {\n if (Thread.CurrentThread != Dispatcher.Thread) {\n // Need for invoke if called from a different thread\n Dispatcher.Invoke(\n DispatcherPriority.Normal, (ThreadStart)delegate() { AddToLog(message); });\n }\n else {\n // add this line at the top of the log\n m_AppLog.Insert(0, new StringWrapper(message));\n // ...\n ObservableCollection<> RemoveRange() List<>" }, { "answer_id": 2630735, "author": "KP.", "author_id": 315629, "author_profile": "https://Stackoverflow.com/users/315629", "pm_score": 2, "selected": false, "text": "Public Class Session\nImplements INotifyPropertyChanged\n\nPublic Event PropertyChanged As PropertyChangedEventHandler _\n Implements INotifyPropertyChanged.PropertyChanged\n\nPrivate Sub NotifyPropertyChanged(ByVal info As String)\n RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(info))\nEnd Sub\n\nPrivate _name As String = \"No name\"\n''' <summary>\n''' Name of Session\n''' </summary>\n''' <value></value>\n''' <returns></returns>\n''' <remarks></remarks>\nPublic Property Name() As String\n Get\n Return _name\n End Get\n Set(ByVal value As String)\n _name = value\n NotifyPropertyChanged(\"Name\")\n End Set\nEnd Property\n" }, { "answer_id": 4139066, "author": "Alfred B. Thordarson", "author_id": 3379, "author_profile": "https://Stackoverflow.com/users/3379", "pm_score": 3, "selected": false, "text": "ObservableCollection<MyEntity> ListBox ListBox MyEntity ListBox" }, { "answer_id": 59042877, "author": "Berger", "author_id": 11217628, "author_profile": "https://Stackoverflow.com/users/11217628", "pm_score": 2, "selected": false, "text": "CollectionViewSource.GetDefaultView(this.myObservableCollection).Refresh();\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/253036", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28149/" ]
253,038
<p>I'm having a bit of a problem. I have a datatable in the parent form. I open a dialogbox form that gets the datatable property and creates a checkboxlist. This will be used to export those columns. But when I run the application the parentform property is null. I've tried setting it in the parent and dialogbox form (I assumed this would have been done automagically if ShowDialog() was called).</p> <p>Can someone take a look and see where I'm going wrong? From the dialogbox:</p> <pre><code>frmParent MyParentForm = (frmParent)this.ParentForm; for (int i=0; i&lt;MyParentForm.DataGridTable.Count; i++) { chkListExportItems.Add(MyParentForm.DataGrid.Columns[i].Name,true); } </code></pre> <p>From the parent form:</p> <pre><code>frmExports MyForm = new frmExports(); MyForm.MdiParent = this; if (MyForm.ShowDialog == DialogResult.OK) { MyForm.SelectedItems // Do something } </code></pre>
[ { "answer_id": 253298, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": 7, "selected": true, "text": "List<MyCustomType>() void On_MyObjProperty_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)\n{\n MyListBox.Items.Refresh();\n}\n" }, { "answer_id": 1851824, "author": "rolling", "author_id": 225348, "author_profile": "https://Stackoverflow.com/users/225348", "pm_score": 4, "selected": false, "text": "ObservableCollection<> List<> ObservableCollection<> List<> INotifyCollectionChange ListBox private ObservableCollection<StringWrapper> m_AppLog;\nObservableCollection<StringWrapper> Log { get { return m_AppLog; } }\n // notify bound objects\nOnPropertyChanged(\"Log\");\n ObservableCollection public void AddToLog(string message) {\n if (Thread.CurrentThread != Dispatcher.Thread) {\n // Need for invoke if called from a different thread\n Dispatcher.Invoke(\n DispatcherPriority.Normal, (ThreadStart)delegate() { AddToLog(message); });\n }\n else {\n // add this line at the top of the log\n m_AppLog.Insert(0, new StringWrapper(message));\n // ...\n ObservableCollection<> RemoveRange() List<>" }, { "answer_id": 2630735, "author": "KP.", "author_id": 315629, "author_profile": "https://Stackoverflow.com/users/315629", "pm_score": 2, "selected": false, "text": "Public Class Session\nImplements INotifyPropertyChanged\n\nPublic Event PropertyChanged As PropertyChangedEventHandler _\n Implements INotifyPropertyChanged.PropertyChanged\n\nPrivate Sub NotifyPropertyChanged(ByVal info As String)\n RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(info))\nEnd Sub\n\nPrivate _name As String = \"No name\"\n''' <summary>\n''' Name of Session\n''' </summary>\n''' <value></value>\n''' <returns></returns>\n''' <remarks></remarks>\nPublic Property Name() As String\n Get\n Return _name\n End Get\n Set(ByVal value As String)\n _name = value\n NotifyPropertyChanged(\"Name\")\n End Set\nEnd Property\n" }, { "answer_id": 4139066, "author": "Alfred B. Thordarson", "author_id": 3379, "author_profile": "https://Stackoverflow.com/users/3379", "pm_score": 3, "selected": false, "text": "ObservableCollection<MyEntity> ListBox ListBox MyEntity ListBox" }, { "answer_id": 59042877, "author": "Berger", "author_id": 11217628, "author_profile": "https://Stackoverflow.com/users/11217628", "pm_score": 2, "selected": false, "text": "CollectionViewSource.GetDefaultView(this.myObservableCollection).Refresh();\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/253038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5906/" ]
253,051
<p>I've been teaching myself Objective-C over the past month or so (I'm a Java head) and I've got my brain wrapped around most of it now. One thing that's confusing me at the moment: What's the difference between importing a class via @class vs doing a #import? </p> <p>Is one better than another one, or do I need to use one instead of the other in certain cases? I've been using just #import so far.</p>
[ { "answer_id": 253154, "author": "Ben Gottlieb", "author_id": 6694, "author_profile": "https://Stackoverflow.com/users/6694", "pm_score": 7, "selected": true, "text": "#import #import #import #import #import @class Object1; @class Object2; #import" }, { "answer_id": 253550, "author": "Dave Dribin", "author_id": 26825, "author_profile": "https://Stackoverflow.com/users/26825", "pm_score": 5, "selected": false, "text": "@class @class #import #import #import @protocol SomeProtocol;\n\n@interface ...\n\n- (id<SomeProtocol>)someMethod;\n\n@end\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/253051", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6044/" ]
253,055
<p>When I've worked a bit with my source code, I did my usual thing commit and then I pushed to a remote repository. But then I noticed I forgot to organize my imports in the source code. So I do the amend command to replace the previous commit:</p> <pre><code>&gt; git commit --amend </code></pre> <p>Unfortunately the commit can't be pushed back to the repository. It is rejected like this:</p> <pre><code>&gt; git push origin To //my.remote.repo.com/stuff.git/ ! [rejected] master -&gt; master (non-fast forward) error: failed to push some refs to '//my.remote.repo.com/stuff.git/' </code></pre> <p>What should I do? (I can access the remote repository.)</p>
[ { "answer_id": 253726, "author": "mipadi", "author_id": 28804, "author_profile": "https://Stackoverflow.com/users/28804", "pm_score": 7, "selected": false, "text": "git commit --amend git rebase $ git push origin +master:master\n +" }, { "answer_id": 255080, "author": "CB Bailey", "author_id": 19563, "author_profile": "https://Stackoverflow.com/users/19563", "pm_score": 8, "selected": false, "text": "-f git push -f origin master\n receive.denynonfastforwards ! [remote rejected] master -> master (non-fast forward)\n git push origin :master\ngit push origin master\n git push <local_ref>:<remote_ref> local_ref remote_ref :master master : master master:master" }, { "answer_id": 432518, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 10, "selected": true, "text": "--force .git git reflog old new old new new git checkout new && git merge -s ours old git merge master git push . HEAD:master new old old new" }, { "answer_id": 1459351, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 8, "selected": false, "text": "git pull\n git push\n" }, { "answer_id": 12568457, "author": "bara", "author_id": 794407, "author_profile": "https://Stackoverflow.com/users/794407", "pm_score": 5, "selected": false, "text": "# Rewind to commit before conflicting\ngit reset --soft HEAD~1\n\n# Pull the remote version\ngit pull\n\n# Add the new commit on top\ngit add ...\ngit commit\ngit push\n" }, { "answer_id": 21904884, "author": "davisca", "author_id": 3298088, "author_profile": "https://Stackoverflow.com/users/3298088", "pm_score": 4, "selected": false, "text": "# Rewind to commit just before the pushed-and-amended one.\n# Replace <hash> with the needed hash.\n# --soft means: leave all the changes there, so nothing is lost.\ngit reset --soft <hash>\n\n# Create new branch, just for a backup, still having all changes in it.\n# The branch was feature/1234, new one - feature/1234-gone-bad\ngit checkout -b feature/1234-gone-bad\n\n# Commit all the changes (all the mess) not to lose it & not to carry around\ngit commit -a -m \"feature/1234 backup\"\n\n# Switch back to the original branch\ngit checkout feature/1234\n\n# Pull the from remote (named 'origin'), thus 'repairing' our main problem\ngit pull origin/feature/1234\n\n# Now you have a clean-and-non-diverged branch and a backup of the local changes.\n# Check the needed files from the backup branch\ngit checkout feature/1234-gone-bad -- the/path/to/file.php\n" }, { "answer_id": 27916801, "author": "Prabhakar Undurthi", "author_id": 2200417, "author_profile": "https://Stackoverflow.com/users/2200417", "pm_score": 3, "selected": false, "text": " git commit --amend -m \"Your new message\"\n git commit --amend -m \"BRANCH-NAME: new message\"\n git commit --amend -m \"BRANCH-NAME : your new message\"\n\ngit push -f origin BRANCH-NAME # Not a best practice. Read below why?\n git commit --amend -m \"BRANCH-NAME : your new message\"\n git pull origin BRANCH-NAME\n git push -f origin BRANCH-NAME\n" }, { "answer_id": 30965735, "author": "Faiza", "author_id": 2349823, "author_profile": "https://Stackoverflow.com/users/2349823", "pm_score": 6, "selected": false, "text": "commit --amend git reset --soft HEAD^\ngit stash\ngit push -f origin master\ngit stash pop\ngit commit -a\ngit push origin master\n origin master" }, { "answer_id": 34850197, "author": "craken", "author_id": 3952386, "author_profile": "https://Stackoverflow.com/users/3952386", "pm_score": 2, "selected": false, "text": "git add \"your files\" git commit --amend git push origin master -f\n git push origin master --force\n" }, { "answer_id": 34916908, "author": "Praveen Dhawan", "author_id": 5060168, "author_profile": "https://Stackoverflow.com/users/5060168", "pm_score": 3, "selected": false, "text": "git push -f origin branch_name\n git pull origin branch_name\n" }, { "answer_id": 37668596, "author": "ShawnFeatherly", "author_id": 228738, "author_profile": "https://Stackoverflow.com/users/228738", "pm_score": 3, "selected": false, "text": "--force-with-lease git push" }, { "answer_id": 55135753, "author": "Harshal Wani", "author_id": 2226399, "author_profile": "https://Stackoverflow.com/users/2226399", "pm_score": 0, "selected": false, "text": "git stash git commit --all --amend git log git diff HEAD^ git stash apply" }, { "answer_id": 60032800, "author": "MadPhysicist", "author_id": 5969463, "author_profile": "https://Stackoverflow.com/users/5969463", "pm_score": 1, "selected": false, "text": "git push -f origin master" }, { "answer_id": 60560824, "author": "Okan Cetin", "author_id": 9134911, "author_profile": "https://Stackoverflow.com/users/9134911", "pm_score": 3, "selected": false, "text": "git commit --amend git push --force" }, { "answer_id": 71289589, "author": "FNia", "author_id": 3092394, "author_profile": "https://Stackoverflow.com/users/3092394", "pm_score": 0, "selected": false, "text": "git update-ref HEAD HEAD^\n" }, { "answer_id": 71495523, "author": "M-Razavi", "author_id": 601288, "author_profile": "https://Stackoverflow.com/users/601288", "pm_score": 3, "selected": false, "text": "git commit --amend -m \"New message\"\n\ngit push --force repository-name branch-name\n git push --force-with-lease repository-name branch-name\n --force --force-with-lease" }, { "answer_id": 72211457, "author": "Dario Fernández", "author_id": 11751045, "author_profile": "https://Stackoverflow.com/users/11751045", "pm_score": 2, "selected": false, "text": "git commit --amend git pull git push" }, { "answer_id": 73939340, "author": "Hunter8", "author_id": 11488976, "author_profile": "https://Stackoverflow.com/users/11488976", "pm_score": 1, "selected": false, "text": "git push origin <branch-name> -f force git commit --amend git push -f ... git pull --rebase squash" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/253055", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3713/" ]
253,058
<p>Today I happens to find that one C# class can inherit one interface both in implicit and explicit way. This surprises me. If C# works in this way, then one instance can behave differently when referenced in different way.</p> <pre><code>interface IFoo { void DoSomething(); } class Foo : IFoo { #region IFoo Members public void DoSomething() { Console.WriteLine("do something implicitly"); } #endregion #region IFoo Members void IFoo.DoSomething() { Console.WriteLine("do something explicitly"); } #endregion } Foo f = new Foo(); f.DoSomething(); ((IFoo)f).DoSomething(); </code></pre> <p>Above code runs and output</p> <pre><code>do something implicitly do something explicitly </code></pre> <p>I believe that this design of C# make inconsistency of behavior. Perhaps it is mandatory that one C# class can inherit from one interface in implicit or expliict way, but not both. </p> <p>Is there any reason that why C# is designed in such a way?</p>
[ { "answer_id": 253079, "author": "François", "author_id": 32379, "author_profile": "https://Stackoverflow.com/users/32379", "pm_score": 2, "selected": false, "text": " interface IMoveable\n {\n public void Act();\n }\n\n interface IRollable\n {\n public void Act();\n }\n\n class Thing : IMoveable, IRollable\n {\n //TODO Roll/Move code here\n\n void IRollable.Act()\n {\n Roll();\n }\n\n void IMoveable.Act()\n {\n Move();\n }\n }\n" }, { "answer_id": 253083, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": false, "text": "IEnumerator IEnumerator<T> Current" }, { "answer_id": 253200, "author": "Morgan Cheng", "author_id": 26349, "author_profile": "https://Stackoverflow.com/users/26349", "pm_score": 0, "selected": false, "text": " Foo f = new Foo();\n f.DoSomething();\n Action<IFoo> func = foo => foo.DoSomething();\n func(f);\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/253058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26349/" ]
253,063
<p>Any ideas on how to disable, but not uninstall Resharper 4.x or above?</p>
[ { "answer_id": 344447, "author": "mackenir", "author_id": 25457, "author_profile": "https://Stackoverflow.com/users/25457", "pm_score": 3, "selected": false, "text": "C:\\Program\n Files\\JetBrains\\ReSharper\\v4.0\\Bin\\Product.VisualStudio.80.AddIn C:\\Program\n Files\\JetBrains\\ReSharper\\v4.0\\Bin\\Product.VisualStudio.90.AddIn" }, { "answer_id": 5200569, "author": "Oscar Mederos", "author_id": 297114, "author_profile": "https://Stackoverflow.com/users/297114", "pm_score": 4, "selected": false, "text": "ReSharper_Suspend ReSharper_Resume ReSharper_Suspend ReSharper_Resume" }, { "answer_id": 10234635, "author": "Ben Newcomb", "author_id": 703201, "author_profile": "https://Stackoverflow.com/users/703201", "pm_score": 1, "selected": false, "text": "devenv psbuild.sln /safemode\n" }, { "answer_id": 13633008, "author": "valdetero", "author_id": 1134836, "author_profile": "https://Stackoverflow.com/users/1134836", "pm_score": 3, "selected": false, "text": "\"C:\\Program Files (x86)\\Microsoft Visual Studio 11.0\\Common7\\IDE\\devenv.exe\" /Resharper.Suspend\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/253063", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3834/" ]
253,064
<p>Are there any libraries out there (preferably a self contained Text Edit Control) for .NET that have Spell Check capabilities. I would like to add the typical red underline to miss-spelled words in the edit area of my application.</p> <p>Edit: To clarify, this is for WinForms</p>
[ { "answer_id": 26321325, "author": "Steve", "author_id": 3396597, "author_profile": "https://Stackoverflow.com/users/3396597", "pm_score": 2, "selected": false, "text": "using System;\nusing System.ComponentModel;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Forms.Integration;\nusing System.Windows.Forms.Design;\n\n[Designer(typeof(ControlDesigner))]\nclass SpellCheckTextbox: ElementHost\n{\n private TextBox box;\n\n public SpellCheckTextbox()\n {\n box = new TextBox();\n base.Child = box;\n box.TextChanged += (sender, e) => OnTextChanged(EventArgs.Empty);\n box.SpellCheck.IsEnabled = true;\n box.VerticalScrollBarVisibility = ScrollBarVisibility.Hidden;\n this.Size = new System.Drawing.Size(100, 200);\n }\n public override string Text\n {\n get { return box.Text; }\n set { box.Text = value; }\n }\n\n [DefaultValue(true)]\n public bool Multiline\n {\n get { return box.AcceptsReturn; }\n set { box.AcceptsReturn = value; }\n }\n\n [DefaultValue(false)]\n public bool ScrollBars\n {\n get \n {\n if (box.VerticalScrollBarVisibility == ScrollBarVisibility.Visible ||\n box.HorizontalScrollBarVisibility == ScrollBarVisibility.Visible)\n {\n return true;\n }\n else \n {\n return false;\n }\n\n }\n set \n {\n if (value)\n {\n box.VerticalScrollBarVisibility = ScrollBarVisibility.Visible;\n box.HorizontalScrollBarVisibility = ScrollBarVisibility.Visible;\n }\n else\n {\n box.VerticalScrollBarVisibility = ScrollBarVisibility.Hidden;\n box.HorizontalScrollBarVisibility = ScrollBarVisibility.Hidden;\n }\n\n }\n }\n\n [DefaultValue(false)]\n public bool WordWrap\n {\n get { return box.TextWrapping != TextWrapping.NoWrap; }\n set { box.TextWrapping = value ? TextWrapping.Wrap : TextWrapping.NoWrap; }\n }\n\n [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]\n public new System.Windows.UIElement Child\n {\n get { return base.Child; }\n set { /* Do nothing to solve a problem with the serializer !! */ }\n }\n\n}\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/253064", "https://Stackoverflow.com", "https://Stackoverflow.com/users/194/" ]
253,066
<p>How do you debug <a href="http://java.sun.com/javase/6/docs/api/java/lang/ClassLoader.html#getResource(java.lang.String)" rel="noreferrer">getResource</a>-style methods that are failing, returning null?</p> <p>I am sure the file it's looking for is there, but it's returning NULL. How do I know what it is looking for to try to spot any mismatch?</p>
[ { "answer_id": 253448, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 4, "selected": false, "text": "getResource() getResource() log.debug(\"classpath is: \" + System.getProperty(\"java.class.path\"));\n\n//the line that is returning null\n... = Thread.currentThread().getContextClassLoader().getResource(\"foobar\");\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/253066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6068/" ]
253,075
<p>Is there a csh script/command to list all the files in source source tree which have line endings that show up as "^M" in emacs (under linux).</p> <p>Thanks!</p>
[ { "answer_id": 253084, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 0, "selected": false, "text": "find . -type f -exec grep $'\\r' {} +\n $'\\r'" }, { "answer_id": 253111, "author": "Rob Wells", "author_id": 2974, "author_profile": "https://Stackoverflow.com/users/2974", "pm_score": 0, "selected": false, "text": "find . -type f -print | xargs grep 'cntl-M$'\n" }, { "answer_id": 253130, "author": "CesarB", "author_id": 28258, "author_profile": "https://Stackoverflow.com/users/28258", "pm_score": 4, "selected": true, "text": "fgrep -rl `echo -ne '\\r'` .\n" } ]
2008/10/31
[ "https://Stackoverflow.com/questions/253075", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5775/" ]