qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
56,950
<p>We all know T-SQL's string manipulation capabilities sometimes leaves much to be desired...</p> <p>I have a numeric field that needs to be output in T-SQL as a right-aligned text column. Example:</p> <pre><code>Value ---------- 143.55 3532.13 1.75 </code></pre> <p>How would you go about that? A good solution ought to be clear and compact, but remember there is such a thing as "too clever".</p> <p>I agree this is the wrong place to do this, but sometimes we're stuck by forces outside our control.</p> <p>Thank you.</p>
[ { "answer_id": 56972, "author": "d91-jal", "author_id": 5085, "author_profile": "https://Stackoverflow.com/users/5085", "pm_score": 5, "selected": true, "text": "SELECT STR(123.45, 6, 1)\n\n------\n 123.5\n\n(1 row(s) affected)\n" }, { "answer_id": 56973, "author": "Espo", "author_id": 2257, "author_profile": "https://Stackoverflow.com/users/2257", "pm_score": 1, "selected": false, "text": "SELECT REPLICATE(' ', 40 - LEN(CAST(numColumn as varchar(40)))) + \nCAST(numColumn AS varchar(40)) FROM YourTable\n" }, { "answer_id": 56977, "author": "Josef", "author_id": 5581, "author_profile": "https://Stackoverflow.com/users/5581", "pm_score": 1, "selected": false, "text": "CREATE FUNCTION PadLeft(@PadString nvarchar(100), @PadLength int)\nRETURNS nvarchar(200)\nAS\nbegin\nreturn replicate(' ',@padlength-len(@PadString)) + @PadString\nend\ngo\nprint dbo.PadLeft('123.456', 20)\nprint dbo.PadLeft('1.23', 20)\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/56950", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2230/" ]
56,954
<p>The code</p> <pre><code>private SomeClass&lt;Integer&gt; someClass; someClass = EasyMock.createMock(SomeClass.class); </code></pre> <p>gives me a warning "Type safety: The expression of type SomeClass needs unchecked conversion to conform to SomeClass&lt;Integer&gt;".</p>
[ { "answer_id": 56996, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 2, "selected": false, "text": "private static class SomeClass_Integer extends SomeClass<Integer>();\nprivate SomeClass<Integer> someClass;\n...\n someClass = EasyMock.createMock(SomeClass_Integer.class);\n" }, { "answer_id": 57247, "author": "Cem Catikkas", "author_id": 3087, "author_profile": "https://Stackoverflow.com/users/3087", "pm_score": 2, "selected": false, "text": "@SuppressWarnings(\"unchecked\") @Test\n@SuppressWarnings(\"unchecked\")\npublic void someTest() {\n SomeClass<Integer> someClass = EasyMock.createMock(SomeClass.class);\n}\n" }, { "answer_id": 396122, "author": "Barend", "author_id": 49489, "author_profile": "https://Stackoverflow.com/users/49489", "pm_score": 5, "selected": false, "text": "SuppressWarnings SuppressWarnings public void testSomething() {\n\n @SuppressWarnings(\"unchecked\")\n Foo<Integer> foo = EasyMock.createMock(Foo.class);\n\n // Rest of test method may still expose other warnings\n}\n @SuppressWarnings(\"unchecked\")\nprivate static <T> Foo<T> createFooMock() {\n return (Foo<T>)EasyMock.createMock(Foo.class);\n}\n\npublic void testSomething() {\n Foo<String> foo = createFooMock();\n\n // Rest of test method may still expose other warnings\n}\n" }, { "answer_id": 8897152, "author": "Barry John Williams", "author_id": 1154244, "author_profile": "https://Stackoverflow.com/users/1154244", "pm_score": 4, "selected": false, "text": "private abstract class MySpecialString implements MySpecial<String>{};\n MySpecial<String> myMock = createControl().createMock(MySpecialString.class);\n" }, { "answer_id": 20427511, "author": "chim", "author_id": 673282, "author_profile": "https://Stackoverflow.com/users/673282", "pm_score": 1, "selected": false, "text": "MyItem myItem = createMock(myItem.class);\nList<MyItem> myItemList = new ArrayList<MyItem>();\nmyItemList.add(myItem);\n MyItem myItem = createMock(myItem.class);\n@SuppressWarnings(\"unchecked\")\nList<MyItem> myItemList = createMock(ArrayList.class);\nexpect(myItemList.get(0)).andReturn(myItem);\nreplay(myItemList);\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/56954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4792/" ]
56,968
<p>I'm trying to attach an instance of UIScrollbar component to a dynamic text field inside of an instance of a class that is being made after some XML is loaded. The scroll bar component is getting properly attached, as the size of the slider varies depending on the amount of content in the text field, however, it won't scroll.</p> <p>Here's the code:</p> <pre><code>function xmlLoaded(evt:Event):void { //do some stuff for(var i:int = 0; i &lt; numProfiles; i++) { var thisProfile:profile = new profile(); thisProfile.alpha = 0; thisProfile.x = 0; thisProfile.y = 0; thisProfile.name = "profile" + i; profilecontainer.addChild(thisProfile); thisProfile.profiletextholder.profilename.htmlText = profiles[i].attribute("name"); thisProfile.profiletextholder.profiletext.htmlText = profiles[i].profiletext; //add scroll bar var vScrollBar:UIScrollBar = new UIScrollBar(); vScrollBar.direction = ScrollBarDirection.VERTICAL; vScrollBar.move(thisProfile.profiletextholder.profiletext.x + thisProfile.profiletextholder.profiletext.width, thisProfile.profiletextholder.profiletext.y); vScrollBar.height = thisProfile.profiletextholder.profiletext.height; vScrollBar.scrollTarget = thisProfile.profiletextholder.profiletext; vScrollBar.name = "scrollbar"; vScrollBar.update(); vScrollBar.visible = (thisProfile.profiletextholder.profiletext.maxScrollV &gt; 1); thisProfile.profiletextholder.addChild(vScrollBar); //do some more stuff } } </code></pre> <p>I've also tried it with a UIScrollBar component within the movieclip/class itself, and it still doesn't work. Any ideas?</p>
[ { "answer_id": 74302, "author": "defmeta", "author_id": 10875, "author_profile": "https://Stackoverflow.com/users/10875", "pm_score": 0, "selected": false, "text": "vScrollBar.update(); addChild(vScollbar);" }, { "answer_id": 74342, "author": "defmeta", "author_id": 10875, "author_profile": "https://Stackoverflow.com/users/10875", "pm_score": 2, "selected": false, "text": "private function assignScrollBar(tf:TextField, sb:UIScrollBar):void {\n trace(\"assigning scrollbar\");\n sb.move(tf.x + tf.width, tf.y);\n sb.setSize(15, tf.height);\n sb.direction = ScrollBarDirection.VERTICAL;\n sb.scrollTarget = tf;\n addChild(sb);\n sb.update(); \n}\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/56968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
56,974
<p>In the following snippet:</p> <pre><code>public class a { public void otherMethod(){} public void doStuff(String str, InnerClass b){} public void method(a){ doStuff("asd", new InnerClass(){ public void innerMethod(){ otherMethod(); } } ); } } </code></pre> <p>Is there a keyword to refer to the outer class from the inner class? Basically what I want to do is <code>outer.otherMethod()</code>, or something of the like, but can't seem to find anything.</p>
[ { "answer_id": 56987, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 9, "selected": true, "text": "OuterClassName.this a.this.otherMethod()" }, { "answer_id": 56992, "author": "jjnguy", "author_id": 2598, "author_profile": "https://Stackoverflow.com/users/2598", "pm_score": 6, "selected": false, "text": "OuterClassName.this.outerClassMethod();\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/56974", "https://Stackoverflow.com", "https://Stackoverflow.com/users/292/" ]
57,002
<p>What CSS should I use to make a cell's border appear even if the cell is empty?</p> <p>IE 7 specifically.</p>
[ { "answer_id": 57006, "author": "Grant", "author_id": 30, "author_profile": "https://Stackoverflow.com/users/30", "pm_score": 7, "selected": true, "text": "&nbsp; empty-cells:hide" }, { "answer_id": 57023, "author": "Allain Lalonde", "author_id": 2443, "author_profile": "https://Stackoverflow.com/users/2443", "pm_score": 3, "selected": false, "text": "empty-cells: show \n" }, { "answer_id": 57071, "author": "rpetrich", "author_id": 4007, "author_profile": "https://Stackoverflow.com/users/4007", "pm_score": 5, "selected": false, "text": "border-collapse collapse td {\n border: 1px solid red;\n}\ntable {\n border-collapse: collapse;\n}\n<html> <head> <title>Border-collapse Test</title> <style type=\"text/css\"> td {\n border: 1px solid red;\n}\ntable {\n border-collapse: collapse;\n} <table>\n <tr>\n <td></td>\n <td>test</td>\n <td>test</td>\n </tr>\n <tr>\n <td>test</td>\n <td></td>\n <td>test</td>\n </tr>\n <tr>\n <td>test</td>\n <td></td>\n <td>test</td>\n </tr>\n <tr>\n <td>test</td>\n <td></td>\n <td />\n </tr>\n</table>" }, { "answer_id": 1199608, "author": "Rasmus", "author_id": 25792, "author_profile": "https://Stackoverflow.com/users/25792", "pm_score": 5, "selected": false, "text": " $(document).ready(function() {\n $(\"td:empty\").html(\"&nbsp;\");\n });\n" }, { "answer_id": 2546836, "author": "Sofox", "author_id": 232147, "author_profile": "https://Stackoverflow.com/users/232147", "pm_score": 0, "selected": false, "text": ".sampletable {\nborder-collapse: collapse;}\n\n.sampleTD {\nempty-cells: show;}\n" }, { "answer_id": 3613100, "author": "Crystal Jones", "author_id": 436358, "author_profile": "https://Stackoverflow.com/users/436358", "pm_score": 1, "selected": false, "text": "table {\n*border-collapse: collapse;}\n\n.sampleTD {\nempty-cells: show;}\n" }, { "answer_id": 5172978, "author": "renozu", "author_id": 641885, "author_profile": "https://Stackoverflow.com/users/641885", "pm_score": 5, "selected": false, "text": "<table border=\"1\" cellspacing=\"0\" frame=\"box\" rules=\"all\">\n" }, { "answer_id": 5574304, "author": "Voodoo", "author_id": 135476, "author_profile": "https://Stackoverflow.com/users/135476", "pm_score": 3, "selected": false, "text": "border-collapse: collapse &nbsp;" }, { "answer_id": 6157050, "author": "vol7ron", "author_id": 183181, "author_profile": "https://Stackoverflow.com/users/183181", "pm_score": 3, "selected": false, "text": "null null <div></div> <span></span> null div/span zoom:1 <table>\n <tr><td>Foo</td>\n <td><span style=\"zoom:1;\"></span></td></tr>\n</table>\n &nbsp; empty-cell:<show|hide> null" }, { "answer_id": 6763943, "author": "ruruskyi", "author_id": 372939, "author_profile": "https://Stackoverflow.com/users/372939", "pm_score": 1, "selected": false, "text": "var tn = document.createTextNode('\\ ');\nyourContainer.appendChild(ta);\n" }, { "answer_id": 15893230, "author": "JT...", "author_id": 853263, "author_profile": "https://Stackoverflow.com/users/853263", "pm_score": 1, "selected": false, "text": "<table cellspacing=\"1\" style=\"background-color:#000;\" border=\"0\"> td{background-color:#fff;}\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57002", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2443/" ]
57,004
<p>I want to create dynamic content based on this. I know it's somewhere, as web analytics engines can get this data to determine how people got to your site (referrer, search terms used, etc.), but I don't know how to get at it myself.</p>
[ { "answer_id": 57015, "author": "Espo", "author_id": 2257, "author_profile": "https://Stackoverflow.com/users/2257", "pm_score": 4, "selected": true, "text": "Request.Referer" }, { "answer_id": 57050, "author": "Jared", "author_id": 3442, "author_profile": "https://Stackoverflow.com/users/3442", "pm_score": 0, "selected": false, "text": "public void Page_Load(Object Sender, EventArgs E) {\n if (null == Session[\"source\"] || Session[\"source\"].ToString().Equals(string.Empty)) {\n if (Request.QueryString[\"src\"] != null) {\n Session[\"source\"] = Server.UrlDecode(Request.QueryString[\"src\"].ToString());\n } else {\n if (Request.UrlReferrer != null) {\n Session[\"source\"] = Request.UrlReferrer.ToString();\n } else {\n Session[\"source\"] = string.Empty;\n }\n }\n }}\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57004", "https://Stackoverflow.com", "https://Stackoverflow.com/users/572/" ]
57,010
<p>Please, now that I've re-written the question, and before it suffers from further <a href="https://stackoverflow.com/questions/56103/fastest-gun-in-the-west-problem">fast-gun answers</a> or premature closure by <a href="https://stackoverflow.com/users/905/keith">eager editors</a> let me point out that this is not a duplicate of <a href="https://stackoverflow.com/questions/9673/remove-duplicates-from-array">this question</a>. I know how to remove duplicates from an array.</p> <p>This question is about removing <strong>sequences</strong> from an array, not duplicates in the strict sense.</p> <p>Consider this sequence of elements in an array;</p> <pre><code>[0] a [1] a [2] b [3] c [4] c [5] a [6] c [7] d [8] c [9] d </code></pre> <p>In this example I want to obtain the following...</p> <pre><code>[0] a [1] b [2] c [3] a [4] c [5] d </code></pre> <p>Notice that duplicate elements are retained but that sequences of the same element have been reduced to a single instance of that element.</p> <p>Further, notice that when two lines repeat they should be reduced to one set (of two lines).</p> <pre><code>[0] c [1] d [2] c [3] d </code></pre> <p>...reduces to...</p> <pre><code>[0] c [1] d </code></pre> <p>I'm coding in C# but algorithms in any language appreciated.</p>
[ { "answer_id": 57181, "author": "nlucaroni", "author_id": 157, "author_profile": "https://Stackoverflow.com/users/157", "pm_score": 2, "selected": false, "text": "REMOVE LENGTH 2: (no other length has other matches)\n//the lower case letters are the matches\nABCBAbabaBBCbcbcbVbvBCbcbcAB \n__ABCBABABABBCBCBCBVBVBCBCBCAB\n\nREMOVE LENGTH 1 (duplicate characters):\n//* denote that a string was removed to prevent continual contraction\n//of the string, unless this is what you want.\nABCBA*BbC*V*BC*AB\n_ABCBA*BBC*V*BC*AB\n\nRESULT:\nABCBA*B*C*V*BC*AB == ABCBABCVBCAB\n" }, { "answer_id": 57410, "author": "sieben", "author_id": 1147, "author_profile": "https://Stackoverflow.com/users/1147", "pm_score": 3, "selected": true, "text": "class Program\n{\n private static List<string> values;\n private const int MAX_PATTERN_LENGTH = 4;\n\n static void Main(string[] args)\n {\n values = new List<string>();\n values.AddRange(new string[] { \"a\", \"b\", \"c\", \"c\", \"a\", \"c\", \"d\", \"c\", \"d\" });\n\n\n for (int i = MAX_PATTERN_LENGTH; i > 0; i--)\n {\n RemoveDuplicatesOfLength(i);\n }\n\n foreach (string s in values)\n {\n Console.WriteLine(s);\n }\n }\n\n private static void RemoveDuplicatesOfLength(int dupeLength)\n {\n for (int i = 0; i < values.Count; i++)\n {\n if (i + dupeLength > values.Count)\n break;\n\n if (i + dupeLength + dupeLength > values.Count)\n break;\n\n var patternA = values.GetRange(i, dupeLength);\n var patternB = values.GetRange(i + dupeLength, dupeLength);\n\n bool isPattern = ComparePatterns(patternA, patternB);\n\n if (isPattern)\n {\n values.RemoveRange(i, dupeLength);\n }\n }\n }\n\n private static bool ComparePatterns(List<string> pattern, List<string> candidate)\n {\n for (int i = 0; i < pattern.Count; i++)\n {\n if (pattern[i] != candidate[i])\n return false;\n }\n\n return true;\n }\n}\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57010", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4200/" ]
57,020
<p>Was considering the <code>System.Collections.ObjectModel ObservableCollection&lt;T&gt;</code> class. This one is strange because </p> <ul> <li>it has an Add Method which takes <strong>one</strong> item only. No AddRange or equivalent. </li> <li>the Notification event arguments has a NewItems property, which is a <strong>IList</strong> (of objects.. not T)</li> </ul> <p>My need here is to add a batch of objects to a collection and the listener also gets the batch as part of the notification. Am I missing something with ObservableCollection ? Is there another class that meets my spec?</p> <p><em>Update: Don't want to roll my own as far as feasible. I'd have to build in add/remove/change etc.. a whole lot of stuff.</em></p> <hr> <p>Related Q:<br> <a href="https://stackoverflow.com/questions/670577/observablecollection-doesnt-support-addrange-method-so-i-get-notified-for-each/670579#670579">https://stackoverflow.com/questions/670577/observablecollection-doesnt-support-addrange-method-so-i-get-notified-for-each</a></p>
[ { "answer_id": 57069, "author": "fryguybob", "author_id": 4592, "author_profile": "https://Stackoverflow.com/users/4592", "pm_score": 4, "selected": false, "text": "INotifyCollectionChanged ObservableCollection<T> AddRange AddRange ObservableCollection<T> public class MyObservableCollection<T> : ObservableCollection<T>\n{\n // matching constructors ...\n\n bool isInAddRange = false;\n\n protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)\n {\n // intercept this when it gets called inside the AddRange method.\n if (!isInAddRange) \n base.OnCollectionChanged(e);\n }\n\n\n public void AddRange(IEnumerable<T> items)\n {\n isInAddRange = true;\n foreach (T item in items)\n Add(item);\n isInAddRange = false;\n\n var e = new NotifyCollectionChangedEventArgs(\n NotifyCollectionChangedAction.Add,\n items.ToList());\n base.OnCollectionChanged(e);\n }\n}\n" }, { "answer_id": 58255, "author": "Ryan Lundy", "author_id": 5486, "author_profile": "https://Stackoverflow.com/users/5486", "pm_score": 2, "selected": false, "text": "System.Collections.ObjectModel.Collection<T>" }, { "answer_id": 61564, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": 3, "selected": false, "text": "using System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Collections.Specialized;\n\nnamespace MyNamespace\n{\n public class ObservableCollectionWithBatchUpdates<T> : ObservableCollection<T>\n {\n public void AddRange(ICollection<T> obNewItems)\n {\n IList<T> obAddedItems = new List<T>();\n foreach (T obItem in obNewItems)\n {\n Items.Add(obItem);\n obAddedItems.Add(obItem);\n }\n NotifyCollectionChangedEventArgs obEvtArgs = new NotifyCollectionChangedEventArgs(\n NotifyCollectionChangedAction.Add, \n obAddedItems as System.Collections.IList);\n base.OnCollectionChanged(obEvtArgs);\n }\n\n }\n}\n" }, { "answer_id": 851197, "author": "Sam Saffron", "author_id": 17174, "author_profile": "https://Stackoverflow.com/users/17174", "pm_score": 2, "selected": false, "text": " public void AddRange(IEnumerable<T> collection)\n {\n foreach (var i in collection) Items.Add(i);\n OnPropertyChanged(\"Count\");\n OnPropertyChanged(\"Item[]\");\n OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));\n }\n" }, { "answer_id": 1790438, "author": "Boris", "author_id": 217845, "author_profile": "https://Stackoverflow.com/users/217845", "pm_score": 0, "selected": false, "text": "((List<Person>)this.Items).AddRange(NewItems);\n" }, { "answer_id": 3829525, "author": "Akash Kava", "author_id": 85597, "author_profile": "https://Stackoverflow.com/users/85597", "pm_score": 2, "selected": false, "text": "BindingList<T>" }, { "answer_id": 8837627, "author": "Mo0gles", "author_id": 283512, "author_profile": "https://Stackoverflow.com/users/283512", "pm_score": 2, "selected": false, "text": "public class DeferableObservableCollection<T> : ObservableCollection<T>\n{\n private int deferLevel;\n\n private class DeferHelper<T> : IDisposable\n {\n private DeferableObservableCollection<T> owningCollection;\n public DeferHelper(DeferableObservableCollection<T> owningCollection)\n {\n this.owningCollection = owningCollection;\n }\n\n public void Dispose()\n {\n owningCollection.EndDefer();\n }\n }\n\n private void EndDefer()\n {\n if (--deferLevel <= 0)\n {\n deferLevel = 0;\n OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));\n }\n }\n\n public IDisposable DeferNotifications()\n {\n deferLevel++;\n return new DeferHelper<T>(this);\n }\n\n protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)\n {\n if (deferLevel == 0) // Not in a defer just send events as normally\n {\n base.OnCollectionChanged(e);\n } // Else notify on EndDefer\n }\n}\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57020", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1695/" ]
57,053
<p>I am writing some software to identify tracking numbers (in the same way that Google identifies FedEx or UPS numbers when you search for them). Most couriers use a system, such as a "weighted average mod system" which can be used to identify if a number is a valid tracking number. Does anyone know if TNT consignment numbers use such a system, and if so, what it is? I have asked TNT support, and the rep told me they do not... but I'd like to doublecheck.</p>
[ { "answer_id": 19512345, "author": "user2902405", "author_id": 2902405, "author_profile": "https://Stackoverflow.com/users/2902405", "pm_score": 0, "selected": false, "text": " Dim number As String = TextBox1.Text\n Dim A As Integer\n Dim B As Integer\n Dim C As Integer\n Dim check_digit As Integer\n\n A = (CInt(Mid(number, 1, 1)) * 8) + (CInt(Mid(number, 2, 1)) * 6) + (CInt(Mid(number, 3, 1)) * 4) + (CInt(Mid(number, 4, 1)) * 2) + (CInt(Mid(number, 5, 1)) * 3) + (CInt(Mid(number, 6, 1)) * 5) + (CInt(Mid(number, 7, 1)) * 9) + (CInt(Mid(number, 8, 1)) * 7)\n B = ((A \\ 11) * 11)\n C = A - B\n\n If C = 0 Then\n check_digit = 5\n End If\n\n If C = 1 Then\n check_digit = 0\n End If\n\n If C <> 0 And C <> 1 Then\n check_digit = 11 - C\n End If\n\n MsgBox(number & check_digit)\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57053", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4939/" ]
57,054
<p>I've got a collection that implements an interface that extends both IList&lt;T> and List. </p> <pre><code>public Interface IMySpecialCollection : IList&lt;MyObject&gt;, IList { ... } </code></pre> <p>That means I have two versions of the indexer. </p> <p>I wish the generic implementation to be used, so I implement that one normally:</p> <pre><code>public MyObject this[int index] { .... } </code></pre> <p>I only need the IList version for serialization, so I implement it explicitly, to keep it hidden:</p> <pre><code>object IList.this[int index] { ... } </code></pre> <p>However, in my unit tests, the following</p> <pre><code>MyObject foo = target[0]; </code></pre> <p>results in a compiler error</p> <blockquote> <p>The call is ambiguous between the following methods or properties</p> </blockquote> <p>I'm a bit surprised at this; I believe I've done it before and it works fine. What am I missing here? How can I get IList&lt;T> and IList to coexist within the same interface?</p> <p><strong>Edit</strong> IList&lt;T> does <em>not</em> implement IList, and I <strong>must</strong> implement IList for serialization. I'm not interested in workarounds, I want to know what I'm missing.</p> <p><strong>Edit again</strong>: I've had to drop IList from the interface and move it on my class. I don't want to do this, as classes that implement the interface are eventually going to be serialized to Xaml, which requires collections to implement IDictionary or IList...</p>
[ { "answer_id": 57093, "author": "Jarrett Meyer", "author_id": 5834, "author_profile": "https://Stackoverflow.com/users/5834", "pm_score": -1, "selected": false, "text": "T IList<T>.this[int index] { get; set; }\n" }, { "answer_id": 57166, "author": "Darryl Braaten", "author_id": 1834, "author_profile": "https://Stackoverflow.com/users/1834", "pm_score": 3, "selected": true, "text": "public interface IMySpecialCollection : IList<MyObject>, IList { ... } public class MySpecialCollection : IList<MyObject>, IList { ... } IList<object> myspecialcollection = new MySpecialCollection();\n IList list = (IList)myspecialcollection;" }, { "answer_id": 1669935, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 2, "selected": false, "text": "public Interface IMySpecialCollection : IList<MyObject>, IList\n{\n new MyObject this[int index];\n ... \n}\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57054", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
57,091
<p>Let's say I have a parent DIV. Inside, there are three child DIVs: header, content and footer. Header is attached to the top of the parent and fills it horizontally. Footer is attached to the bottom of the parent and fills it horizontally too. Content is supposed to fill all the space between header and footer.</p> <p>The parent has to have a fixed width and height. The content DIV has to fill all available space between header and footer. When the content size of the content DIV exceeds the space between header and footer, <strong><em>the content DIV should display scrollbars and allow appropriate scrolling</em></strong> so that the footer contents should never be obscured nor the footer obscure content.</p> <p>Now comes the hard part: <strong><em>you don't know the height of the header nor footer beforehand</em></strong> (eg. header and footer are filled dynamically). How can content be positioned <strong><em>without using JavaScript</em></strong>?</p> <p>Example:</p> <pre><code>&lt;div style="position : relative; width : 200px; height : 200px; background-color : #e0e0ff; overflow : hidden;"&gt; &lt;div style="background-color: #80ff80; position : absolute; left : 0; right : 0; top : 0;"&gt; header &lt;/div&gt; &lt;div style="background-color: #8080ff; overflow : auto; position : absolute;"&gt; content (how to position it?) &lt;/div&gt; &lt;div style="background-color: #ff8080; position : absolute; bottom : 0px; left :0; right : 0;"&gt; footer &lt;/div&gt; &lt;/div&gt; </code></pre> <hr> <p><strong>To clarify this event further</strong> - the target layout that I'm trying to achieve will be used in a business web application. <strong><em>The parent DIV will have a fixed, but unknown size</em></strong> (for instance, it will be exactly the size of the browser viewport, sizing itself along with sizing the browser window by the user). Let's call the parent DIV a "screen".</p> <p>The header will contain a set of filtering controls (like textboxes, drop down lists and a "filter" button) that should wrap to the next line if there is insufficient horizontal space (so its height can change any time to accomodate line breaking). <strong><em>The header should always be visible and attached to the top</em></strong> of the "screen".</p> <p>The footer will contain a set of buttons, like on a dialog window. These too can wrap to next line if there is not enough space horizontally. <strong><em>The footer must be attached to the bottom</em></strong> of the "screen" to be accessible and visible at all times.</p> <p>The content will contain "screen" contents, like dialog fields etc. If there are too few fields, the rest of the content will be "blank" (in this case the footer should not begin right after the content, but still be attached to the bottom of the "screen" which is fixed size). If there are too many fields, <strong><em>the content DIV will provide scrollbar(s)</em></strong> to access the hidden controls (in this case the content DIV must not extend itself below the footer, as the scrollbar would be partially hidden). </p> <p>I hope this clarifies the question a little bit further, as I have too low rep to enter comments to your repsonses.</p>
[ { "answer_id": 57119, "author": "rpetrich", "author_id": 4007, "author_profile": "https://Stackoverflow.com/users/4007", "pm_score": 0, "selected": false, "text": "<div id=\"wrapper\">\n <div id=\"header\">\n header\n </div>\n <div id=\"content\">\n content\n </div>\n <div id=\"footer\">\n footer\n </div>\n</div>\n #wrapper {\n width: 200px;\n height: 200px;\n overflow: visible;\n background: #e0e0ff;\n}\n#header {\n background: #80ff80;\n}\n#content {\n background: #8080ff;\n}\n#footer {\n background: #ff8080;\n}\n" }, { "answer_id": 57121, "author": "busse", "author_id": 5702, "author_profile": "https://Stackoverflow.com/users/5702", "pm_score": 0, "selected": false, "text": "<div style=\"position : relative; width : 200px; background-color : #e0e0ff; overflow : hidden;\">\n<div style=\"float: left; clear: left; background-color: #80ff80;\">\nheader \n</div>\n<div style=\"float: left; clear: left; background-color: #8080ff; overflow : auto; \">\ncontent (how to position it?)\n<BR />taller\n<BR />taller\n<BR />taller\n<BR />taller\n<BR />taller\n<BR />taller\n<BR />taller\n<BR />taller\n</div>\n<div style=\"float: left; clear: left; background-color: #ff8080;\">\nfooter \n<BR />taller\n</div> \n <div style=\"position : relative; width : 200px; height : 200px; background-color : #e0e0ff; overflow : hidden;\">\n<div style=\"float: left; clear: left; background-color: #80ff80; \">\nheader <BR .> taller\n</div>\n<div style=\"float: left; clear: left; background-color: #8080ff; overflow : auto; \">\ncontent (how to position it?)<BR /> and another line\n</div>\n<div style=\"background-color: #ff8080; position : absolute; bottom : 0px; left :0; right : 0;\">\nfooter <BR /> taller\n</div> \n" }, { "answer_id": 21977077, "author": "pschueller", "author_id": 2126792, "author_profile": "https://Stackoverflow.com/users/2126792", "pm_score": 2, "selected": false, "text": "display: flex; flex-direction: column; justify content: space-between; height: 100vh; flex: 1 0 0; overflow-y: auto; -webkit- -ms- body {\n display: -webkit-flex; /* Safari 6.1+ */\n display: -ms-flex; /* IE 10 */ \n display: flex;\n -webkit-flex-direction: column; /* Safari 6.1+ */\n -ms-flex-direction: column; /* IE 10 */\n flex-direction: column;\n -webkit-justify-content: space-between; /* Safari 6.1+ */\n -ms-justify-content: space-between; /* IE 10 */\n justify-content: space-between; /* Header top, footer bottom */\n height: 100vh; /* Fill viewport height */\n}\nmain {\n -webkit-flex: 1 0 0; /* Safari 6.1+ */\n -ms-flex: 1 0 0; /* IE 10 */\n flex: 1 0 0; /* Grow to fill space */\n overflow-y: auto; /* Add scrollbar */\n height: 100%; /* Needed to fill space in IE */\n}\nheader, footer {\n -webkit-flex: 0 0 auto; /* Safari 6.1+ */\n -ms-flex: 0 0 auto; /* IE 10 */\n flex: 0 0 auto;\n}\n\n\n\n/* Make it look a little nicer */\nbody {\n margin: 0;\n background-color: #8080ff;\n}\nheader {\n background-color: #80ff80; \n}\nfooter {\n background-color: #ff8080;\n}\np {\n margin: 1.25rem;\n} <body>\n <header>\n <p>header</p> \n </header>\n <main>\n <article>\n <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam pellentesque lobortis augue, in porta arcu dapibus dapibus. Suspendisse vulputate tempus venenatis. Pellentesque ac euismod urna. Donec dui odio, ullamcorper in posuere eu, laoreet sed nisl. Sed vitae vestibulum leo. Maecenas mattis lacus eget nisl malesuada, quis semper urna ornare. Praesent id mauris nec neque aliquet dignissim.</p>\n <p>Morbi varius dolor at lorem aliquet lacinia. Aliquam id lacinia quam. Sed vel libero felis. Etiam et pellentesque sem. Aenean bibendum, ante quis luctus tincidunt, elit mauris volutpat nisi, et tempus lectus sapien in mauris. Aliquam condimentum nisl ut elit accumsan hendrerit. Morbi mollis turpis est, id tincidunt ipsum rhoncus eget. Fusce in feugiat lacus. Quisque vel massa magna. Mauris varius congue nisl, vitae pellentesque diam ultricies at. Sed ac nibh ac diam tristique venenatis non nec nisl. Vivamus enim eros, pretium at iaculis nec, pharetra non sem. Aenean ac imperdiet odio.</p>\n <p>Morbi varius dolor at lorem aliquet lacinia. Aliquam id lacinia quam. Sed vel libero felis. Etiam et pellentesque sem. Aenean bibendum, ante quis luctus tincidunt, elit mauris volutpat nisi, et tempus lectus sapien in mauris. Aliquam condimentum nisl ut elit accumsan hendrerit. Morbi mollis turpis est, id tincidunt ipsum rhoncus eget. Fusce in feugiat lacus. Quisque vel massa magna. Mauris varius congue nisl, vitae pellentesque diam ultricies at. Sed ac nibh ac diam tristique venenatis non nec nisl. Vivamus enim eros, pretium at iaculis nec, pharetra non sem. Aenean ac imperdiet odio.</p>\n </article>\n </main>\n <footer>\n <p>footer</p> \n </footer>\n</body> display: table; <div id=\"screen\">\n <div id=\"header\"></div>\n <div id=\"content\">\n <div id=\"content_frame\">\n <div id=\"content_wrap\"></div>\n </div>\n </div>\n <div id=\"footer\"></div>\n</div>\n html, body, #screen, #content, #content_frame {\n height: 100%; /* Make #screen viewport height and #content fill space */\n}\n#screen {\n display: table;\n}\n#header, #content, #footer {\n display: table-row;\n}\n#content_frame {\n overflow-y: auto; /* Add scrollbar */\n position: relative;\n}\n#content_wrap {\n position: absolute; /* Fix problem with overflow in FF */\n}\n position: absolute;" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57091", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5348/" ]
57,094
<p>I have ASP.NET web pages for which I want to build automated tests (using WatiN &amp; MBUnit). How do I start the ASP.Net Development Server from my code? I do not want to use IIS.</p>
[ { "answer_id": 57105, "author": "Dillie-O", "author_id": 71, "author_profile": "https://Stackoverflow.com/users/71", "pm_score": 4, "selected": true, "text": "C:\\Windows\\Microsoft.NET\\Framework\\v2.0.50727\\Webdev.WebServer.exe /port:[PORT NUMBER] /path: [PATH TO ROOT]\n" }, { "answer_id": 57890, "author": "Ray", "author_id": 4872, "author_profile": "https://Stackoverflow.com/users/4872", "pm_score": 3, "selected": false, "text": "using System;\nusing System.Diagnostics;\nusing System.Web;\n...\n\n// settings\nstring PortNumber = \"1162\"; // arbitrary unused port #\nstring LocalHostUrl = string.Format(\"http://localhost:{0}\", PortNumber);\nstring PhysicalPath = Environment.CurrentDirectory // the path of compiled web app\nstring VirtualPath = \"\";\nstring RootUrl = LocalHostUrl + VirtualPath; \n\n// create a new process to start the ASP.NET Development Server\nProcess process = new Process();\n\n/// configure the web server\nprocess.StartInfo.FileName = HttpRuntime.ClrInstallDirectory + \"WebDev.WebServer.exe\";\nprocess.StartInfo.Arguments = string.Format(\"/port:{0} /path:\\\"{1}\\\" /virtual:\\\"{2}\\\"\", PortNumber, PhysicalPath, VirtualPath);\nprocess.StartInfo.CreateNoWindow = true;\nprocess.StartInfo.UseShellExecute = false;\n\n// start the web server\nprocess.Start();\n\n// rest of code...\n" }, { "answer_id": 19845812, "author": "Michael Sorens", "author_id": 115690, "author_profile": "https://Stackoverflow.com/users/115690", "pm_score": 1, "selected": false, "text": "public void LaunchWebServer(string appWebDir)\n{\n var PortNumber = \"1162\"; // arbitrary unused port #\n var LocalHostUrl = string.Format(\"http://localhost:{0}\", PortNumber);\n var VirtualPath = \"/\";\n\n var exePath = FindLatestWebServer();\n\n var process = new Process\n {\n StartInfo =\n {\n FileName = exePath,\n Arguments = string.Format(\n \"/port:{0} /nodirlist /path:\\\"{1}\\\" /virtual:\\\"{2}\\\"\",\n PortNumber, appWebDir, VirtualPath),\n CreateNoWindow = true,\n UseShellExecute = false\n }\n };\n process.Start();\n}\n\nprivate string FindLatestWebServer()\n{\n var exeCandidates = new List<string>\n {\n BuildCandidatePaths(11, true), // vs2012\n BuildCandidatePaths(11, false),\n BuildCandidatePaths(10, true), // vs2010\n BuildCandidatePaths(10, false)\n };\n return exeCandidates.Where(f => File.Exists(f)).FirstOrDefault();\n}\n\nprivate string BuildCandidatePaths(int versionNumber, bool isX64)\n{\n return Path.Combine(\n Environment.GetFolderPath(isX64\n ? Environment.SpecialFolder.CommonProgramFiles\n : Environment.SpecialFolder.CommonProgramFilesX86),\n string.Format(\n @\"microsoft shared\\DevServer\\{0}.0\\WebDev.WebServer40.EXE\",\n versionNumber));\n}\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57094", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4872/" ]
57,104
<p>I'm going to be starting a project soon that requires support for large-ish binary files. I'd like to use Ruby on Rails for the webapp, but I'm concerned with the BLOB support. In my experience with other languages, frameworks, and databases, BLOBs are often overlooked and thus have poor, difficult, and/or buggy functionality.</p> <p>Does RoR spport BLOBs adequately? Are there any gotchas that creep up once you're already committed to Rails?</p> <p>BTW: I want to be using PostgreSQL and/or MySQL as the backend database. Obviously, BLOB support in the underlying database is important. For the moment, I want to avoid focusing on the DB's BLOB capabilities; I'm more interested in how Rails itself reacts. Ideally, Rails should be hiding the details of the database from me, and so I should be able to switch from one to the other. If this is <em>not</em> the case (ie: there's some problem with using Rails with a particular DB) then please do mention it. </p> <p>UPDATE: Also, I'm not just talking about ActiveRecord here. I'll need to handle binary files on the HTTP side (file upload effectively). That means getting access to the appropriate HTTP headers and streams via Rails. I've updated the question title and description to reflect this.</p>
[ { "answer_id": 57201, "author": "John Topley", "author_id": 1450, "author_profile": "https://Stackoverflow.com/users/1450", "pm_score": 3, "selected": false, "text": ":binary class BlobTest < ActiveRecord::Migration\n def self.up\n create_table :files do |t|\n t.column :file_data, :binary, :limit => 1.megabyte\n end\n end\nend\n" }, { "answer_id": 57608, "author": "Matt Rogish", "author_id": 2590, "author_profile": "https://Stackoverflow.com/users/2590", "pm_score": 4, "selected": true, "text": "<%= image_tag @youruser.avatar.path %>\n send_data(@youruser.avatar.current_data, :type => @youruser.avatar.content_type, :filename => @youruser.avatar.filename, :disposition => 'inline' )\n" }, { "answer_id": 58377, "author": "Jim Puls", "author_id": 6010, "author_profile": "https://Stackoverflow.com/users/6010", "pm_score": 4, "selected": false, "text": "render :text => render :content_type => 'application/octet-stream', :text => Proc.new {\n |response, output|\n # do something that reads data and writes it to output\n}\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57104", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3488/" ]
57,124
<p>I know I can call the GetVersionEx Win32 API function to retrieve Windows version. In most cases returned value reflects the version of my Windows, but sometimes that is not so.</p> <p>If a user runs my application under the compatibility layer, then GetVersionEx won't be reporting the real version but the version enforced by the compatibility layer. For example, if I'm running Vista and execute my program in "Windows NT 4" compatibility mode, GetVersionEx won't return version 6.0 but 4.0.</p> <p>Is there a way to bypass this behaviour and get true Windows version?</p>
[ { "answer_id": 57128, "author": "EBGreen", "author_id": 1358, "author_profile": "https://Stackoverflow.com/users/1358", "pm_score": 5, "selected": false, "text": "\"Select * from Win32_OperatingSystem\"\n \"Select Version from Win32_OperatingSystem\"\n function OperatingSystemDisplayName: string;\n\n function GetWMIObject(const objectName: string): IDispatch;\n var\n chEaten: Integer;\n BindCtx: IBindCtx;\n Moniker: IMoniker;\n begin\n OleCheck(CreateBindCtx(0, bindCtx));\n OleCheck(MkParseDisplayName(BindCtx, PChar(objectName), chEaten, Moniker));\n OleCheck(Moniker.BindToObject(BindCtx, nil, IDispatch, Result));\n end;\n\n function VarToString(const Value: OleVariant): string;\n begin\n if VarIsStr(Value) then begin\n Result := Trim(Value);\n end else begin\n Result := '';\n end;\n end;\n\n function FullVersionString(const Item: OleVariant): string;\n var\n Caption, ServicePack, Version, Architecture: string;\n begin\n Caption := VarToString(Item.Caption);\n ServicePack := VarToString(Item.CSDVersion);\n Version := VarToString(Item.Version);\n Architecture := ArchitectureDisplayName(SystemArchitecture);\n Result := Caption;\n if ServicePack <> '' then begin\n Result := Result + ' ' + ServicePack;\n end;\n Result := Result + ', version ' + Version + ', ' + Architecture;\n end;\n\nvar\n objWMIService: OleVariant;\n colItems: OleVariant;\n Item: OleVariant;\n oEnum: IEnumvariant;\n iValue: LongWord;\n\nbegin\n Try\n objWMIService := GetWMIObject('winmgmts:\\\\localhost\\root\\cimv2');\n colItems := objWMIService.ExecQuery('SELECT Caption, CSDVersion, Version FROM Win32_OperatingSystem', 'WQL', 0);\n oEnum := IUnknown(colItems._NewEnum) as IEnumVariant;\n if oEnum.Next(1, Item, iValue)=0 then begin\n Result := FullVersionString(Item);\n exit;\n end;\n Except\n // yes, I know this is nasty, but come what may I want to use the fallback code below should the WMI code fail\n End;\n\n (* Fallback, relies on the deprecated function GetVersionEx, reports erroneous values\n when manifest does not contain supportedOS matching the executing system *)\n Result := TOSVersion.ToString;\nend;\n" }, { "answer_id": 57130, "author": "gabr", "author_id": 4997, "author_profile": "https://Stackoverflow.com/users/4997", "pm_score": 6, "selected": true, "text": "TDSiWindowsVersion = (wvUnknown, wvWin31, wvWin95, wvWin95OSR2, wvWin98,\n wvWin98SE, wvWinME, wvWin9x, wvWinNT3, wvWinNT4, wvWin2000, wvWinXP,\n wvWinNT, wvWinServer2003, wvWinVista);\n\nfunction DSiGetWindowsVersion: TDSiWindowsVersion;\nvar\n versionInfo: TOSVersionInfo;\nbegin\n versionInfo.dwOSVersionInfoSize := SizeOf(versionInfo);\n GetVersionEx(versionInfo);\n Result := wvUnknown;\n case versionInfo.dwPlatformID of\n VER_PLATFORM_WIN32s: Result := wvWin31;\n VER_PLATFORM_WIN32_WINDOWS:\n case versionInfo.dwMinorVersion of\n 0:\n if Trim(versionInfo.szCSDVersion[1]) = 'B' then\n Result := wvWin95OSR2\n else\n Result := wvWin95;\n 10:\n if Trim(versionInfo.szCSDVersion[1]) = 'A' then\n Result := wvWin98SE\n else\n Result := wvWin98;\n 90:\n if (versionInfo.dwBuildNumber = 73010104) then\n Result := wvWinME;\n else\n Result := wvWin9x;\n end; //case versionInfo.dwMinorVersion\n VER_PLATFORM_WIN32_NT:\n case versionInfo.dwMajorVersion of\n 3: Result := wvWinNT3;\n 4: Result := wvWinNT4;\n 5:\n case versionInfo.dwMinorVersion of\n 0: Result := wvWin2000;\n 1: Result := wvWinXP;\n 2: Result := wvWinServer2003;\n else Result := wvWinNT\n end; //case versionInfo.dwMinorVersion\n 6: Result := wvWinVista;\n end; //case versionInfo.dwMajorVersion\n end; //versionInfo.dwPlatformID\nend; { DSiGetWindowsVersion }\n\nfunction DSiGetTrueWindowsVersion: TDSiWindowsVersion;\n\n function ExportsAPI(module: HMODULE; const apiName: string): boolean;\n begin\n Result := GetProcAddress(module, PChar(apiName)) <> nil;\n end; { ExportsAPI }\n\nvar\n hKernel32: HMODULE;\n\nbegin { DSiGetTrueWindowsVersion }\n hKernel32 := GetModuleHandle('kernel32');\n Win32Check(hKernel32 <> 0);\n if ExportsAPI(hKernel32, 'GetLocaleInfoEx') then\n Result := wvWinVista\n else if ExportsAPI(hKernel32, 'GetLargePageMinimum') then\n Result := wvWinServer2003\n else if ExportsAPI(hKernel32, 'GetNativeSystemInfo') then\n Result := wvWinXP\n else if ExportsAPI(hKernel32, 'ReplaceFile') then\n Result := wvWin2000\n else if ExportsAPI(hKernel32, 'OpenThread') then\n Result := wvWinME\n else if ExportsAPI(hKernel32, 'GetThreadPriorityBoost') then\n Result := wvWinNT4\n else if ExportsAPI(hKernel32, 'IsDebuggerPresent') then //is also in NT4!\n Result := wvWin98\n else if ExportsAPI(hKernel32, 'GetDiskFreeSpaceEx') then //is also in NT4!\n Result := wvWin95OSR2\n else if ExportsAPI(hKernel32, 'ConnectNamedPipe') then\n Result := wvWinNT3\n else if ExportsAPI(hKernel32, 'Beep') then\n Result := wvWin95\n else // we have no idea\n Result := DSiGetWindowsVersion;\nend; { DSiGetTrueWindowsVersion }\n" }, { "answer_id": 57326, "author": "botismarius", "author_id": 4528, "author_profile": "https://Stackoverflow.com/users/4528", "pm_score": 3, "selected": false, "text": "HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\ProductName\n HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\n" }, { "answer_id": 8123929, "author": "Warren P", "author_id": 84704, "author_profile": "https://Stackoverflow.com/users/84704", "pm_score": 1, "selected": false, "text": "GetVersionEx GetWindowsVersion TWindowsVersion =\n (wvUnknown, wvWin95, wvWin95OSR2, wvWin98, wvWin98SE, wvWinME,\n wvWinNT31, wvWinNT35, wvWinNT351, wvWinNT4, wvWin2000, wvWinXP,\n wvWin2003, wvWinXP64, wvWin2003R2, wvWinVista, wvWinServer2008,\n wvWin7, wvWinServer2008R2);\n JclSysInfo.IsWindows64 TWindowsEdition =\n (weUnknown, weWinXPHome, weWinXPPro, weWinXPHomeN, weWinXPProN, weWinXPHomeK,\n weWinXPProK, weWinXPHomeKN, weWinXPProKN, weWinXPStarter, weWinXPMediaCenter,\n weWinXPTablet, weWinVistaStarter, weWinVistaHomeBasic, weWinVistaHomeBasicN,\n weWinVistaHomePremium, weWinVistaBusiness, weWinVistaBusinessN,\n weWinVistaEnterprise, weWinVistaUltimate, weWin7Starter, weWin7HomeBasic,\n weWin7HomePremium, weWin7Professional, weWin7Enterprise, weWin7Ultimate);\n TNtProductType =       (ptUnknown, ptWorkStation, ptServer, ptAdvancedServer,        \n ptPersonal, ptProfessional, ptDatacenterServer, \n ptEnterprise, ptWebEdition);\n function IsSupported:Boolean;\nbegin\n case GetWindowsVersion of\n wvVista: result := false; \n else\n result := true;\n end;\nend;\n path Win32_OperatingSystem" }, { "answer_id": 24345510, "author": "Victor Fedorenkov", "author_id": 3763602, "author_profile": "https://Stackoverflow.com/users/3763602", "pm_score": 3, "selected": false, "text": "unit RealWindowsVerUnit;\n\ninterface\n\nuses\n Windows;\n\nvar\n //Real version Windows\n Win32MajorVersionReal: Integer;\n Win32MinorVersionReal: Integer;\n\nimplementation\n\ntype\n PPEB=^PEB;\n PEB = record\n InheritedAddressSpace: Boolean;\n ReadImageFileExecOptions: Boolean;\n BeingDebugged: Boolean;\n Spare: Boolean;\n Mutant: Cardinal;\n ImageBaseAddress: Pointer;\n LoaderData: Pointer;\n ProcessParameters: Pointer; //PRTL_USER_PROCESS_PARAMETERS;\n SubSystemData: Pointer;\n ProcessHeap: Pointer;\n FastPebLock: Pointer;\n FastPebLockRoutine: Pointer;\n FastPebUnlockRoutine: Pointer;\n EnvironmentUpdateCount: Cardinal;\n KernelCallbackTable: PPointer;\n EventLogSection: Pointer;\n EventLog: Pointer;\n FreeList: Pointer; //PPEB_FREE_BLOCK;\n TlsExpansionCounter: Cardinal;\n TlsBitmap: Pointer;\n TlsBitmapBits: array[0..1] of Cardinal;\n ReadOnlySharedMemoryBase: Pointer;\n ReadOnlySharedMemoryHeap: Pointer;\n ReadOnlyStaticServerData: PPointer;\n AnsiCodePageData: Pointer;\n OemCodePageData: Pointer;\n UnicodeCaseTableData: Pointer;\n NumberOfProcessors: Cardinal;\n NtGlobalFlag: Cardinal;\n Spare2: array[0..3] of Byte;\n CriticalSectionTimeout: LARGE_INTEGER;\n HeapSegmentReserve: Cardinal;\n HeapSegmentCommit: Cardinal;\n HeapDeCommitTotalFreeThreshold: Cardinal;\n HeapDeCommitFreeBlockThreshold: Cardinal;\n NumberOfHeaps: Cardinal;\n MaximumNumberOfHeaps: Cardinal;\n ProcessHeaps: Pointer;\n GdiSharedHandleTable: Pointer;\n ProcessStarterHelper: Pointer;\n GdiDCAttributeList: Pointer;\n LoaderLock: Pointer;\n OSMajorVersion: Cardinal;\n OSMinorVersion: Cardinal;\n OSBuildNumber: Cardinal;\n OSPlatformId: Cardinal;\n ImageSubSystem: Cardinal;\n ImageSubSystemMajorVersion: Cardinal;\n ImageSubSystemMinorVersion: Cardinal;\n GdiHandleBuffer: array [0..33] of Cardinal;\n PostProcessInitRoutine: Cardinal;\n TlsExpansionBitmap: Cardinal;\n TlsExpansionBitmapBits: array [0..127] of Byte;\n SessionId: Cardinal;\n end;\n\n//Get PEB block current win32 process\nfunction GetPDB: PPEB; stdcall;\nasm\n MOV EAX, DWORD PTR FS:[30h]\nend;\n\ninitialization\n //Detect true windows wersion\n Win32MajorVersionReal := GetPDB^.OSMajorVersion;\n Win32MinorVersionReal := GetPDB^.OSMinorVersion;\nend.\n" }, { "answer_id": 31755501, "author": "FredS", "author_id": 5042682, "author_profile": "https://Stackoverflow.com/users/5042682", "pm_score": 1, "selected": false, "text": "function GetWinVersion: string;\nvar\n Buffer: PServerInfo101;\nbegin\n Buffer := nil;\n if NetServerGetInfo(nil, 101, Pointer(Buffer)) = NO_ERROR then\n try\n Result := <Build You Version String here>(\n Buffer.sv101_version_major,\n Buffer.sv101_version_minor,\n VER_PLATFORM_WIN32_NT // Save since minimum support begins in W2K\n );\n finally\n NetApiBufferFree(Buffer);\n end;\nend;\n" }, { "answer_id": 31756711, "author": "Remy Lebeau", "author_id": 65863, "author_profile": "https://Stackoverflow.com/users/65863", "pm_score": 3, "selected": false, "text": "uses\n System.SysUtils, Winapi.Windows;\n\ntype\n NET_API_STATUS = DWORD;\n\n _SERVER_INFO_101 = record\n sv101_platform_id: DWORD;\n sv101_name: LPWSTR;\n sv101_version_major: DWORD;\n sv101_version_minor: DWORD;\n sv101_type: DWORD;\n sv101_comment: LPWSTR;\n end;\n SERVER_INFO_101 = _SERVER_INFO_101;\n PSERVER_INFO_101 = ^SERVER_INFO_101;\n LPSERVER_INFO_101 = PSERVER_INFO_101;\n\nconst\n MAJOR_VERSION_MASK = $0F;\n\nfunction NetServerGetInfo(servername: LPWSTR; level: DWORD; var bufptr): NET_API_STATUS; stdcall; external 'Netapi32.dll';\nfunction NetApiBufferFree(Buffer: LPVOID): NET_API_STATUS; stdcall; external 'Netapi32.dll';\n\ntype\n pfnRtlGetVersion = function(var RTL_OSVERSIONINFOEXW): LONG; stdcall;\nvar\n Buffer: PSERVER_INFO_101;\n ver: RTL_OSVERSIONINFOEXW;\n RtlGetVersion: pfnRtlGetVersion;\nbegin\n Buffer := nil;\n\n // Win32MajorVersion and Win32MinorVersion are populated from GetVersionEx()...\n ShowMessage(Format('GetVersionEx: %d.%d', [Win32MajorVersion, Win32MinorVersion])); // shows 6.2, as expected per GetVersionEx() documentation\n\n @RtlGetVersion := GetProcAddress(GetModuleHandle('ntdll.dll'), 'RtlGetVersion');\n if Assigned(RtlGetVersion) then\n begin\n ZeroMemory(@ver, SizeOf(ver));\n ver.dwOSVersionInfoSize := SizeOf(ver);\n\n if RtlGetVersion(ver) = 0 then\n ShowMessage(Format('RtlGetVersion: %d.%d', [ver.dwMajorVersion, ver.dwMinorVersion])); // shows 10.0\n end;\n\n if NetServerGetInfo(nil, 101, Buffer) = NO_ERROR then\n try\n ShowMessage(Format('NetServerGetInfo: %d.%d', [Buffer.sv101_version_major and MAJOR_VERSION_MASK, Buffer.sv101_version_minor])); // shows 10.0\n finally\n NetApiBufferFree(Buffer);\n end;\nend.\n NetWkstaGetInfo()" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4997/" ]
57,137
<p>I recently upgraded to Subversion 1.5, and now I cannot commit my code to the repository. I get an error message: "403 Forbidden in response to MKACTIVITY". I know the upgrade worked because my fellow developers are not getting this issue. What's going on?</p>
[ { "answer_id": 29477185, "author": "Eve", "author_id": 713790, "author_profile": "https://Stackoverflow.com/users/713790", "pm_score": 0, "selected": false, "text": "subclipse 1.4 svn 1.4.3" }, { "answer_id": 44561204, "author": "user55926", "author_id": 3000788, "author_profile": "https://Stackoverflow.com/users/3000788", "pm_score": 0, "selected": false, "text": "http.proxyHost=proxyserver\nhttp.proxyPort=3128\n http.nonProxyHosts=localhost|*.companydomain.com\n" }, { "answer_id": 44699981, "author": "bahrep", "author_id": 761095, "author_profile": "https://Stackoverflow.com/users/761095", "pm_score": 1, "selected": false, "text": "Access to 'foo' forbidden 403 Forbidden svn auth" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57137", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5626/" ]
57,140
<p>Say instead of returning void a method you returned a reference to the class even if it didn't make any particular semantic sense. It seems to me like it would give you more options on how the methods are called, allowing you to use it in a fluent-interface-like style and I can't really think of any disadvantages since you don't have to do anything with the return value (even store it).</p> <p>So suppose you're in a situation where you want to update an object and then return its current value. instead of saying </p> <pre><code>myObj.Update(); var val = myObj.GetCurrentValue(); </code></pre> <p>you will be able to combine the two lines to say</p> <pre><code>var val = myObj.Update().GetCurrentValue(); </code></pre> <hr> <p><strong>EDIT:</strong> I asked the below on a whim, in retrospect, I agree that its likely to be unnecessary and complicating, however my question regarding returning this rather than void stands.</p> <p>On a related note, what do you guys think of having the language include a new bit of syntactic sugar:</p> <pre><code>var val = myObj.Update()&lt;.GetCurrentValue(); </code></pre> <p>This operator would have a low order of precedence so myObj.Update() would execute first and then call GetCurrentValue() on myObj instead of the void return of Update.</p> <p>Essentially I'm imagining an operator that will say "call the method on the right-hand side of the operator on the first valid object on the left". Any thoughts?</p>
[ { "answer_id": 57176, "author": "John Calsbeek", "author_id": 5696, "author_profile": "https://Stackoverflow.com/users/5696", "pm_score": 2, "selected": false, "text": "self" }, { "answer_id": 57212, "author": "Tim Frey", "author_id": 1471, "author_profile": "https://Stackoverflow.com/users/1471", "pm_score": 2, "selected": false, "text": "public MyCollection remove(Object someElement)\n" }, { "answer_id": 57792, "author": "Ismael", "author_id": 5999, "author_profile": "https://Stackoverflow.com/users/5999", "pm_score": 0, "selected": false, "text": "with obj\n .GetA();\n .GetB();\nend with;\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57140", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5056/" ]
57,145
<p>While creating classes in Java I often find myself creating instance-level collections that I know ahead of time will be very small - less than 10 items in the collection. But I don't know the number of items ahead of time so I typically opt for a dynamic collection (ArrayList, Vector, etc).</p> <pre><code>class Foo { ArrayList&lt;Bar&gt; bars = new ArrayList&lt;Bar&gt;(10); } </code></pre> <p>A part of me keeps nagging at me that it's wasteful to use complex dynamic collections for something this small in size. Is there a better way of implementing something like this? Or is this the norm?</p> <p>Note, I'm not hit with any (noticeable) performance penalties or anything like that. This is just me wondering if there isn't a better way to do things.</p>
[ { "answer_id": 57185, "author": "John Calsbeek", "author_id": 5696, "author_profile": "https://Stackoverflow.com/users/5696", "pm_score": 4, "selected": true, "text": "ArrayList Object[] ArrayList ArrayList ArrayList" }, { "answer_id": 57341, "author": "Cagatay", "author_id": 3071, "author_profile": "https://Stackoverflow.com/users/3071", "pm_score": 2, "selected": false, "text": "Lists.asList" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57145", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2881/" ]
57,152
<p>Let's say I've got Alpha things that may or may not <em>be</em> or be <em>related to</em> Bravo or Charlie things.</p> <p>These are one-to-one relationships: No Alpha will relate to more than one Bravo. And no Bravo will relate to more than one Alpha.</p> <p>I've got a few goals:</p> <ul> <li>a system that's easy to learn and maintain.</li> <li>data integrity enforced within my database.</li> <li>a schema that matches the real-world, logical organization of my data.</li> <li>classes/objects within my programming that map well to database tables (à la Linq to SQL)</li> <li>speedy read and write operations</li> <li>effective use of space (few null fields)</li> </ul> <p>I've got three ideas&hellip;</p> <pre><code>PK = primary key FK = foreign key NU = nullable </code></pre> <p>One table with many nullalbe fields (flat file)&hellip;</p> <pre><code> Alphas -------- PK AlphaId AlphaOne AlphaTwo AlphaThree NU BravoOne NU BravoTwo NU BravoThree NU CharlieOne NU CharlieTwo NU CharlieThree </code></pre> <p>Many tables with zero nullalbe fields&hellip;</p> <pre><code> Alphas -------- PK AlphaId AlphaOne AlphaTwo AlphaThree Bravos -------- FK PK AlphaId BravoOne BravoTwo BravoThree Charlies -------- FK PK AlphaId CharlieOne CharlieTwo CharlieThree </code></pre> <p>Best (or worst) of both: Lots of nullalbe foreign keys to many tables&hellip;</p> <pre><code> Alphas -------- PK AlphaId AlphaOne AlphaTwo AlphaThree NU FK BravoId NU FK CharlieId Bravos -------- PK BravoId BravoOne BravoTwo BravoThree Charlies -------- PK CharlieId CharlieOne CharlieTwo CharlieThree </code></pre> <p>What if an Alpha must be either Bravo or Charlie, but not both?</p> <p>What if instead of just Bravos and Charlies, Alphas could also be any of Deltas, Echos, Foxtrots, or Golfs, etc&hellip;?</p> <hr> <p><strong>EDIT:</strong> This is a portion of the question: <a href="https://stackoverflow.com/questions/56981/which-is-the-best-database-schema-for-my-navigation#57056">Which is the best database schema for my navigation?</a></p>
[ { "answer_id": 57209, "author": "David Schmitt", "author_id": 4918, "author_profile": "https://Stackoverflow.com/users/4918", "pm_score": 3, "selected": false, "text": " Bravos\n --------\nFK PK AlphaId\n BravoOne\n BravoTwo\n BravoThree\n Alpha\n --------\n PK AlphaId\n PK AlphaType NOT NULL IN (\"Bravo\", \"Charlie\")\n AlphaOne\n AlphaTwo\n AlphaThree\n\n Bravos\n --------\nFK PK AlphaId\nFK PK AlphaType == \"Bravo\"\n BravoOne\n BravoTwo\n BravoThree\n\n Charlies\n --------\nFK PK AlphaId\nFK PK AlphaType == \"Charlie\"\n CharlieOne\n CharlieTwo\n CharlieThree\n" }, { "answer_id": 57772, "author": "Fernando Barrocal", "author_id": 2274, "author_profile": "https://Stackoverflow.com/users/2274", "pm_score": 1, "selected": false, "text": "// For example sake lets think Id as a CHAR.\n// and pardon me on any mistake, I dont have the exact code here,\n// but you can get the idea\n\nSELECT \n (CASE alpha_type_id\n WHEN 'B' THEN '[Bravo].[Name]'\n WHEN 'C' THEN '[Charlie].[Name]'\n ELSE Null\n END)\nFROM ...\n" }, { "answer_id": 86025, "author": "Mike McAllister", "author_id": 16247, "author_profile": "https://Stackoverflow.com/users/16247", "pm_score": 0, "selected": false, "text": " THINGS\n ------\nPK ThingId \n\n ALPHAS\n ------\nFK ThingId (not null, identifying, exported from THINGS)\n AlphaCol1\n AlphaCol2\n AlphaCol3 \n\n BRAVOS\n ------\nFK ThingId (not null, identifying, exported from THINGS)\n BravoCol1\n BravoCol2\n BravoCol3 \n\n CHARLIES\n --------\nFK ThingId (not null, identifying, exported from THINGS)\n CharlieCol1\n CharlieCol2\n CharlieCol3\n insert into things values (1);\ninsert into alphas values (1,'alpha col 1',5,'blue');\ninsert into charlies values (1,'charlie col 1',17,'Y');\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57152", "https://Stackoverflow.com", "https://Stackoverflow.com/users/83/" ]
57,168
<p>I have two identical tables and need to copy rows from table to another. What is the best way to do that? (I need to programmatically copy just a few rows, I don't need to use the bulk copy utility).</p>
[ { "answer_id": 57172, "author": "Jarrett Meyer", "author_id": 5834, "author_profile": "https://Stackoverflow.com/users/5834", "pm_score": 3, "selected": false, "text": "SELECT * INTO < new_table > FROM < existing_table > WHERE < clause >\n" }, { "answer_id": 57188, "author": "Scott Nichols", "author_id": 4299, "author_profile": "https://Stackoverflow.com/users/4299", "pm_score": 8, "selected": true, "text": "INSERT INTO TableNew\nSELECT * FROM TableOld\nWHERE [Conditions]\n" }, { "answer_id": 57189, "author": "Michael Haren", "author_id": 29, "author_profile": "https://Stackoverflow.com/users/29", "pm_score": 6, "selected": false, "text": "INSERT tbl (Col1, Col2, ..., ColN)\n SELECT Col1, Col2, ..., ColN\n FROM Tbl2\n WHERE ...\n" }, { "answer_id": 57190, "author": "Kaniu", "author_id": 3236, "author_profile": "https://Stackoverflow.com/users/3236", "pm_score": 3, "selected": false, "text": "INSERT INTO DestTable\nSELECT * FROM SourceTable\nWHERE ... \n" }, { "answer_id": 57198, "author": "ScottStonehouse", "author_id": 2342, "author_profile": "https://Stackoverflow.com/users/2342", "pm_score": 5, "selected": false, "text": "INSERT Table2\n(columnX, columnY)\nSELECT column1, column2 FROM Table1\nWHERE [Conditions]\n" }, { "answer_id": 69256412, "author": "Shravya Mutyapu", "author_id": 12065837, "author_profile": "https://Stackoverflow.com/users/12065837", "pm_score": 0, "selected": false, "text": "SELECT TOP 10 *\nINTO db2.dbo.new_table\nFROM db1.dbo.old_table;\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57168", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2536/" ]
57,183
<p>How do I get the history of commits that have been made to the repository for a particular user? </p> <p>I am able to access CVS either through the command line or TortioseCVS, so a solution using either method is sufficient.</p>
[ { "answer_id": 57218, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 4, "selected": true, "text": "cvs history -u username\n" }, { "answer_id": 115301, "author": "Chris Noe", "author_id": 14749, "author_profile": "https://Stackoverflow.com/users/14749", "pm_score": 4, "selected": false, "text": "-c" }, { "answer_id": 5150036, "author": "Brain90", "author_id": 341959, "author_profile": "https://Stackoverflow.com/users/341959", "pm_score": 0, "selected": false, "text": "cvs history -x AMR -D \"your-desired-date\"\n cvs history -x AMR -D \"2012-04-12\"\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57183", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3498/" ]
57,202
<p>I would like to put a link to a webpage in an alert dialog box so that I can give a more detailed description of how to fix the error that makes the dialog box get created. </p> <p>How can I make the dialog box show something like this:</p> <pre><code>There was an error. Go to this page to fix it. wwww.TheWebPageToFix.com </code></pre> <p>Thanks.</p>
[ { "answer_id": 57214, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 2, "selected": false, "text": "alert()" }, { "answer_id": 57215, "author": "DrFloyd5", "author_id": 1736623, "author_profile": "https://Stackoverflow.com/users/1736623", "pm_score": 2, "selected": false, "text": "alert(\"There was an error. Got to this page to fix it.\\nwww.TheWebPageToFix.com\");\n alert()" }, { "answer_id": 57233, "author": "jessegavin", "author_id": 5651, "author_profile": "https://Stackoverflow.com/users/5651", "pm_score": 3, "selected": false, "text": "alert()" }, { "answer_id": 57236, "author": "Hafthor", "author_id": 4489, "author_profile": "https://Stackoverflow.com/users/4489", "pm_score": 3, "selected": false, "text": "window.open() prompt() confirm() div" }, { "answer_id": 57306, "author": "rpetrich", "author_id": 4007, "author_profile": "https://Stackoverflow.com/users/4007", "pm_score": 4, "selected": true, "text": "if(window.prompt('Do you wish to visit the following website?','http://www.google.ca'))\n location.href='http://www.google.ca/';\n if (window.showModalDialog)\n window.showModalDialog(\"mypage.html\",\"popup\",\"dialogWidth:255px;dialogHeight:250px\");\nelse\n window.open(\"mypage.html\",\"name\",\"height=255,width=250,toolbar=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,modal=yes\");\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57202", "https://Stackoverflow.com", "https://Stackoverflow.com/users/730/" ]
57,238
<p>Say I have several JavaScript includes in a page:</p> <pre><code>&lt;script type="text/javascript" src="/js/script0.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="/js/script1.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="/js/script2.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="/js/script3.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="/js/script4.js"&gt;&lt;/script&gt; </code></pre> <p>Is there a way i can tell if any of those weren't found (404) without having to manually check each one? I guess i'm looking for an online tool or something similar. Any ideas?</p>
[ { "answer_id": 57297, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "var script0Exists = true; // inside script0.js\nvar script1Exists = true; // inside script1.js\n if ( script0Exists ) {\n // not a 404 - it exists\n}\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5261/" ]
57,243
<p>I am trying to do something I've done a million times and it's not working, can anyone tell me why?</p> <p>I have a table for people who sent in resumes, and it has their email address in it...</p> <p>I want to find out if any of these people have NOT signed up on the web site. The aspnet_Membership table has all the people who ARE signed up on the web site.</p> <p>There are 9472 job seekers, with unique email addresses.</p> <p>This query produces 1793 results:</p> <pre><code>select j.email from jobseeker j join aspnet_Membership m on j.email = m.email </code></pre> <p>This suggests that there should be 7679 (9472-1793) emails of people who are not signed up on the web site. Since 1793 of them DID match, I would expect the rest of them DON'T match... but when I do the query for that, I get nothing!</p> <p>Why is this query giving me nothing???</p> <pre><code>select j.email from jobseeker j where j.email not in (select email from aspnet_Membership) </code></pre> <p>I don't know how that could be not working - it basically says "show me all the emails which are IN the jobseeker table, but NOT IN the aspnet_Membership table... </p>
[ { "answer_id": 57251, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 2, "selected": false, "text": "SELECT j.email\nFROM jobseeker j\nLEFT JOIN aspnet_Membership m ON m.email = j.email\nWHERE m.email IS NULL\n" }, { "answer_id": 57264, "author": "Mike Stone", "author_id": 122, "author_profile": "https://Stackoverflow.com/users/122", "pm_score": 3, "selected": true, "text": "select j.email \nfrom jobseeker j\nwhere j.email not in (select email from aspnet_Membership\n where email is not null)\n" }, { "answer_id": 57716, "author": "Martynnw", "author_id": 5466, "author_profile": "https://Stackoverflow.com/users/5466", "pm_score": 0, "selected": false, "text": "exists in Select J.Email\nFrom Jobseeker j\nWhere not exists (Select * From aspnetMembership a where j.email = a.email)\n in" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5255/" ]
57,249
<p>I'm interested in grabbing the EPG data from DVB-T streams. Does anyone know of any C libraries or an alternative means of getting the data?</p>
[ { "answer_id": 42530646, "author": "mkrufky", "author_id": 5535550, "author_profile": "https://Stackoverflow.com/users/5535550", "pm_score": 0, "selected": false, "text": "dvbtee" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57249", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3796/" ]
57,287
<p>How do I create an rss feed in ASP.Net? Is there anything built in to support it? If not, what third-party tools are available?</p> <p>I'm thinking webforms, not MVC, though I suppose since this isn't a traditional page the difference may be minimal.</p>
[ { "answer_id": 57309, "author": "Alex Duggleby", "author_id": 5790, "author_profile": "https://Stackoverflow.com/users/5790", "pm_score": 2, "selected": false, "text": "public void PageLoad()\n{\n\n// create channel\nRssChannel _soChannel = new RssChannel();\n\n// create item\nRssItem _soItem = new RssItem();\n_soItem.Title = \"Answer\";\n_soItem.Description = \"Example\";\n_soItem.PubDate = DateTime.Now.ToUniversalTime();\n\n// add to channel\n_soChannel.Items.Add(_soItem.);\n\n// set channel props\n_soChannel.Title = \"Stack Overflow\";\n_soChannel.Description = \"Great site.. jada jada jada\";\n_soChannel.LastBuildDate = DateTime.Now.ToUniversalTime();\n\n// change type and send to output\nRssFeed _f = new RssFeed();\n_f.Channels.Add(channel);\nResponse.ContentType = \"text/xml\";\n_f.Write(Response.OutputStream);\nResponse.End();\n\n}\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57287", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3043/" ]
57,291
<p>I have seen <a href="https://stackoverflow.com/questions/4046/can-someone-give-me-a-working-example-of-a-buildxml-for-an-ear-that-deploys-in">this question</a> about deploying to WebSphere using the WAS ant tasks.</p> <p>Is there a simpler way to do this? In the past I have deployed to Tomcat by dropping a war file into a directory. I was hoping there would be a similar mechanism for WebSphere that doesn't involve calling the IBM libraries or rely on RAD to be installed on your workstation.</p>
[ { "answer_id": 57310, "author": "Juha Pohjalainen", "author_id": 5240, "author_profile": "https://Stackoverflow.com/users/5240", "pm_score": 2, "selected": false, "text": "wsadminlib.py.zip" }, { "answer_id": 359520, "author": "Hans-Peter Störr", "author_id": 21499, "author_profile": "https://Stackoverflow.com/users/21499", "pm_score": 2, "selected": false, "text": "wsadmin.bat -lang jython \"thecommandscomehere\"" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57291", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1958/" ]
57,314
<p>What could the best strategy for writing validation layer for mid-enterprise level business application built on Spring 2.5</p> <p>I know that Spring provides facility where we can implement Validator interface and write validation logic in validate method. But this will be restricted to only web requests coming through spring controller.</p> <p>I would like to develop the validation framework which can be utilized during web-services calls.</p> <p>In other words, the framework can remain and be called independently without the need of implementing Validator interface and then too it can be automatically integrated into Spring MVC flow.</p> <p>Hope you get my point.</p>
[ { "answer_id": 67287, "author": "MetroidFan2002", "author_id": 8026, "author_profile": "https://Stackoverflow.com/users/8026", "pm_score": 0, "selected": false, "text": "boolean supports(Class clazz)\nvoid validate(Object target, Errors errors)\n Object target public interface ErrorReturning { \n public void getErrors(Errors errors);\n}\n public interface ValidationObject {\n public Errors getErrors(Errors errors);\n public Object getResultOfWebServiceValidation();\n}\n getErrors() getCommonValidator().validate(partialObject).getErrors(errors);\n getCommonValidator().validate(partialObject)" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/959/" ]
57,350
<p>I want to point a file dialog at a particular folder in the current user's Local Settings folder on Windows. What is the shortcut to get this path?</p>
[ { "answer_id": 57363, "author": "Matthew Maravillas", "author_id": 2186, "author_profile": "https://Stackoverflow.com/users/2186", "pm_score": 6, "selected": true, "text": "String appData = \n Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);\n" }, { "answer_id": 6971240, "author": "nawfal", "author_id": 661933, "author_profile": "https://Stackoverflow.com/users/661933", "pm_score": 2, "selected": false, "text": "string localPath = Directory.GetParent(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)).FullName;\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/327/" ]
57,355
<p>I'm having a little trouble figuring out exactly how const applies in a specific case. Here's the code I have:</p> <pre><code>struct Widget { Widget():x(0), y(0), z(0){} int x, y, z; }; struct WidgetHolder //Just a simple struct to hold four Widgets. { WidgetHolder(Widget a, Widget b, Widget c, Widget d): A(a), B(b), C(c), D(d){} Widget&amp; A; Widget&amp; B; Widget&amp; C; Widget&amp; D; }; class Test //This class uses four widgets internally, and must provide access to them externally. { public: const WidgetHolder AccessWidgets() const { //This should return our four widgets, but I don't want anyone messing with them. return WidgetHolder(A, B, C, D); } WidgetHolder AccessWidgets() { //This should return our four widgets, I don't care if they get changed. return WidgetHolder(A, B, C, D); } private: Widget A, B, C, D; }; int main() { const Test unchangeable; unchangeable.AccessWidgets().A.x = 1; //Why does this compile, shouldn't the Widget&amp; be const? } </code></pre> <p>Basically, I have a class called test. It uses four widgets internally, and I need it to return these, but if test was declared const, I want the widgets returned const also.</p> <p>Can someone explain to me why the code in main() compiles?</p> <p>Thank you very much.</p>
[ { "answer_id": 57370, "author": "Frank Krueger", "author_id": 338, "author_profile": "https://Stackoverflow.com/users/338", "pm_score": 2, "selected": false, "text": "WidgetHolder" }, { "answer_id": 57376, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 3, "selected": true, "text": "WidgetHolder(Widget a, Widget b, Widget c, Widget d): A(a), B(b), C(c), D(d){}\n WidgetHolder(Widget &a, Widget &b, Widget &c, Widget &d): A(a), B(b), C(c), D(d){}\n" }, { "answer_id": 57431, "author": "Greg Rogers", "author_id": 5963, "author_profile": "https://Stackoverflow.com/users/5963", "pm_score": 3, "selected": false, "text": "\nstruct ConstWidgetHolder\n{\n ConstWidgetHolder(const Widget &a, const Widget &b, const Widget &c, const Widget &d): A(a), B(b), C(c), D(d){}\n\n const Widget& A;\n const Widget& B;\n const Widget& C;\n const Widget& D;\n};\n\nclass Test\n{\npublic:\n ConstWidgetHolder AccessWidgets() const\n {\n return ConstWidgetHolder(A, B, C, D);\n }\n \nclass vector {\n iterator begin();\n const_iterator begin() const;\n" }, { "answer_id": 58537, "author": "Pieter", "author_id": 5822, "author_profile": "https://Stackoverflow.com/users/5822", "pm_score": 0, "selected": false, "text": "#include <iostream>\n\nclass Widget\n{\n int x;\npublic:\n Widget(int inX) : x(inX){}\n ~Widget() {\n std::cout << \"widget \" << static_cast< void*>(this) << \" destroyed\" << std::endl;\n }\n};\n\nstruct WidgetHolder\n{\n Widget& A;\n\npublic:\n WidgetHolder(Widget a): A(a) {}\n\n const Widget& a() const {\n std::cout << \"widget \" << static_cast< void*>(&A) << \" used\" << std::endl;\n return A;\n}\n\n};\n\nint main(char** argv, int argc)\n{\nWidget test(7);\nWidgetHolder holder(test);\nWidget const & test2 = holder.a();\n\nreturn 0;\n} \n" }, { "answer_id": 62608, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "#include <stdio.h>\n\nclass Test\n{\npublic:\n Test(int v){m_v = v;}\n ~Test(){printf(\"Destruct value = %d\\n\",m_v);}\n\n int& GetV(){printf (\"None Const returning %d\\n\",m_v); return m_v; }\n\n const int& GetV() const { printf(\"Const returning %d\\n\",m_v); return m_v;}\nprivate:\n int m_v;\n};\n\nvoid main()\n{\n // A none const object (or reference) calls the none const functions\n // in preference to the const\n Test one(10);\n int& x = one.GetV();\n // We can change the member variable via the reference\n x = 12;\n\n const Test two(20);\n // This will call the const version \n two.GetV();\n\n // So the below line will not compile\n // int& xx = two.GetV();\n\n // Where as this will compile\n const int& xx = two.GetV();\n\n // And then the below line will not compile\n // xx = 3;\n\n}\n class WidgetHolder {\n...\n\nWidget& GetA();\nconst Widget& GetA() const;\n...\n};\n class Test {\n...\nWigetHolder& AccessWidgets() { return m_Widgets;}\nconst WidgetHolder&AcessWidgets() const { return m_Widgets;}\n\nprivate:\n WidgetHolder m_Widgets;\n...\n};\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3175/" ]
57,380
<p>Will the code below work if the clock on the server is ahead of the clock on the client?</p> <pre><code>Response.Cache.SetExpires(DateTime.Now.AddSeconds(-1)) </code></pre> <p>EDIT: the reason I ask is on one of our web apps some users are claiming they are seeing the pages ( account numbers, etc ) from a user that previously used that machine. Yet we use the line above and others to 'prevent' this from happening.</p>
[ { "answer_id": 57413, "author": "Joseph Bui", "author_id": 3275, "author_profile": "https://Stackoverflow.com/users/3275", "pm_score": 0, "selected": false, "text": "<input autocomplete=\"off\">\n" }, { "answer_id": 57715, "author": "Andrew Johnson", "author_id": 5109, "author_profile": "https://Stackoverflow.com/users/5109", "pm_score": 0, "selected": false, "text": "Response.Cache.SetNoServerCaching();\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57380", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2357/" ]
57,383
<p>I am calling, through reflection, a method which may cause an exception. How can I pass the exception to my caller without the wrapper reflection puts around it?<br> I am rethrowing the InnerException, but this destroys the stack trace.<br> Example code:</p> <pre><code>public void test1() { // Throw an exception for testing purposes throw new ArgumentException("test1"); } void test2() { try { MethodInfo mi = typeof(Program).GetMethod("test1"); mi.Invoke(this, null); } catch (TargetInvocationException tiex) { // Throw the new exception throw tiex.InnerException; } } </code></pre>
[ { "answer_id": 57387, "author": "GEOCHET", "author_id": 5640, "author_profile": "https://Stackoverflow.com/users/5640", "pm_score": 5, "selected": false, "text": "throw;\n" }, { "answer_id": 57389, "author": "skolima", "author_id": 3205, "author_profile": "https://Stackoverflow.com/users/3205", "pm_score": 4, "selected": false, "text": "catch (TargetInvocationException tiex)\n{\n // Get the _remoteStackTraceString of the Exception class\n FieldInfo remoteStackTraceString = typeof(Exception)\n .GetField(\"_remoteStackTraceString\",\n BindingFlags.Instance | BindingFlags.NonPublic); // MS.Net\n\n if (remoteStackTraceString == null)\n remoteStackTraceString = typeof(Exception)\n .GetField(\"remote_stack_trace\",\n BindingFlags.Instance | BindingFlags.NonPublic); // Mono\n\n // Set the InnerException._remoteStackTraceString\n // to the current InnerException.StackTrace\n remoteStackTraceString.SetValue(tiex.InnerException,\n tiex.InnerException.StackTrace + Environment.NewLine);\n\n // Throw the new exception\n throw tiex.InnerException;\n}\n" }, { "answer_id": 1663549, "author": "Eric", "author_id": 201208, "author_profile": "https://Stackoverflow.com/users/201208", "pm_score": 4, "selected": false, "text": "public static class ExceptionHelper\n{\n private static Action<Exception> _preserveInternalException;\n\n static ExceptionHelper()\n {\n MethodInfo preserveStackTrace = typeof( Exception ).GetMethod( \"InternalPreserveStackTrace\", BindingFlags.Instance | BindingFlags.NonPublic );\n _preserveInternalException = (Action<Exception>)Delegate.CreateDelegate( typeof( Action<Exception> ), preserveStackTrace ); \n }\n\n public static void PreserveStackTrace( this Exception ex )\n {\n _preserveInternalException( ex );\n }\n}\n" }, { "answer_id": 1992235, "author": "Boris Treukhov", "author_id": 241986, "author_profile": "https://Stackoverflow.com/users/241986", "pm_score": 3, "selected": false, "text": " public void test1()\n {\n // Throw an exception for testing purposes\n throw new ArgumentException(\"test1\");\n }\n\n void test2()\n {\n MethodInfo mi = typeof(Program).GetMethod(\"test1\");\n ((Action)Delegate.CreateDelegate(typeof(Action), mi))();\n\n }\n" }, { "answer_id": 2085377, "author": "Anton Tykhyy", "author_id": 77724, "author_profile": "https://Stackoverflow.com/users/77724", "pm_score": 6, "selected": false, "text": "static void PreserveStackTrace (Exception e)\n{\n var ctx = new StreamingContext (StreamingContextStates.CrossAppDomain) ;\n var mgr = new ObjectManager (null, ctx) ;\n var si = new SerializationInfo (e.GetType (), new FormatterConverter ()) ;\n\n e.GetObjectData (si, ctx) ;\n mgr.RegisterObject (e, 1, si) ; // prepare for SetObjectData\n mgr.DoFixups () ; // ObjectManager calls SetObjectData\n\n // voila, e is unmodified save for _remoteStackTraceString\n}\n InternalPreserveStackTrace // usage (A): cross-thread invoke, messaging, custom task schedulers etc.\ncatch (Exception e)\n{\n PreserveStackTrace (e) ;\n\n // store exception to be re-thrown later,\n // possibly in a different thread\n operationResult.Exception = e ;\n}\n\n// usage (B): after calling MethodInfo.Invoke() and the like\ncatch (TargetInvocationException tiex)\n{\n PreserveStackTrace (tiex.InnerException) ;\n\n // unwrap TargetInvocationException, so that typed catch clauses \n // in library/3rd-party code can work correctly;\n // new stack trace is appended to existing one\n throw tiex.InnerException ;\n}\n" }, { "answer_id": 9989557, "author": "chickenbyproduct", "author_id": 1309889, "author_profile": "https://Stackoverflow.com/users/1309889", "pm_score": 2, "selected": false, "text": " static void PreserveStackTrace(Exception e)\n {\n var ctx = new StreamingContext(StreamingContextStates.CrossAppDomain);\n var si = new SerializationInfo(typeof(Exception), new FormatterConverter());\n var ctor = typeof(Exception).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { typeof(SerializationInfo), typeof(StreamingContext) }, null);\n\n e.GetObjectData(si, ctx);\n ctor.Invoke(e, new object[] { si, ctx });\n }\n" }, { "answer_id": 17091351, "author": "Paul Turner", "author_id": 138578, "author_profile": "https://Stackoverflow.com/users/138578", "pm_score": 10, "selected": true, "text": "ExceptionDispatchInfo using ExceptionDispatchInfo = \n System.Runtime.ExceptionServices.ExceptionDispatchInfo;\n\ntry\n{\n task.Wait();\n}\ncatch(AggregateException ex)\n{\n ExceptionDispatchInfo.Capture(ex.InnerException).Throw();\n}\n AggregateException await AggregateException" }, { "answer_id": 40586566, "author": "Mark", "author_id": 6192931, "author_profile": "https://Stackoverflow.com/users/6192931", "pm_score": 5, "selected": false, "text": "ExceptionDispatchInfo.Capture( ex ).Throw() throw ExceptionDispatchInfo.Capture( ex ).Throw() void CallingMethod()\n{\n //try\n {\n throw new Exception( \"TEST\" );\n }\n //catch\n {\n // throw;\n }\n}\n void CallingMethod()\n{\n try\n {\n throw new Exception( \"TEST\" );\n }\n catch( Exception ex )\n {\n ExceptionDispatchInfo.Capture( ex ).Throw();\n throw; // So the compiler doesn't complain about methods which don't either return or throw.\n }\n}\n void CallingMethod()\n{\n try\n {\n throw new Exception( \"TEST\" );\n }\n catch\n {\n throw;\n }\n}\n void CallingMethod()\n{\n try\n {\n throw new Exception( \"TEST\" );\n }\n catch( Exception ex )\n {\n throw new Exception( \"RETHROW\", ex );\n }\n}\n CallingMethod throw new Exception( \"TEST\" ) CallingMethod throw throw new Exception( \"TEST\" )" }, { "answer_id": 57052791, "author": "Jürgen Steinblock", "author_id": 98491, "author_profile": "https://Stackoverflow.com/users/98491", "pm_score": 4, "selected": false, "text": " public static Exception Capture(this Exception ex)\n {\n ExceptionDispatchInfo.Capture(ex).Throw();\n return ex;\n }\n return ex throw ex.Capture() not all code paths return a value public static object InvokeEx(this MethodInfo method, object obj, object[] parameters)\n {\n {\n return method.Invoke(obj, parameters);\n }\n catch (TargetInvocationException ex) when (ex.InnerException != null)\n {\n throw ex.InnerException.Capture();\n }\n }\n" }, { "answer_id": 73625170, "author": "Ben", "author_id": 723645, "author_profile": "https://Stackoverflow.com/users/723645", "pm_score": 1, "selected": false, "text": "public static class ExceptionExtensions\n{\n [DoesNotReturn]\n public static void Rethrow(this Exception ex) \n => ExceptionDispatchInfo.Capture(ex).Throw();\n}\n PropertyName myObject try\n{\n object? value = myObject.GetType().GetProperty(\"PropertyName\")?.GetValue(myObject);\n}\ncatch (TargetInvocationException ex)\n{\n (ex.InnerException ?? ex).Rethrow();\n}\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3205/" ]
57,421
<p>I would like to make an ajax call to a different server (same domain and box, just a different port.) e.g.</p> <p>My page is</p> <pre> http://localhost/index.html </pre> <p>I would like to make a ajax get request to:</p> <pre> http://localhost:7076/?word=foo </pre> <p>I am getting this error:</p> <pre> Access to restricted URI denied (NS_ERROR_DOM_BAD_URI) </pre> <p>I know that you can not make an ajax request to a different domain, but it seem this also included different ports? are there any workarounds?</p>
[ { "answer_id": 57435, "author": "Joseph Bui", "author_id": 3275, "author_profile": "https://Stackoverflow.com/users/3275", "pm_score": 3, "selected": true, "text": "http://localhost/proxy?port=7076&url=%2f%3fword%3dfoo\n" }, { "answer_id": 57442, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 0, "selected": false, "text": "localhost localhost:7076" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57421", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1638/" ]
57,424
<p>I'd like to use the camera in my Macbook in a program. I'm fairly language agnostic - C, Java, Python etc are all fine. Could anyone suggest the best place to look for documents or "Hello world" type code?</p>
[ { "answer_id": 57461, "author": "Chris Hanson", "author_id": 714, "author_profile": "https://Stackoverflow.com/users/714", "pm_score": 4, "selected": true, "text": "IKPictureTaker" }, { "answer_id": 2195738, "author": "meduz", "author_id": 234547, "author_profile": "https://Stackoverflow.com/users/234547", "pm_score": 1, "selected": false, "text": "import motmot.cam_iface.cam_iface_ctypes as cam_iface\nimport numpy as np\n\nmode_num = 0\ndevice_num = 0\nnum_buffers = 32\n\ncam = cam_iface.Camera(device_num,num_buffers,mode_num)\ncam.start_camera()\nframe = np.asarray(cam.grab_next_frame_blocking())\nprint 'grabbed frame with shape %s'%(frame.shape,)\n" }, { "answer_id": 4777011, "author": "meduz", "author_id": 234547, "author_profile": "https://Stackoverflow.com/users/234547", "pm_score": 0, "selected": false, "text": "import cv\ncapture = cv.CaptureFromCAM(0)\nimg = cv.QueryFrame(capture)\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57424", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5346/" ]
57,439
<p>No, this is not a question about generics.</p> <p>I have a Factory pattern with several classes with internal constructors (I don't want them being instantiated if not through the factory).</p> <p>My problem is that <code>CreateInstance</code> fails with a "No parameterless constructor defined for this object" error unless I pass "true" on the non-public parameter.</p> <p>Example</p> <pre><code>// Fails Activator.CreateInstance(type); // Works Activator.CreateInstance(type, true); </code></pre> <p>I wanted to make the factory generic to make it a little simpler, like this:</p> <pre><code>public class GenericFactory&lt;T&gt; where T : MyAbstractType { public static T GetInstance() { return Activator.CreateInstance&lt;T&gt;(); } } </code></pre> <p>However, I was unable to find how to pass that "true" parameter for it to accept non-public constructors (internal).</p> <p>Did I miss something or it isn't possible?</p>
[ { "answer_id": 57450, "author": "Kilhoffer", "author_id": 5469, "author_profile": "https://Stackoverflow.com/users/5469", "pm_score": 5, "selected": true, "text": "public class GenericFactory<T> where T : MyAbstractType\n{\n public static T GetInstance()\n {\n return Activator.CreateInstance(typeof(T), true);\n }\n}\n" }, { "answer_id": 57463, "author": "rpetrich", "author_id": 4007, "author_profile": "https://Stackoverflow.com/users/4007", "pm_score": 2, "selected": false, "text": "public abstract class GenericFactory<T> where T : MyAbstractType\n{\n public static T GetInstance()\n {\n return (T)Activator.CreateInstance(typeof(T), true);\n }\n}\n public abstract class GenericFactory<T> where T : MyAbstractType, new()\n{\n public static T GetInstance()\n {\n return new T;\n }\n}\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1782/" ]
57,449
<p>I'm working on a big .NET 1.1 project, and there exists a wish to upgrade this, majorily to be able to use better tools like Visual Studio 2008, but also because of the new features and smaller amount of bugs in the .NET 2.0 framework.</p> <p>The project consist for the bigger part of VB.NET, but there are also parts in C#. It is a Windows Forms application, using various third party controls. Using .NET remoting the rich client talks to a server process which interfaces with a MSSQL 2000 database.</p> <p>What kind of issues can we expect in case we decide to perform the upgrade?</p>
[ { "answer_id": 74534, "author": "CindyH", "author_id": 12897, "author_profile": "https://Stackoverflow.com/users/12897", "pm_score": 1, "selected": false, "text": " Imports System.Web.Mail\n '\n Dim message As New MailMessage' this is a web.mail msg, not a net.mail msg\n Dim objConn As SmtpMail\n Dim objAttach As MailAttachment\n '\n message .From = \"[email protected]\"\n ' more properties assigned to objMail\n objAttach = New MailAttachment(ExportName)\n message.Attachments.Add(objAttach)\n ' Here's where we actually send the thing\n SmtpMail.SmtpServer.Insert(0, \"127.0.0.1\")\n objConn.Send(objMail)\n Imports System.Net.Mail\n '\n Dim message as MailMessage ' this is a net.mail msg, not a web.mail msg\n Dim data As Attachment\n Dim client As New SmtpClient(\"127.0.0.1\")\n '\n data = New Attachment(ExportName)\n ' Create the message and add the attachment\n message = New MailMessage(EmailFrom, EmailTo, reportDescription)\n message.Attachments.Add(data)\n' Send the message\n client.Send(message)\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57449", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5422/" ]
57,467
<p>Is there an equivalent of svn's blame for Perforce on the command line? <code>p4 annotate</code> doesn't display usernames -- only changeset numbers (without ancestor history!).</p> <p>I currently have to track code back through ancestors and compare against the filelog, and there just has to be an easier way -- maybe a F/OSS utility?</p>
[ { "answer_id": 57517, "author": "Mark", "author_id": 4405, "author_profile": "https://Stackoverflow.com/users/4405", "pm_score": 6, "selected": false, "text": "p4v.exe -cmd \"annotate //<path/to/file>\"\n" }, { "answer_id": 57661, "author": "cdleary", "author_id": 3594, "author_profile": "https://Stackoverflow.com/users/3594", "pm_score": 1, "selected": false, "text": "last if $type eq 'branch';\n" }, { "answer_id": 16088968, "author": "Alexander Bird", "author_id": 10608, "author_profile": "https://Stackoverflow.com/users/10608", "pm_score": 1, "selected": false, "text": "p4 annotate -I -i -I\nFollow integrations into the file. If a line was introduced into the file by a merge, the source of the merge is indicated as the changelist that introduced the line. If that source was itself the result of an integration, that source will be used instead, and so on.\nThe use of the -I option implies the -c option. The -I option cannot be combined with -i.\n-i\nFollow file history across branches. If a file was created by branching, Perforce includes revisions up to the branch point.\nThe use of the -i option implies the -c option. The -i option cannot be combined with -I.\n" }, { "answer_id": 25327392, "author": "Arnon Zilca", "author_id": 3374591, "author_profile": "https://Stackoverflow.com/users/3374591", "pm_score": 3, "selected": false, "text": "#!/bin/bash\n\nFILE=\"$1\"\nLINE=\"$2\"\n\np4 annotate -cq \"${FILE}\" | sed \"${LINE}q;d\" | cut -f1 -d: | xargs p4 describe -s | sed -e '/Affected files/,$d'\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57467", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3594/" ]
57,479
<p>Help! I am using jQuery to make an AJAX call to fill in a drop-down dynamically given the user's previous input (from another drop-down, that is filled server-side). In all other browsers aside from Firefox (IE6/7, Opera, Safari), my append call actually appends the information below my existing option - "Select An ". But in Firefox, it automatically selects the last item given to the select control, regardless of whether I specify the JQuery action to .append or to replace (.html()). </p> <pre><code>&lt;select name="Products" id="Products" onchange="getHeadings(this.value);"&gt; &lt;option value=""&gt;Select Product&lt;/option&gt; &lt;/select&gt; function getProducts(Category) { $.ajax({ type: "GET", url: "getInfo.cfm", data: "Action=getProducts&amp;Category=" + Category, success: function(result){ $("#Products").html(result); } }); }; </code></pre> <p>Any thoughts? I have tried in the past to also transmit another blank first option, and then trigger a JavaScript option to re-select the first index, but this triggers the onChange event in my code, rather annoying for the user.</p> <hr> <p>Update:</p> <p>Here's an example of what the script would return</p> <pre><code>&lt;option value="3"&gt;Option 1&lt;/option&gt; &lt;option value="4"&gt;Option 2&lt;/option&gt; &lt;option value="6"&gt;Option 3&lt;/option&gt; </code></pre> <p>Optionally, if using the .html() method instead of the .append(), I would put another</p> <pre><code>&lt;option value=""&gt;Select a Product&lt;/option&gt; </code></pre> <p>at the top of the result.</p> <hr> <p>@Darryl Hein</p> <p>Here's an example of what the script would return</p> <pre><code>&lt;option value="3"&gt;Option 1&lt;/option&gt; &lt;option value="4"&gt;Option 2&lt;/option&gt; &lt;option value="6"&gt;Option 3&lt;/option&gt; </code></pre> <p>Optionally, if using the .html() method instead of the .append(), I would put another</p> <pre><code>&lt;option value=""&gt;Select a Product&lt;/option&gt; </code></pre> <p>at the top of the result.</p>
[ { "answer_id": 57514, "author": "Darryl Hein", "author_id": 5441, "author_profile": "https://Stackoverflow.com/users/5441", "pm_score": 0, "selected": false, "text": "<select name=\"Products\" id=\"Products\">\n<option value=\"\">Select Product</option>\n</select>\n\n<script type=\"text/javascript\">\n$('#Products').append('<option value=\"1\">test 1</option><option value=\"3\">test 3</option><option value=\"3\">test 3</option>');\n</script>\n" }, { "answer_id": 57905, "author": "Prestaul", "author_id": 5628, "author_profile": "https://Stackoverflow.com/users/5628", "pm_score": 3, "selected": true, "text": "$(\"#Products\").append(result).selectedIndex = 0;\n var tmpIdx = $(\"#Products\").selectedIndex;\n$(\"#Products\").append(result).selectedIndex = tmpIdx;\n" }, { "answer_id": 490513, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "$('#field').find('option:first').attr('selected', 'selected').parent('select');\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57479", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5405/" ]
57,483
<p>What is the difference between a pointer variable and a reference variable?</p>
[ { "answer_id": 57490, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 7, "selected": false, "text": "const const" }, { "answer_id": 57492, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 11, "selected": false, "text": "int x = 5;\nint y = 6;\nint *p;\np = &x;\np = &y;\n*p = 10;\nassert(x == 5);\nassert(y == 10);\n int x = 5;\nint y = 6;\nint &q; // error\nint &r = x;\n & sizeof int x = 0;\nint &r = x;\nint *p = &x;\nint *p2 = &r;\n\nassert(p == p2); // &x == &r\nassert(&p != &p2);\n int x = 0;\nint y = 0;\nint *p = &x;\nint *q = &y;\nint **pp = &p;\n\n**pp = 2;\npp = &q; // *pp is now q\n**pp = 4;\n\nassert(y == 4);\nassert(x == 2);\n nullptr nullptr /* the code below is undefined; your compiler may optimise it\n * differently, emit warnings, or outright refuse to compile it */\n\nint &r = *static_cast<int *>(nullptr);\n\n// prints \"null\" under GCC 10\nstd::cout\n << (&r != nullptr\n ? \"not null\" : \"null\")\n << std::endl;\n\nbool f(int &r) { return &r != nullptr; }\n\n// prints \"not null\" under GCC 10\nstd::cout\n << (f(*static_cast<int *>(nullptr))\n ? \"not null\" : \"null\")\n << std::endl;\n nullptr ++ + 4 * -> . const int &x = int(12); // legal C++\nint *y = &int(12); // illegal to take the address of a temporary.\n const &" }, { "answer_id": 57502, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "NULL" }, { "answer_id": 57656, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 7, "selected": false, "text": "int * p = NULL;\nint & r = *p;\nr = 1; // crash! (if you're lucky)\n class MyClass\n{\n ...\n virtual void DoSomething(int,int,int,int,int);\n};\n\nvoid Foo(const MyClass & bar)\n{\n ...\n bar.DoSomething(i1,i2,i3,i4,i5); // crash occurs here due to memory access violation - obvious why?\n}\n\nMyClass * GetInstance()\n{\n if (somecondition)\n return NULL;\n ...\n}\n\nMyClass * p = GetInstance();\nFoo(*p);\n if(&bar==NULL)... if template<typename T>\nT& deref(T* p)\n{\n if (p == NULL)\n throw std::invalid_argument(std::string(\"NULL reference\"));\n return *p;\n}\n\nMyClass * p = GetInstance();\nFoo(deref(p));\n" }, { "answer_id": 57734, "author": "Matt Price", "author_id": 852, "author_profile": "https://Stackoverflow.com/users/852", "pm_score": 8, "selected": false, "text": "std::string s1 = \"123\";\nstd::string s2 = \"456\";\n\nstd::string s3_copy = s1 + s2;\nconst std::string& s3_reference = s1 + s2;\n const" }, { "answer_id": 57780, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 7, "selected": false, "text": "-> . foo.bar foo->bar" }, { "answer_id": 58996, "author": "Aardvark", "author_id": 3655, "author_profile": "https://Stackoverflow.com/users/3655", "pm_score": 4, "selected": false, "text": "p += offset;" }, { "answer_id": 59636, "author": "Don Wakefield", "author_id": 3778, "author_profile": "https://Stackoverflow.com/users/3778", "pm_score": 4, "selected": false, "text": "class UDT\n{\npublic:\n UDT() : val_d(33) {};\n UDT(int val) : val_d(val) {};\n virtual ~UDT() {};\nprivate:\n int val_d;\n};\n\nclass UDT_Derived : public UDT\n{\npublic:\n UDT_Derived() : UDT() {};\n virtual ~UDT_Derived() {};\n};\n\nclass Behavior\n{\npublic:\n Behavior(\n const UDT &udt = UDT()\n ) {};\n};\n\nint main()\n{\n Behavior b; // take default\n\n UDT u(88);\n Behavior c(u);\n\n UDT_Derived ud;\n Behavior d(ud);\n\n return 1;\n}\n" }, { "answer_id": 60148, "author": "MSN", "author_id": 6210, "author_profile": "https://Stackoverflow.com/users/6210", "pm_score": 5, "selected": false, "text": "class scope_test\n{\npublic:\n ~scope_test() { printf(\"scope_test done!\\n\"); }\n};\n\n...\n\n{\n const scope_test &test= scope_test();\n printf(\"in scope\\n\");\n}\n in scope\nscope_test done!\n" }, { "answer_id": 101406, "author": "Vincent Robert", "author_id": 268, "author_profile": "https://Stackoverflow.com/users/268", "pm_score": 6, "selected": false, "text": "int a = 0;\nint& b = a;\n a a a b void increment(int& n)\n{\n n = n + 1;\n}\n\nint a;\nincrement(a);\n" }, { "answer_id": 596750, "author": "Christoph", "author_id": 48015, "author_profile": "https://Stackoverflow.com/users/48015", "pm_score": 9, "selected": false, "text": "*" }, { "answer_id": 1569931, "author": "Adisak", "author_id": 14904, "author_profile": "https://Stackoverflow.com/users/14904", "pm_score": 4, "selected": false, "text": "void increment(int *ptrint) { (*ptrint)++; }\nvoid increment(int &refint) { refint++; }\nvoid incptrtest()\n{\n int testptr=0;\n increment(&testptr);\n}\nvoid increftest()\n{\n int testref=0;\n increment(testref);\n}\n" }, { "answer_id": 2162825, "author": "kriss", "author_id": 168465, "author_profile": "https://Stackoverflow.com/users/168465", "pm_score": 4, "selected": false, "text": "int a;\nvoid * p = &a; // ok\nvoid & p = a; // forbidden\n" }, { "answer_id": 6076707, "author": "Kunal Vyas", "author_id": 731433, "author_profile": "https://Stackoverflow.com/users/731433", "pm_score": 5, "selected": false, "text": "int ival = 1024, ival2 = 2048;\nint *pi = &ival, *pi2 = &ival2;\npi = pi2; // pi now points to ival2\n int &ri = ival, &ri2 = ival2;\nri = ri2; // assigns ival2 to ival\n" }, { "answer_id": 14112711, "author": "fatma.ekici", "author_id": 1678760, "author_profile": "https://Stackoverflow.com/users/1678760", "pm_score": 5, "selected": false, "text": " void fun(int &a, int &b); // A common usage of references.\n int a = 0;\n int &b = a; // b is an alias for a. Not so common to use. \n" }, { "answer_id": 15081923, "author": "tanweer alam", "author_id": 2002964, "author_profile": "https://Stackoverflow.com/users/2002964", "pm_score": 4, "selected": false, "text": "int& j = i;\n int* const j = &i;\n" }, { "answer_id": 15423961, "author": "Arlene Batada", "author_id": 2172349, "author_profile": "https://Stackoverflow.com/users/2172349", "pm_score": 4, "selected": false, "text": "#include<iostream>\n\nusing namespace std;\n\nint main()\n{\nint *ptr=0, x=9; // pointer and variable declaration\nptr=&x; // pointer to variable \"x\"\nint & j=x; // reference declaration; reference to variable \"x\"\n\ncout << \"x=\" << x << endl;\n\ncout << \"&x=\" << &x << endl;\n\ncout << \"j=\" << j << endl;\n\ncout << \"&j=\" << &j << endl;\n\ncout << \"*ptr=\" << *ptr << endl;\n\ncout << \"ptr=\" << ptr << endl;\n\ncout << \"&ptr=\" << &ptr << endl;\n getch();\n}\n" }, { "answer_id": 18555015, "author": "Cort Ammon", "author_id": 2728148, "author_profile": "https://Stackoverflow.com/users/2728148", "pm_score": 6, "selected": false, "text": "void maybeModify(int& x); // may modify x in some way\n\nvoid hurtTheCompilersOptimizer(short size, int array[])\n{\n // This function is designed to do something particularly troublesome\n // for optimizers. It will constantly call maybeModify on array[0] while\n // adding array[1] to array[2]..array[size-1]. There's no real reason to\n // do this, other than to demonstrate the power of references.\n for (int i = 2; i < (int)size; i++) {\n maybeModify(array[0]);\n array[i] += array[1];\n }\n}\n void hurtTheCompilersOptimizer(short size, int array[])\n{\n // Do the same thing as above, but instead of accessing array[1]\n // all the time, access it once and store the result in a register,\n // which is much faster to do arithmetic with.\n register int a0 = a[0];\n register int a1 = a[1]; // access a[1] once\n for (int i = 2; i < (int)size; i++) {\n maybeModify(a0); // Give maybeModify a reference to a register\n array[i] += a1; // Use the saved register value over and over\n }\n a[0] = a0; // Store the modified a[0] back into the array\n}\n void maybeModify(int* x); // May modify x in some way\n\nvoid hurtTheCompilersOptimizer(short size, int array[])\n{\n // Same operation, only now with pointers, making the\n // optimization trickier.\n for (int i = 2; i < (int)size; i++) {\n maybeModify(&(array[0]));\n array[i] += array[1];\n }\n}\n F createF(int argument);\n\nvoid extending()\n{\n const F& ref = createF(5);\n std::cout << ref.getArgument() << std::endl;\n};\n createF(5) ref ref" }, { "answer_id": 21092239, "author": "Life", "author_id": 2143209, "author_profile": "https://Stackoverflow.com/users/2143209", "pm_score": 5, "selected": false, "text": ">>> The address that locates a variable within memory is\n what we call a reference to that variable. (5th paragraph at page 63)\n\n>>> The variable that stores the reference to another\n variable is what we call a pointer. (3rd paragraph at page 64)\n >>> reference stands for memory location\n>>> pointer is a reference container (Maybe because we will use it for\nseveral times, it is better to remember that reference.)\n int Tom(0);\nint & alias_Tom = Tom;\n alias_Tom alias of a variable typedef alias of a type Tom Tom" }, { "answer_id": 26370807, "author": "Tory", "author_id": 3093272, "author_profile": "https://Stackoverflow.com/users/3093272", "pm_score": 4, "selected": false, "text": "#include <iostream>\nint main(int argc, char** argv) {\n // Create a string on the heap\n std::string *str_ptr = new std::string(\"THIS IS A STRING\");\n // Dereference the string on the heap, and assign it to the reference\n std::string &str_ref = *str_ptr;\n // Not even a compiler warning! At least with gcc\n // Now lets try to print it's value!\n std::cout << str_ref << std::endl;\n // It works! Now lets print and compare actual memory addresses\n std::cout << str_ptr << \" : \" << &str_ref << std::endl;\n // Exactly the same, now remember to free the memory on the heap\n delete str_ptr;\n}\n THIS IS A STRING\n0xbb2070 : 0xbb2070\n int main(int argc, char** argv) {\n // In the actual new declaration let immediately de-reference and assign it to the reference\n std::string &str_ref = *(new std::string(\"THIS IS A STRING\"));\n // Once again, it works! (at least in gcc)\n std::cout << str_ref;\n // Once again it prints fine, however we have no pointer to the heap allocation, right? So how do we free the space we just ignorantly created?\n delete &str_ref;\n /*And, it works, because we are taking the memory address that the reference is\n storing, and deleting it, which is all a pointer is doing, just we have to specify\n the address with '&' whereas a pointer does that implicitly, this is sort of like\n calling delete &(*str_ptr); (which also compiles and runs fine).*/\n}\n THIS IS A STRING\n" }, { "answer_id": 28410732, "author": "Destructor", "author_id": 3777958, "author_profile": "https://Stackoverflow.com/users/3777958", "pm_score": 4, "selected": false, "text": "#include<iostream>\nusing namespace std;\n\nvoid swap(char * &str1, char * &str2)\n{\n char *temp = str1;\n str1 = str2;\n str2 = temp;\n}\n\nint main()\n{\n char *str1 = \"Hi\";\n char *str2 = \"Hello\";\n swap(str1, str2);\n cout<<\"str1 is \"<<str1<<endl;\n cout<<\"str2 is \"<<str2<<endl;\n return 0;\n}\n #include<stdio.h>\n/* Swaps strings by swapping pointers */\nvoid swap1(char **str1_ptr, char **str2_ptr)\n{\n char *temp = *str1_ptr;\n *str1_ptr = *str2_ptr;\n *str2_ptr = temp;\n}\n\nint main()\n{\n char *str1 = \"Hi\";\n char *str2 = \"Hello\";\n swap1(&str1, &str2);\n printf(\"str1 is %s, str2 is %s\", str1, str2);\n return 0;\n}\n #include <iostream>\nusing namespace std;\n\nint main()\n{\n int x = 10;\n int *ptr = &x;\n int &*ptr1 = ptr;\n}\n" }, { "answer_id": 41507371, "author": "dhokar.w", "author_id": 7383437, "author_profile": "https://Stackoverflow.com/users/7383437", "pm_score": 3, "selected": false, "text": "int* p = 0;\n int& p = 0; int& p=5 ; Int x = 0;\nInt y = 5;\nInt& p = x;\nInt& p1 = y;\n Int a = 6, b = 5;\nInt& rf = a;\n\nCout << rf << endl; // The result we will get is 6, because rf is referencing to the value of a.\n\nrf = b;\ncout << a << endl; // The result will be 5 because the value of b now will be stored into the address of a so the former value of a will be erased\n Std ::vector<int>v(10); // Initialize a vector with 10 elements\nV[5] = 5; // Writing the value 5 into the 6 element of our vector, so if the returned type of operator [] was a pointer and not a reference we should write this *v[5]=5, by making a reference we overwrite the element by using the assignment \"=\"\n" }, { "answer_id": 44957687, "author": "Ap31", "author_id": 6350858, "author_profile": "https://Stackoverflow.com/users/6350858", "pm_score": 4, "selected": false, "text": "T T& std::reference_wrapper<T> T& T& T&& str[0] = 'X'; char* str operator+(const T& a, const T& b)" }, { "answer_id": 47073963, "author": "Arthur Tacca", "author_id": 7008416, "author_profile": "https://Stackoverflow.com/users/7008416", "pm_score": 4, "selected": false, "text": "void fn1(std::string s);\nvoid fn2(const std::string& s);\nvoid fn3(std::string& s);\nvoid fn4(std::string* s);\n\nvoid bar() {\n std::string x;\n fn1(x); // Cannot modify x\n fn2(x); // Cannot modify x (without const_cast)\n fn3(x); // CAN modify x!\n fn4(&x); // Can modify x (but is obvious about it)\n}\n fn(x) x fn(&x) & & const const nullptr fn3()" }, { "answer_id": 47243714, "author": "Immac", "author_id": 3203817, "author_profile": "https://Stackoverflow.com/users/3203817", "pm_score": 2, "selected": false, "text": "// receives an alias of an int, an address of an int and an int value\npublic void my_function(int& a,int* b,int c){\n int d = 1; // declares an integer named d\n int &e = d; // declares that e is an alias of d\n // using either d or e will yield the same result as d and e name the same object\n int *f = e; // invalid, you are trying to place an object in an address\n // imagine writting your name in an address field \n int *g = f; // writes an address to an address\n g = &d; // &d means get me the address of the object named d you could also\n // use &e as it is an alias of d and write it on g, which is an address so it's ok\n}\n" }, { "answer_id": 51658995, "author": "Mark Lakata", "author_id": 364818, "author_profile": "https://Stackoverflow.com/users/364818", "pm_score": 2, "selected": false, "text": "in out void DoSomething(const Foo& thisIsAnInput, Foo* thisIsAnOutput)\n{\n if (thisIsAnOuput)\n *thisIsAnOutput = thisIsAnInput;\n}\n" }, { "answer_id": 54222315, "author": "ebasconp", "author_id": 1680261, "author_profile": "https://Stackoverflow.com/users/1680261", "pm_score": 2, "selected": false, "text": "my_point operator+(const my_point& a, const my_point& b)\n{\n return { a.x + b.x, a.y + b.y };\n}\n" }, { "answer_id": 54731129, "author": "FrankHB", "author_id": 2307646, "author_profile": "https://Stackoverflow.com/users/2307646", "pm_score": 5, "selected": false, "text": "& && * cv && std::initializer_list [] * + & const && operator= ++ int unique_ptr shared_ptr std::optional observer_ptr operator new void* void*" }, { "answer_id": 57363123, "author": "Gerard ONeill", "author_id": 1331672, "author_profile": "https://Stackoverflow.com/users/1331672", "pm_score": 1, "selected": false, "text": "int x = 1;\nint *y = &x;\nint &z = x;\n x = 2;\n*y = 2;\nz = 2;\n int *yz = &z; -- legal\nint **yy = &y; -- legal\n\nint *yx = &x; -- legal; notice how this looks like the z example. x and z are equivalent.\n x++;\nz++;\n\n*y++; // what people assume is happening behind the scenes, but isn't. it would produce the same results in this example.\n*(y++); // this one adds to the pointer, and then dereferences it. It makes sense that a pointer datatype (an address) can be incremented. Just like an int can be incremented. \n" }, { "answer_id": 59591539, "author": "S.S. Anne", "author_id": 10795151, "author_profile": "https://Stackoverflow.com/users/10795151", "pm_score": 3, "selected": false, "text": "NULL &obj + 5 int &ri = i;\n i" }, { "answer_id": 59748316, "author": "Sadhana Singh", "author_id": 9011579, "author_profile": "https://Stackoverflow.com/users/9011579", "pm_score": 3, "selected": false, "text": "int a = 20;\nint &r = a;\nr = 40; /* now the value of a is changed to 40 */\n\nint b =20;\nint *ptr;\nptr = &b; /*assigns address of b to ptr not the value */\n" }, { "answer_id": 62199065, "author": "Lewis Kelsey", "author_id": 7194773, "author_profile": "https://Stackoverflow.com/users/7194773", "pm_score": 4, "selected": false, "text": "int * const a = &b int& a = b const int * const a #include <iostream>\n\nint main() {\n int a =1;\n int* b = &a;\n std::cout << b ;\n}\n\nint main() {\n int a =1;\n int& b = a;\n std::cout << &b ;\n}\n they both have the same assembly output\n-Ofast:\nmain:\n sub rsp, 24\n mov edi, OFFSET FLAT:_ZSt4cout\n lea rsi, [rsp+12]\n mov DWORD PTR [rsp+12], 1\n call std::basic_ostream<char, std::char_traits<char> >& std::basic_ostream<char, std::char_traits<char> >::_M_insert<void const*>(void const*)\n xor eax, eax\n add rsp, 24\n ret\n--------------------------------------------------------------------\n-O0:\nmain:\n push rbp\n mov rbp, rsp\n sub rsp, 16\n mov DWORD PTR [rbp-12], 1\n lea rax, [rbp-12]\n mov QWORD PTR [rbp-8], rax\n mov rax, QWORD PTR [rbp-8]\n mov rsi, rax\n mov edi, OFFSET FLAT:_ZSt4cout\n call std::basic_ostream<char, std::char_traits<char> >::operator<<(void const*)\n mov eax, 0\n leave\n ret\n #include <iostream>\nint b=1;\nstruct A {int* i=&b; int& j=b;};\nA a;\nint main() {\n std::cout << &a.j << &a.i;\n}\n\nThe address of b is stored twice in the object. \n\na:\n .quad b\n .quad b\n mov rax, QWORD PTR a[rip+8] //&a.j\n mov esi, OFFSET FLAT:a //&a.i\n" }, { "answer_id": 68188598, "author": "Sarath Govind", "author_id": 12284466, "author_profile": "https://Stackoverflow.com/users/12284466", "pm_score": 2, "selected": false, "text": "int b = 15;\nint *q = &b;\n int *q;\nq = &b;\n int b=15;\nint &c=b;\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/123/" ]
57,484
<p>I'm trying to do a basic "OR" on three fields using a hibernate criteria query.</p> <p>Example</p> <pre><code>class Whatever{ string name; string address; string phoneNumber; } </code></pre> <p>I'd like to build a criteria query where my search string could match "name" or "address" or "phoneNumber".</p>
[ { "answer_id": 57526, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 8, "selected": true, "text": "Restrictions.disjuntion() session.createCriteria(Whatever.class)\n .add(Restrictions.disjunction()\n .add(Restrictions.eq(\"name\", queryString))\n .add(Restrictions.eq(\"address\", queryString))\n .add(Restrictions.eq(\"phoneNumber\", queryString))\n );\n" }, { "answer_id": 57541, "author": "Rob Oxspring", "author_id": 1867, "author_profile": "https://Stackoverflow.com/users/1867", "pm_score": 6, "selected": false, "text": "Criteria c = session.createCriteria(Whatever.class);\nDisjunction or = Restrictions.disjunction();\nor.add(Restrictions.eq(\"name\",searchString));\nor.add(Restrictions.eq(\"address\",searchString));\nor.add(Restrictions.eq(\"phoneNumber\",searchString));\nc.add(or);\n" }, { "answer_id": 58643, "author": "Geir-Tore Lindsve", "author_id": 4582, "author_profile": "https://Stackoverflow.com/users/4582", "pm_score": 2, "selected": false, "text": "ICriteria c = session.CreateCriteria(typeof (Whatever))\n .Add(Expression.Disjunction()\n .Add(Expression.Eq(\"name\", searchString))\n .Add(Expression.Eq(\"address\", searchString))\n .Add(Expression.Eq(\"phoneNumber\", searchString)));\n" }, { "answer_id": 25283984, "author": "Dharmender Rawat", "author_id": 3936966, "author_profile": "https://Stackoverflow.com/users/3936966", "pm_score": 4, "selected": false, "text": " //Expression : (c1 AND c2) OR (c3) \n\n\n Criteria criteria = session.createCriteria(Employee.class);\n\n Criterion c1 = Restrictions.like(\"name\", \"%e%\");\n Criterion c2 = Restrictions.ge(\"salary\", 10000.00);\n Criterion c3 = Restrictions.like(\"name\", \"%YYY%\");\n Criterion c4 = Restrictions.or(Restrictions.and(c1, c2), c3);\n criteria.add(c4);\n" }, { "answer_id": 25294252, "author": "Dharmender Rawat", "author_id": 3936975, "author_profile": "https://Stackoverflow.com/users/3936975", "pm_score": 3, "selected": false, "text": "//Expression : (c1 AND c2) OR (c3) \n\n\n Criteria criteria = session.createCriteria(Employee.class);\n\n Criterion c1 = Restrictions.like(\"name\", \"%e%\");\n Criterion c2 = Restrictions.ge(\"salary\", 10000.00);\n Criterion c3 = Restrictions.like(\"name\", \"%YYY%\");\n Criterion c4 = Restrictions.or(Restrictions.and(c1, c2), c3);\n criteria.add(c4);\n\n //Same thing can be done for (c1 OR c2) AND c3, or any complex expression.\n" }, { "answer_id": 36494224, "author": "Tiago Medici", "author_id": 6117311, "author_profile": "https://Stackoverflow.com/users/6117311", "pm_score": 1, "selected": false, "text": "Criteria query = getCriteria(\"ENTITY_NAME\");\nquery.add(Restrictions.ne(\"column Name\", current _value));\n\nDisjunction disjunction = Restrictions.disjunction();\n\nif (param_1 != null)\n disjunction.add(Restrictions.or(Restrictions.eq(\"column Name\", param1)));\n\nif (param_2 != null)\n disjunction.add(Restrictions.or(Restrictions.eq(\"column Name\", param_2)));\n\nif (param_3 != null)\n disjunction.add(Restrictions.or(Restrictions.eq(\"column Name\", param_3)));\nif (param_4 != null && param_5 != null)\n disjunction.add(Restrictions.or(Restrictions.and(Restrictions.eq(\"column Name\", param_4 ), Restrictions.eq(\"column Name\", param_5 ))));\n\nif (disjunction.conditions() != null && disjunction.conditions().iterator().hasNext())\n query.add(Restrictions.and(disjunction));\n\nreturn query.list();\n" }, { "answer_id": 56698228, "author": "ronak", "author_id": 6673843, "author_profile": "https://Stackoverflow.com/users/6673843", "pm_score": 1, "selected": false, "text": "criteria.add( Restrictions.or(\n Restrictions.eq(ch.getPath(ch.propertyResolver().getXXXX()), \"OR_STRING\"),\n Restrictions.in(ch.getPath(ch.propertyResolver().getYYYY()), new String[]{\"AA\",\"BB\",\"CC\"})\n ));\n and (\n this_.XXXX=? \n or this_.YYYY in (\n ?, ?, ?\n )\n ) \n" }, { "answer_id": 63181989, "author": "Gaspar", "author_id": 3681565, "author_profile": "https://Stackoverflow.com/users/3681565", "pm_score": 1, "selected": false, "text": "Predicate List<Predicate> predicates = new ArrayList<>();\nif (...) {\n predicates.add(...);\n}\n\ncriteriaQuery.where(cb.or(predicates.toArray(new Predicate[predicates.size()])));\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57484", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1310/" ]
57,488
<p>Does anyone know of a way to declare a date constant that is compatible with international dates?</p> <p>I've tried:</p> <pre><code>' not international compatible public const ADate as Date = #12/31/04# ' breaking change if you have an optional parameter that defaults to this value ' because it isnt constant. public shared readonly ADate As New Date(12, 31, 04) </code></pre>
[ { "answer_id": 57511, "author": "Rob Cooper", "author_id": 832, "author_profile": "https://Stackoverflow.com/users/832", "pm_score": 0, "selected": false, "text": "public static DateTime SadDayForAll()\n{\n return new DateTime(2001, 09, 11);\n}\n" }, { "answer_id": 57695, "author": "Michael Haren", "author_id": 29, "author_profile": "https://Stackoverflow.com/users/29", "pm_score": 1, "selected": false, "text": "Dim FirstDate as Date = Date.UtcNow() 'or this: = NewDate (2008,09,10)'\nDim SecondDate as Date\n\nSecondDate = FirstDate.AddDays(1)\n HeaderLabel.Text = SecondDate.ToString()\n Dim BadDate as Date = CDate(\"2/20/2000\")\n Dim OkButBadPracticeDate as Date = CDate(\"2/20/2000\", CultureInfo.InvariantCulture)\n" }, { "answer_id": 59626, "author": "Jason DeFontes", "author_id": 6159, "author_profile": "https://Stackoverflow.com/users/6159", "pm_score": 4, "selected": true, "text": "public const ADate as Date = #12/31/04#\n .field public static initonly valuetype [mscorlib]System.DateTime ADate\n.custom instance void [mscorlib]System.Runtime.CompilerServices.DateTimeConstantAttribute::.ctor(int64) = ( 01 00 00 C0 2F CE E2 BC C6 08 00 00 )\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57488", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5966/" ]
57,493
<p>In my WPF application, I have a number of databound TextBoxes. The <code>UpdateSourceTrigger</code> for these bindings is <code>LostFocus</code>. The object is saved using the File menu. The problem I have is that it is possible to enter a new value into a TextBox, select Save from the File menu, and never persist the new value (the one visible in the TextBox) because accessing the menu does not remove focus from the TextBox. How can I fix this? Is there some way to force all the controls in a page to databind?</p> <p><em>@palehorse: Good point. Unfortunately, I need to use LostFocus as my UpdateSourceTrigger in order to support the type of validation I want.</em></p> <p><em>@dmo: I had thought of that. It seems, however, like a really inelegant solution for a relatively simple problem. Also, it requires that there be some control on the page which is is always visible to receive the focus. My application is tabbed, however, so no such control readily presents itself.</em></p> <p><em>@Nidonocu: The fact that using the menu did not move focus from the TextBox confused me as well. That is, however, the behavior I am seeing. The following simple example demonstrates my problem:</em></p> <pre class="lang-xml prettyprint-override"><code>&lt;Window x:Class="WpfApplication2.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="300" Width="300"&gt; &lt;Window.Resources&gt; &lt;ObjectDataProvider x:Key="MyItemProvider" /&gt; &lt;/Window.Resources&gt; &lt;DockPanel LastChildFill="True"&gt; &lt;Menu DockPanel.Dock="Top"&gt; &lt;MenuItem Header="File"&gt; &lt;MenuItem Header="Save" Click="MenuItem_Click" /&gt; &lt;/MenuItem&gt; &lt;/Menu&gt; &lt;StackPanel DataContext="{Binding Source={StaticResource MyItemProvider}}"&gt; &lt;Label Content="Enter some text and then File &gt; Save:" /&gt; &lt;TextBox Text="{Binding ValueA}" /&gt; &lt;TextBox Text="{Binding ValueB}" /&gt; &lt;/StackPanel&gt; &lt;/DockPanel&gt; &lt;/Window&gt; </code></pre> <pre><code>using System; using System.Text; using System.Windows; using System.Windows.Data; namespace WpfApplication2 { public partial class Window1 : Window { public MyItem Item { get { return (FindResource("MyItemProvider") as ObjectDataProvider).ObjectInstance as MyItem; } set { (FindResource("MyItemProvider") as ObjectDataProvider).ObjectInstance = value; } } public Window1() { InitializeComponent(); Item = new MyItem(); } private void MenuItem_Click(object sender, RoutedEventArgs e) { MessageBox.Show(string.Format("At the time of saving, the values in the TextBoxes are:\n'{0}'\nand\n'{1}'", Item.ValueA, Item.ValueB)); } } public class MyItem { public string ValueA { get; set; } public string ValueB { get; set; } } } </code></pre>
[ { "answer_id": 58451, "author": "rudigrobler", "author_id": 5147, "author_profile": "https://Stackoverflow.com/users/5147", "pm_score": 3, "selected": false, "text": "TextBox focusedTextBox = Keyboard.FocusedElement as TextBox;\nif (focusedTextBox != null)\n{\n focusedTextBox.GetBindingExpression(TextBox.TextProperty).UpdateSource();\n}\n" }, { "answer_id": 229738, "author": "Sam", "author_id": 7021, "author_profile": "https://Stackoverflow.com/users/7021", "pm_score": 0, "selected": false, "text": "IInputElement x = System.Windows.Input.Keyboard.FocusedElement;\nDummyField.Focus();\nx.Focus();\n TextBox t = Keyboard.FocusedElement as TextBox;\nif ((t != null) && (t.GetBindingExpression(TextBox.TextProperty) != null))\n t.GetBindingExpression(TextBox.TextProperty).UpdateSource();\n\nComboBox c = Keyboard.FocusedElement as ComboBox;\nif ((c != null) && (c.GetBindingExpression(ComboBox.TextProperty) != null))\n c.GetBindingExpression(ComboBox.TextProperty).UpdateSource();\n" }, { "answer_id": 1764845, "author": "BigBlondeViking", "author_id": 119910, "author_profile": "https://Stackoverflow.com/users/119910", "pm_score": 5, "selected": false, "text": "<Menu FocusManager.IsFocusScope=\"False\" >\n" }, { "answer_id": 4724766, "author": "Dave the Rave", "author_id": 580011, "author_profile": "https://Stackoverflow.com/users/580011", "pm_score": 4, "selected": false, "text": "Control currentControl = System.Windows.Input.Keyboard.FocusedElement as Control;\n\nif (currentControl != null)\n{\n // Force focus away from the current control to update its binding source.\n currentControl.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));\n currentControl.Focus();\n}\n" }, { "answer_id": 6195116, "author": "Shawn Nelson", "author_id": 437254, "author_profile": "https://Stackoverflow.com/users/437254", "pm_score": 0, "selected": false, "text": "var currentControl = System.Windows.Input.Keyboard.FocusedElement;\nif (currentControl != null)\n{\n Type type = currentControl.GetType();\n if (type.GetMethod(\"MoveFocus\") != null && type.GetMethod(\"Focus\") != null)\n {\n try\n {\n type.GetMethod(\"MoveFocus\").Invoke(currentControl, new object[] { new TraversalRequest(FocusNavigationDirection.Next) });\n type.GetMethod(\"Focus\").Invoke(currentControl, null);\n }\n catch (Exception ex)\n {\n throw new Exception(\"Unable to handle unknown type: \" + type.Name, ex);\n }\n }\n}\n" }, { "answer_id": 7518908, "author": "Ram", "author_id": 959677, "author_profile": "https://Stackoverflow.com/users/959677", "pm_score": 2, "selected": false, "text": " <StackPanel DataContext=\"{Binding Source={StaticResource MyItemProvider}}\"> \n <Label Content=\"Enter some text and then File > Save:\" /> \n <TextBox Text=\"{Binding ValueA, UpdateSourceTrigger=PropertyChanged}\" /> \n <TextBox Text=\"{Binding ValueB, UpdateSourceTrigger=PropertyChanged}\" /> \n </StackPanel> \n" }, { "answer_id": 8680327, "author": "Nathan Swannet", "author_id": 983690, "author_profile": "https://Stackoverflow.com/users/983690", "pm_score": 1, "selected": false, "text": "public static class Validator\n{\n private static Dictionary<String, List<DependencyProperty>> gdicCachedDependencyProperties = new Dictionary<String, List<DependencyProperty>>();\n\n public static Boolean IsValid(DependencyObject Parent)\n {\n // Move focus and reset it to update bindings which or otherwise not processed until losefocus\n IInputElement lfocusedElement = Keyboard.FocusedElement;\n if (lfocusedElement != null && lfocusedElement is UIElement)\n {\n // Move to previous AND to next InputElement (if your next InputElement is a menu, focus will not be lost -> therefor move in both directions)\n (lfocusedElement as UIElement).MoveFocus(new TraversalRequest(FocusNavigationDirection.Previous));\n (lfocusedElement as UIElement).MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));\n Keyboard.ClearFocus();\n }\n\n if (Parent as UIElement == null || (Parent as UIElement).Visibility != Visibility.Visible)\n return true;\n\n // Validate all the bindings on the parent \n Boolean lblnIsValid = true;\n foreach (DependencyProperty aDependencyProperty in GetAllDependencyProperties(Parent))\n {\n if (BindingOperations.IsDataBound(Parent, aDependencyProperty))\n {\n // Get the binding expression base. This way all kinds of bindings (MultiBinding, PropertyBinding, ...) can be updated\n BindingExpressionBase lbindingExpressionBase = BindingOperations.GetBindingExpressionBase(Parent, aDependencyProperty);\n if (lbindingExpressionBase != null)\n {\n lbindingExpressionBase.ValidateWithoutUpdate();\n if (lbindingExpressionBase.HasError)\n lblnIsValid = false;\n }\n }\n }\n\n if (Parent is Visual || Parent is Visual3D)\n {\n // Fetch the visual children (in case of templated content, the LogicalTreeHelper will return no childs)\n Int32 lintVisualChildCount = VisualTreeHelper.GetChildrenCount(Parent);\n for (Int32 lintVisualChildIndex = 0; lintVisualChildIndex < lintVisualChildCount; lintVisualChildIndex++)\n if (!IsValid(VisualTreeHelper.GetChild(Parent, lintVisualChildIndex)))\n lblnIsValid = false;\n }\n\n if (lfocusedElement != null)\n lfocusedElement.Focus();\n\n return lblnIsValid;\n }\n\n public static List<DependencyProperty> GetAllDependencyProperties(DependencyObject DependencyObject)\n {\n Type ltype = DependencyObject.GetType();\n if (gdicCachedDependencyProperties.ContainsKey(ltype.FullName))\n return gdicCachedDependencyProperties[ltype.FullName];\n\n List<DependencyProperty> llstDependencyProperties = new List<DependencyProperty>();\n List<FieldInfo> llstFieldInfos = ltype.GetFields(BindingFlags.Public | BindingFlags.FlattenHierarchy | BindingFlags.Instance | BindingFlags.Static).Where(Field => Field.FieldType == typeof(DependencyProperty)).ToList();\n foreach (FieldInfo aFieldInfo in llstFieldInfos)\n llstDependencyProperties.Add(aFieldInfo.GetValue(null) as DependencyProperty);\n gdicCachedDependencyProperties.Add(ltype.FullName, llstDependencyProperties);\n\n return llstDependencyProperties;\n }\n}\n" }, { "answer_id": 9840108, "author": "Tomer", "author_id": 805138, "author_profile": "https://Stackoverflow.com/users/805138", "pm_score": 2, "selected": false, "text": "<Button Focusable=\"True\" Command=\"{Binding CustomSaveCommand}\"/>\n" }, { "answer_id": 26902637, "author": "kenjiuno", "author_id": 974413, "author_profile": "https://Stackoverflow.com/users/974413", "pm_score": 0, "selected": false, "text": "<R:RibbonWindow Closing=\"RibbonWindow_Closing\" ...>\n\n <FrameworkElement.BindingGroup>\n <BindingGroup />\n </FrameworkElement.BindingGroup>\n\n ...\n</R:RibbonWindow>\n private void RibbonWindow_Closing(object sender, CancelEventArgs e) {\n e.Cancel = !NeedSave();\n}\n\nbool NeedSave() {\n BindingGroup.CommitEdit();\n\n // Insert your business code to check modifications.\n\n // return true; if Saved/DontSave/NotChanged\n // return false; if Cancel\n}\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57493", "https://Stackoverflow.com", "https://Stackoverflow.com/users/317/" ]
57,518
<p>Is it possible for <code>SelectNodes()</code> called on an <code>XmlDocument</code> to return null?</p> <p>My predicament is that I am trying to reach 100% unit test code coverage; ReSharper tells me that I need to guard against a null return from the <code>SelectNodes()</code> method, but I can see no way that an XmlDocument can return null (and therefore, no way to test my guard clause and reach 100% unit test coverage!)</p>
[ { "answer_id": 57532, "author": "Jeremy McGee", "author_id": 3546, "author_profile": "https://Stackoverflow.com/users/3546", "pm_score": 3, "selected": true, "text": "using {} finally {} catch {}" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57518", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5975/" ]
57,522
<p>I can create the following and reference it using</p> <pre><code>area[0].states[0] area[0].cities[0] var area = [ { "State" : "Texas", "Cities" : ['Austin','Dallas','San Antonio'] }, { "State" :"Arkansas", "Cities" : ['Little Rock','Texarkana','Hot Springs'] } ] ; </code></pre> <p>How could I restructure "area" so that if I know the name of the state, I can use it in a reference to get the array of cities?</p> <p>Thanks</p> <p><strong>EDIT</strong> Attempting to implement with the answers I received (thanks @Eli Courtwright, @17 of 26, and @JasonBunting) I realize my question was incomplete. I need to loop through "area" the first time referencing "state" by index, then when I have the selection of the "state", I need to loop back through a structure using the value of "state" to get the associated "cities". I do want to start with the above structure (although I am free to build it how I want) and I don't mind a conversion similar to @eli's answer (although I was not able to get that conversion to work). Should have been more complete in first question. Trying to implement 2 select boxes where the selection from the first populates the second...I will load this array structure in a js file when the page loads.</p>
[ { "answer_id": 57531, "author": "Eli Courtwright", "author_id": 1694, "author_profile": "https://Stackoverflow.com/users/1694", "pm_score": 2, "selected": true, "text": "area = {\n \"Texas\": ['Austin','Dallas','San Antonio']\n}\n states = {}\nfor(var j=0; j<area.length; j++)\n states[ area[0].State ] = area[0].Cities\n states[\"Texas\"]\n ['Austin','Dallas','San Antonio']\n" }, { "answer_id": 57535, "author": "17 of 26", "author_id": 2284, "author_profile": "https://Stackoverflow.com/users/2284", "pm_score": 2, "selected": false, "text": "var area = \n{\n \"Texas\" : { \"Cities\" : ['Austin','Dallas','San Antonio'] },\n \"Arkansas\" : { \"Cities\" : ['Little Rock','Texarkana','Hot Springs'] }\n};\n area[\"Texas\"].Cities[0];\n" }, { "answer_id": 57536, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 1, "selected": false, "text": "var area = {\n \"Texas\" : [\"Austin\",\"Dallas\",\"San Antonio\"], \n \"Arkansas\" : [\"Little Rock\",\"Texarkana\",\"Hot Springs\"]\n};\n\n// area[\"Texas\"] would return [\"Austin\",\"Dallas\",\"San Antonio\"]\n" }, { "answer_id": 58062, "author": "Jay Corbett", "author_id": 2755, "author_profile": "https://Stackoverflow.com/users/2755", "pm_score": 2, "selected": false, "text": "<select id=\"states\" size=\"2\"></select>\n<select id=\"cities\" size=\"3\"></select>\n var area = [\n {\n \"states\" : \"Texas\",\n \"cities\" : ['Austin','Dallas','San Antonio']\n },\n {\n \"states\" :\"Arkansas\",\n \"cities\" : ['Little Rock','Texarkana','Hot Springs']\n }\n ] ;\n $(function() { // create an array to be referenced by state name\n state = [] ;\n for(var i=0; i<area.length; i++) {\n state[area[i].states] = area[i].cities ;\n }\n});\n\n$(function() {\n // populate states select box\n var options = '' ;\n for (var i = 0; i < area.length; i++) {\n options += '<option value=\"' + area[i].states + '\">' + area[i].states + '</option>'; \n }\n $(\"#states\").html(options); // populate select box with array\n\n // selecting state (change) will populate cities select box\n $(\"#states\").bind(\"change\",\n function() {\n $(\"#cities\").children().remove() ; // clear select box\n var options = '' ;\n for (var i = 0; i < state[this.value].length; i++) { \n options += '<option value=\"' + state[this.value][i] + '\">' + state[this.value][i] + '</option>'; \n }\n $(\"#cities\").html(options); // populate select box with array\n } // bind function end\n ); // bind end \n});\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57522", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2755/" ]
57,537
<p>In my Servlet I would like to access the root of the context so that I can do some JavaScript minifying.</p> <p>It would be possible to do the minify as part of the install process but I would like to do it on Servlet startup to reduce the implementation cost.</p> <p>Does anyone know of a method for getting the context directory so that I can load and write files to disk?</p>
[ { "answer_id": 57563, "author": "Walter Rumsby", "author_id": 1654, "author_profile": "https://Stackoverflow.com/users/1654", "pm_score": -1, "selected": false, "text": "public class MyServlet extends HttpServlet {\n\n public void init(final ServletConfig config) {\n final String context = config.getServletContext();\n ...\n }\n\n ...\n}\n" }, { "answer_id": 57595, "author": "ScArcher2", "author_id": 1310, "author_profile": "https://Stackoverflow.com/users/1310", "pm_score": 5, "selected": true, "text": "public class MyServlet extends HttpServlet {\n\n public void init(final ServletConfig config) {\n final String context = config.getServletContext().getRealPath(\"/\");\n ...\n }\n\n ...\n}\n" }, { "answer_id": 1807990, "author": "diätpillen", "author_id": 219965, "author_profile": "https://Stackoverflow.com/users/219965", "pm_score": 0, "selected": false, "text": "script // set up a global java script variable to access the context path\nvar contextPath = \"${request.contextPath}\" \n" }, { "answer_id": 1808295, "author": "BalusC", "author_id": 157882, "author_profile": "https://Stackoverflow.com/users/157882", "pm_score": 2, "selected": false, "text": "ServletContext#getResource() WebContent/js/file.js Servlet File File file = new File(getServletContext().getResource(\"/js/file.js\").getFile());\n InputStream InputStream input = getServletContext().getResourceAsStream(\"/js/file.js\");\n Servlet ServletContextListener contextInitialized()" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57537", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4682/" ]
57,552
<p>Ok, so I got my extender working on a default.aspx page on my website and it looks good. I basically copied and pasted the code for it into a user control control.ascx page. When I do this I completely loose the functionality (just shows the target control label and no dropdown, even upon hover). Is there any reason why it doesn't work in a custom user control inside a masterpage setup?</p> <p>Edit: Didn't quite do the trick. Any other suggestions? Its in a master page setup, using eo web tabs (I tried it inside the tabs and outside the tabs but on the same page as the tabs, to no avail), and its in a custom user control. Think there are dependency issues?</p>
[ { "answer_id": 57572, "author": "Craig", "author_id": 2894, "author_profile": "https://Stackoverflow.com/users/2894", "pm_score": 0, "selected": false, "text": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\" >\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57552", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1491425/" ]
57,560
<p>What's the best way in c# to determine is a given QFE/patch has been installed?</p>
[ { "answer_id": 57626, "author": "rpetrich", "author_id": 4007, "author_profile": "https://Stackoverflow.com/users/4007", "pm_score": 1, "selected": false, "text": "System.Diagnostics.FileVersionInfo.GetVersionInfo(path)" }, { "answer_id": 205258, "author": "Bob King", "author_id": 6897, "author_profile": "https://Stackoverflow.com/users/6897", "pm_score": 3, "selected": true, "text": "strComputer = \".\"\nSet objWMIService = GetObject(\"winmgmts:\" _\n & \"{impersonationLevel=impersonate}!\\\\\" & strComputer & \"\\root\\cimv2\")\nSet colQuickFixes = objWMIService.ExecQuery _\n (\"Select * from Win32_QuickFixEngineering\")\nFor Each objQuickFix in colQuickFixes\n Wscript.Echo \"Computer: \" & objQuickFix.CSName\n Wscript.Echo \"Description: \" & objQuickFix.Description\n Wscript.Echo \"Hot Fix ID: \" & objQuickFix.HotFixID\n Wscript.Echo \"Installation Date: \" & objQuickFix.InstallDate\n Wscript.Echo \"Installed By: \" & objQuickFix.InstalledBy\nNext\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57560", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2564/" ]
57,567
<p>Is there an advantage to dynamically attaching/detaching event handlers?</p> <p>Would manually detaching handlers help ensure that there isn't a reference remaining to a disposed object?</p>
[ { "answer_id": 57605, "author": "OwenP", "author_id": 2547, "author_profile": "https://Stackoverflow.com/users/2547", "pm_score": 2, "selected": false, "text": "Handles AddHandler \nPublic Class Form1\n\n Public Sub New()\n ' This call is required by the Windows Form Designer. '\n InitializeComponent()\n\n ' Add any initialization after the InitializeComponent() call. '\n AddHandler Me.Load, AddressOf Form1_Load\n End Sub\n\n Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load\n Dim breakpoint As Integer = 4\n End Sub\nEnd Class IL_0000: nop\n IL_0001: ldarg.0\n IL_0002: call instance void [System.Windows.Forms]System.Windows.Forms.Form::.ctor()\n IL_0007: nop\n IL_0008: ldarg.0\n IL_0009: ldarg.0\n IL_000a: dup\n IL_000b: ldvirtftn instance void WindowsApplication1.Form1::Form1_Load(object,\n class [mscorlib]System.EventArgs)\n IL_0011: newobj instance void [mscorlib]System.EventHandler::.ctor(object,\n native int)\n IL_0016: call instance void [System.Windows.Forms]System.Windows.Forms.Form::add_Load(class [mscorlib]System.EventHandler)\n\n '... lots of lines here '\n\n IL_0047: ldarg.0\n IL_0048: callvirt instance void WindowsApplication1.Form1::InitializeComponent()\n IL_004d: nop\n IL_004e: ldarg.0\n IL_004f: ldarg.0\n IL_0050: dup\n IL_0051: ldvirtftn instance void WindowsApplication1.Form1::Form1_Load(object,\n class [mscorlib]System.EventArgs)\n IL_0057: newobj instance void [mscorlib]System.EventHandler::.ctor(object,\n native int)\n IL_005c: callvirt instance void [System.Windows.Forms]System.Windows.Forms.Form::add_Load(class [mscorlib]System.EventHandler)\n IL_0061: nop\n IL_0062: nop\n IL_0063: ret\n} // end of method Form1::.ctor" }, { "answer_id": 19306349, "author": "supercat", "author_id": 363751, "author_profile": "https://Stackoverflow.com/users/363751", "pm_score": 2, "selected": false, "text": "WithEvents Nothing" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57567", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4770/" ]
57,584
<p>I've found some examples using the Win32 api or simulating the ^+ button combination (<kbd>ctrl</kbd>-<kbd>+</kbd>) <a href="http://www.codeproject.com/KB/list/AutoResize.aspx" rel="nofollow noreferrer">using SendKeys</a>, but at least with the SendKeys method the listview grabs the cursor and sets it to an hourglass until I hit the start button on my keyboard. What is the cleanest way to do this?</p>
[ { "answer_id": 58102, "author": "Matt Nelson", "author_id": 788, "author_profile": "https://Stackoverflow.com/users/788", "pm_score": 5, "selected": true, "text": "myListView.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent)" }, { "answer_id": 54192601, "author": "Chris Raisin", "author_id": 5316401, "author_profile": "https://Stackoverflow.com/users/5316401", "pm_score": 0, "selected": false, "text": " Private Sub AutoSizeListViewColumns(oListView As ListView)\n Dim nCol As Integer = 0\n SuspendLayout()\n For nCol = 0 To (oListView.Columns.Count - 1)\n oListView.Columns(nCol).Width = -1 'forces autosizing on column\n Next\n oListView.Refresh()\n ResumeLayout()\n End Sub\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57584", "https://Stackoverflow.com", "https://Stackoverflow.com/users/327/" ]
57,586
<p>I get this error on an update panel within a popupControlExtender which is within a dragPanelExtender.</p> <p>I see that a lot of other people have this issue and have various fixes none of which have worked for me.</p> <p>I would love to hear a logical explanation for why this is occurring and a foolproof way to avoid such issues in the future.</p> <p>I have found that like others maintain this error does not occur when the trigger is a LinkButton rather than an ImageButton, still wondering if anyone has an explanation.</p>
[ { "answer_id": 5105155, "author": "Gorgsenegger", "author_id": 412036, "author_profile": "https://Stackoverflow.com/users/412036", "pm_score": 2, "selected": false, "text": "var script = @\"\nif (Sys &&\n Sys.WebForms && Sys.WebForms.PageRequestManager &&\n Sys.WebForms.PageRequestManager.getInstance) \n{\n var prm = Sys.WebForms.PageRequestManager.getInstance();\n if (prm &&\n !prm._postBackSettings)\n {\n prm._postBackSettings = prm._createPostBackSettings(false, null, null);\n }\";\n\nScriptManager.RegisterOnSubmitStatement(\n Page, \n Page.GetType(), \n \"FixPopupFormSubmit\", \n script);\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57586", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3821/" ]
57,599
<p>What would be the best way to calculate someone's age in years, months, and days in T-SQL (SQL Server 2000)?</p> <p>The <code>datediff</code> function doesn't handle year boundaries well, plus getting the months and days separate will be a bear. I know I can do it on the client side relatively easily, but I'd like to have it done in my <a href="http://en.wikipedia.org/wiki/Stored_procedure" rel="noreferrer">stored procedure</a>.</p>
[ { "answer_id": 57642, "author": "Michael Runyon", "author_id": 5405, "author_profile": "https://Stackoverflow.com/users/5405", "pm_score": 0, "selected": false, "text": "Select DateDiff(d,'1984-07-12','2008-09-11')\n\nSelect DateDiff(m,'1984-07-12','2008-09-11')\n\nSelect DateDiff(yyyy,'1984-07-12','2008-09-11')\n" }, { "answer_id": 57720, "author": "Dane", "author_id": 2929, "author_profile": "https://Stackoverflow.com/users/2929", "pm_score": 7, "selected": true, "text": "DECLARE @date datetime, @tmpdate datetime, @years int, @months int, @days int\nSELECT @date = '2/29/04'\n\nSELECT @tmpdate = @date\n\nSELECT @years = DATEDIFF(yy, @tmpdate, GETDATE()) - CASE WHEN (MONTH(@date) > MONTH(GETDATE())) OR (MONTH(@date) = MONTH(GETDATE()) AND DAY(@date) > DAY(GETDATE())) THEN 1 ELSE 0 END\nSELECT @tmpdate = DATEADD(yy, @years, @tmpdate)\nSELECT @months = DATEDIFF(m, @tmpdate, GETDATE()) - CASE WHEN DAY(@date) > DAY(GETDATE()) THEN 1 ELSE 0 END\nSELECT @tmpdate = DATEADD(m, @months, @tmpdate)\nSELECT @days = DATEDIFF(d, @tmpdate, GETDATE())\n\nSELECT @years, @months, @days\n" }, { "answer_id": 57748, "author": "Leonardo", "author_id": 1014, "author_profile": "https://Stackoverflow.com/users/1014", "pm_score": 2, "selected": false, "text": "CREATE PROCEDURE dbo.CalculateAge \n @dayOfBirth datetime\nAS\n\nDECLARE @today datetime, @thisYearBirthDay datetime\nDECLARE @years int, @months int, @days int\n\nSELECT @today = GETDATE()\n\nSELECT @thisYearBirthDay = DATEADD(year, DATEDIFF(year, @dayOfBirth, @today), @dayOfBirth)\n\nSELECT @years = DATEDIFF(year, @dayOfBirth, @today) - (CASE WHEN @thisYearBirthDay > @today THEN 1 ELSE 0 END)\n\nSELECT @months = MONTH(@today - @thisYearBirthDay) - 1\n\nSELECT @days = DAY(@today - @thisYearBirthDay) - 1\n\nSELECT @years, @months, @days\nGO\n" }, { "answer_id": 2809382, "author": "simon831", "author_id": 107062, "author_profile": "https://Stackoverflow.com/users/107062", "pm_score": 2, "selected": false, "text": "create function [dbo].[Age](@dayOfBirth datetime, @today datetime)\n RETURNS varchar(100)\nAS\n\nBegin\nDECLARE @thisYearBirthDay datetime\nDECLARE @years int, @months int, @days int\n\nset @thisYearBirthDay = DATEADD(year, DATEDIFF(year, @dayOfBirth, @today), @dayOfBirth)\nset @years = DATEDIFF(year, @dayOfBirth, @today) - (CASE WHEN @thisYearBirthDay > @today THEN 1 ELSE 0 END)\nset @months = MONTH(@today - @thisYearBirthDay) - 1\nset @days = DAY(@today - @thisYearBirthDay) - 1\n\nreturn cast(@years as varchar(2)) + ' years,' + cast(@months as varchar(2)) + ' months,' + cast(@days as varchar(3)) + ' days'\nend\n" }, { "answer_id": 3324468, "author": "sumesh", "author_id": 400953, "author_profile": "https://Stackoverflow.com/users/400953", "pm_score": 2, "selected": false, "text": "create procedure getDatedifference\n\n(\n @startdate datetime,\n @enddate datetime\n)\nas\nbegin\n declare @monthToShow int\n declare @dayToShow int\n\n --set @startdate='01/21/1934'\n --set @enddate=getdate()\n\n if (DAY(@startdate) > DAY(@enddate))\n begin\n set @dayToShow=0\n\n if (month(@startdate) > month(@enddate))\n begin\n set @monthToShow= (12-month(@startdate)+ month(@enddate)-1)\n end\n else if (month(@startdate) < month(@enddate))\n begin\n set @monthToShow= ((month(@enddate)-month(@startdate))-1)\n end\n else\n begin\n set @monthToShow= 11\n end\n -- set @monthToShow= convert(int, DATEDIFF(mm,0,DATEADD(dd,DATEDIFF(dd,0,@enddate)- DATEDIFF(dd,0,@startdate),0)))-((convert(int,FLOOR(DATEDIFF(day, @startdate, @enddate) / 365.25))*12))-1\n if(@monthToShow<0)\n begin\n set @monthToShow=0\n end\n\n declare @amonthbefore integer\n set @amonthbefore=Month(@enddate)-1\n if(@amonthbefore=0)\n begin\n set @amonthbefore=12\n end\n\n\n if (@amonthbefore in(1,3,5,7,8,10,12))\n begin\n set @dayToShow=31-DAY(@startdate)+DAY(@enddate)\n end\n if (@amonthbefore=2)\n begin\n IF (YEAR( @enddate ) % 4 = 0 AND YEAR( @enddate ) % 100 != 0) OR YEAR( @enddate ) % 400 = 0\n begin\n set @dayToShow=29-DAY(@startdate)+DAY(@enddate)\n end\n else\n begin\n set @dayToShow=28-DAY(@startdate)+DAY(@enddate)\n end\n end\n if (@amonthbefore in (4,6,9,11))\n begin\n set @dayToShow=30-DAY(@startdate)+DAY(@enddate)\n end\n end\n else\n begin\n --set @monthToShow=convert(int, DATEDIFF(mm,0,DATEADD(dd,DATEDIFF(dd,0,@enddate)- DATEDIFF(dd,0,@startdate),0)))-((convert(int,FLOOR(DATEDIFF(day, @startdate, @enddate) / 365.25))*12))\n if (month(@enddate)< month(@startdate))\n begin\n set @monthToShow=12+(month(@enddate)-month(@startdate))\n end\n else\n begin\n set @monthToShow= (month(@enddate)-month(@startdate))\n end\n set @dayToShow=DAY(@enddate)-DAY(@startdate)\n end\n\n SELECT\n FLOOR(DATEDIFF(day, @startdate, @enddate) / 365.25) as [yearToShow],\n @monthToShow as monthToShow ,@dayToShow as dayToShow ,\n convert(varchar,FLOOR(DATEDIFF(day, @startdate, @enddate) / 365.25)) +' Year ' + convert(varchar,@monthToShow) +' months '+convert(varchar,@dayToShow)+' days ' as age\n\n return\nend\n" }, { "answer_id": 6618627, "author": "tkerwood", "author_id": 463425, "author_profile": "https://Stackoverflow.com/users/463425", "pm_score": 4, "selected": false, "text": "SELECT CASE WHEN\n (DATEADD(year,DATEDIFF(year, @datestart ,@dateend) , @datestart) > @dateend)\nTHEN DATEDIFF(year, @datestart ,@dateend) -1\nELSE DATEDIFF(year, @datestart ,@dateend)\nEND\n" }, { "answer_id": 8312825, "author": "Keith", "author_id": 1071528, "author_profile": "https://Stackoverflow.com/users/1071528", "pm_score": 1, "selected": false, "text": "CREATE Function [dbo].[F_Get_Actual_Age](@pi_date1 datetime,@pi_date2 datetime)\nRETURNS Numeric(7,4)\nAS\nBEGIN\n\nDeclare \n @l_tmp_date DATETIME\n,@l_days1 DECIMAL(9,6)\n,@l_days2 DECIMAL(9,6)\n,@l_result DECIMAL(10,6)\n,@l_years DECIMAL(7,4)\n\n\n --Check to make sure there is a date for both inputs\n IF @pi_date1 IS NOT NULL and @pi_date2 IS NOT NULL \n BEGIN\n\n IF @pi_date1 > @pi_date2 --Make sure the \"older\" date is in @pi_date1\n BEGIN\n SET @l_tmp_date = @pi_date2\n SET @pi_date2 = @Pi_date1\n SET @pi_date1 = @l_tmp_date\n END\n\n --Check #1 If date1 + 1 year is greater than date2, difference must be less than 1 year\n IF DATEADD(YYYY,1,@pi_date1) > @pi_date2 \n BEGIN\n --How many days between the two dates (numerator)\n SET @l_days1 = DATEDIFF(dd,@pi_date1, @pi_date2) \n --subtract 1 year from date2 and calculate days bewteen it and date2\n --This is to get the denominator and accounts for leap year (365 or 366 days)\n SET @l_days2 = DATEDIFF(dd,dateadd(yyyy,-1,@pi_date2),@pi_date2) \n SET @l_years = @l_days1 / @l_days2 -- Do the math\n END\n ELSE\n --Check #2 Are the dates an exact number of years apart.\n --Calculate years bewteen date1 and date2, then add the years to date1, compare dates to see if exactly the same.\n IF DATEADD(YYYY,DATEDIFF(YYYY,@pi_date1,@pi_date2),@pi_date1) = @pi_date2 \n SET @l_years = DATEDIFF(YYYY,@pi_date1, @pi_date2) --AS Years, 'Exactly even Years' AS Msg\n ELSE\n BEGIN\n --Check #3 The rest of the cases.\n --Check if datediff, returning years, over or under states the years difference\n SET @l_years = DATEDIFF(YYYY,@pi_date1, @pi_date2)\n IF DATEADD(YYYY,@l_years,@pi_date1) > @pi_date2\n SET @l_years = @l_years -1\n --use basicly same logic as in check #1 \n SET @l_days1 = DATEDIFF(dd,DATEADD(YYYY,@l_years,@pi_date1), @pi_date2) \n SET @l_days2 = DATEDIFF(dd,dateadd(yyyy,-1,@pi_date2),@pi_date2) \n SET @l_years = @l_years + @l_days1 / @l_days2\n --SELECT @l_years AS Years, 'Years Plus' AS Msg\n END\n END\n ELSE\n SET @l_years = 0 --If either date was null\n\nRETURN @l_Years --Return the result as decimal(7,4)\nEND \n" }, { "answer_id": 9986532, "author": "Will", "author_id": 377058, "author_profile": "https://Stackoverflow.com/users/377058", "pm_score": 0, "selected": false, "text": "DateTime declare @birthdate datetime\nset @birthdate = '6/15/1974'\n\n--age in years - short version\nprint year(getdate() - @birthdate) - year(0)\n\n--age in years - visualization\ndeclare @mindate datetime\ndeclare @span datetime\n\nset @mindate = 0\nset @span = getdate() - @birthdate\n\nprint @mindate\nprint @birthdate\nprint getdate()\nprint @span\n--substract minyear from spanyear to get age in years\nprint year(@span) - year(@mindate)\nprint month(@span)\nprint day(@span)\n" }, { "answer_id": 11169287, "author": "Md. Munir Hussain", "author_id": 1476734, "author_profile": "https://Stackoverflow.com/users/1476734", "pm_score": 0, "selected": false, "text": "select trunc((sysdate -to_date('&input_birth_date_dd_mon_yy'))/365) years,\ntrunc(mod(( sysdate -to_date('&input_birth_date_dd_mon_yy'))/365,1)*12) months,\ntrunc((mod((mod((sysdate -to_date('&input_birth_date_dd_mon_yy'))/365,1)*12),1)*30)+1) days \n from dual\n" }, { "answer_id": 15061160, "author": "Junaid", "author_id": 2106258, "author_profile": "https://Stackoverflow.com/users/2106258", "pm_score": 0, "selected": false, "text": "CREATE FUNCTION DBO.GET_AGE\n(\n@DATE AS DATETIME\n)\nRETURNS VARCHAR(MAX)\nAS\nBEGIN\n\nDECLARE @YEAR AS VARCHAR(50) = ''\nDECLARE @MONTH AS VARCHAR(50) = ''\nDECLARE @DAYS AS VARCHAR(50) = ''\nDECLARE @RESULT AS VARCHAR(MAX) = ''\n\nSET @YEAR = CONVERT(VARCHAR,(SELECT DATEDIFF(MONTH,CASE WHEN DAY(@DATE) > DAY(GETDATE()) THEN DATEADD(MONTH,1,@DATE) ELSE @DATE END,GETDATE()) / 12 ))\nSET @MONTH = CONVERT(VARCHAR,(SELECT DATEDIFF(MONTH,CASE WHEN DAY(@DATE) > DAY(GETDATE()) THEN DATEADD(MONTH,1,@DATE) ELSE @DATE END,GETDATE()) % 12 ))\nSET @DAYS = DATEDIFF(DD,DATEADD(MM,CONVERT(INT,CONVERT(INT,@YEAR)*12 + CONVERT(INT,@MONTH)),@DATE),GETDATE())\n\nSET @RESULT = (RIGHT('00' + @YEAR, 2) + ' YEARS ' + RIGHT('00' + @MONTH, 2) + ' MONTHS ' + RIGHT('00' + @DAYS, 2) + ' DAYS')\n\nRETURN @RESULT\nEND\n\nSELECT DBO.GET_AGE('04/12/1986')\n" }, { "answer_id": 17064482, "author": "ZafarYousafi", "author_id": 134164, "author_profile": "https://Stackoverflow.com/users/134164", "pm_score": 1, "selected": false, "text": " Declare @BirthDate As DateTime\nSet @BirthDate = '1994-11-02'\n\nSELECT DATEDIFF(YEAR,@BirthDate,GETDATE()) - (CASE \nWHEN MONTH(@BirthDate)> MONTH(GETDATE()) THEN 1 \nWHEN MONTH(@BirthDate)= MONTH(GETDATE()) AND DAY(@BirthDate) > DAY(GETDATE()) THEN 1 \nElse 0 END)\n" }, { "answer_id": 18517263, "author": "user2730262", "author_id": 2730262, "author_profile": "https://Stackoverflow.com/users/2730262", "pm_score": 0, "selected": false, "text": "DECLARE @BirthDate datetime, @AgeInMonths int\nSET @BirthDate = '10/5/1971'\nSET @AgeInMonths -- Determine the age in \"months old\":\n = DATEDIFF(MONTH, @BirthDate, GETDATE()) -- .Get the difference in months\n - CASE WHEN DATEPART(DAY,GETDATE()) -- .If today was the 1st to 4th,\n < DATEPART(DAY,@BirthDate) -- (or before the birth day of month)\n THEN 1 ELSE 0 END -- ... don't count the month.\nSELECT @AgeInMonths / 12 as AgeYrs -- Divide by 12 months to get the age in years\n ,@AgeInMonths % 12 as AgeXtraMonths -- Get the remainder of dividing by 12 months = extra months\n ,DATEDIFF(DAY -- For the extra days, find the difference between, \n ,DATEADD(MONTH, @AgeInMonths -- 1. Last Monthly Birthday \n , @BirthDate) -- (if birthdays were celebrated monthly)\n ,GETDATE()) as AgeXtraDays -- 2. Today's date.\n" }, { "answer_id": 19204768, "author": "Ajit Bhgayanathan", "author_id": 2850876, "author_profile": "https://Stackoverflow.com/users/2850876", "pm_score": 4, "selected": false, "text": "Select cast((DATEDIFF(m, date_of_birth, GETDATE())/12) as varchar) + ' Y & ' + \n cast((DATEDIFF(m, date_of_birth, GETDATE())%12) as varchar) + ' M' as Age\n **63 Y & 2 M**\n" }, { "answer_id": 25912864, "author": "Jaugar Chang", "author_id": 3630826, "author_profile": "https://Stackoverflow.com/users/3630826", "pm_score": 3, "selected": false, "text": "declare @now date,@dob date, @now_i int,@dob_i int, @days_in_birth_month int\ndeclare @years int, @months int, @days int\nset @now = '2013-02-28' \nset @dob = '2012-02-29' -- Date of Birth\n\nset @now_i = convert(varchar(8),@now,112) -- iso formatted: 20130228\nset @dob_i = convert(varchar(8),@dob,112) -- iso formatted: 20120229\nset @years = ( @now_i - @dob_i)/10000\n-- (20130228 - 20120229)/10000 = 0 years\n\nset @months =(1200 + (month(@now)- month(@dob))*100 + day(@now) - day(@dob))/100 %12\n-- (1200 + 0228 - 0229)/100 % 12 = 11 months\n\nset @days_in_birth_month = day(dateadd(d,-1,left(convert(varchar(8),dateadd(m,1,@dob),112),6)+'01'))\nset @days = (sign(day(@now) - day(@dob))+1)/2 * (day(@now) - day(@dob))\n + (sign(day(@dob) - day(@now))+1)/2 * (@days_in_birth_month - day(@dob) + day(@now))\n-- ( (-1+1)/2*(28 - 29) + (1+1)/2*(29 - 29 + 28))\n-- Explain: if the days of now is bigger than the days of birth, then diff the two days\n-- else add the days of now and the distance from the date of birth to the end of the birth month \nselect @years,@months,@days -- 0, 11, 28 \n dob now years months days \n2012-02-29 2013-02-28 0 11 28 --Days will be 30 if calculated by the approach in accepted answer. \n2012-02-29 2016-02-28 3 11 28 --Days will be 31 if calculated by the approach in accepted answer, since the day of birth will be changed to 28 from 29 after dateadd by years. \n2012-02-29 2016-03-31 4 1 2\n2012-01-30 2016-02-29 4 0 30\n2012-01-30 2016-03-01 4 1 2 --Days will be 1 if calculated by the approach in accepted answer, since the day of birth will be changed to 30 from 29 after dateadd by years.\n2011-12-30 2016-02-29 4 1 30\n set @days = CASE WHEN day(@now) >= day(@dob) THEN day(@now) - day(@dob)\n ELSE @days_in_birth_month - day(@dob) + day(@now) END\n set @years = ( @now_i/100 - @dob_i/100)/100\nset @months =(12 + month(@now) - month(@dob))%12 \nselect @years,@months -- 1, 0\n" }, { "answer_id": 27064788, "author": "miguelbgouveia", "author_id": 2486661, "author_profile": "https://Stackoverflow.com/users/2486661", "pm_score": 0, "selected": false, "text": "CASE WHEN DateOfBirth< DATEADD(YEAR, (DATEPART(YEAR, GETDATE()) - DATEPART(YEAR, DateOfBirth))*-1, GETDATE()) \n THEN DATEPART(YEAR, GETDATE()) - DATEPART(YEAR, DateOfBirth)\n ELSE DATEPART(YEAR, GETDATE()) - DATEPART(YEAR, DateOfBirth) -1 END\n" }, { "answer_id": 35181398, "author": "Komengem", "author_id": 619010, "author_profile": "https://Stackoverflow.com/users/619010", "pm_score": 0, "selected": false, "text": "select case \n when cast(getdate() as date) = cast(dateadd(year, (datediff(year, '1996-09-09', getdate())), '1996-09-09') as date)\n then dateDiff(yyyy,'1996-09-09',dateadd(year, 0, getdate()))\n else dateDiff(yyyy,'1996-09-09',dateadd(year, -1, getdate()))\n end as MemberAge\ngo\n" }, { "answer_id": 35902737, "author": "Mark Brittingham", "author_id": 15592, "author_profile": "https://Stackoverflow.com/users/15592", "pm_score": 0, "selected": false, "text": "SELECT CAST(DATEDIFF(hour,Birthdate,CAST(GETDATE() as Date))/8766.0 as INT) AS Age FROM <YourTable>\n" }, { "answer_id": 36428043, "author": "Harry Steinmeyer", "author_id": 6157545, "author_profile": "https://Stackoverflow.com/users/6157545", "pm_score": -1, "selected": false, "text": "DECLARE @DoB AS DATE = '1968-10-24'\nDECLARE @cDate AS DATE = CAST('2000-10-23' AS DATE)\n\nSELECT \n--Get Year difference\nDATEDIFF(YEAR,@DoB,@cDate) -\n--Cases where year difference will be augmented\nCASE \n --If Date of Birth greater than date passed return 0\n WHEN YEAR(@DoB) - YEAR(@cDate) >= 0 THEN DATEDIFF(YEAR,@DoB,@cDate)\n\n --If date of birth month less than date passed subtract one year\n WHEN MONTH(@DoB) - MONTH(@cDate) > 0 THEN 1 \n\n --If date of birth day less than date passed subtract one year\n WHEN MONTH(@DoB) - MONTH(@cDate) = 0 AND DAY(@DoB) - DAY(@cDate) > 0 THEN 1 \n\n --All cases passed subtract zero\n ELSE 0\nEND\n" }, { "answer_id": 37345569, "author": "user6360847", "author_id": 6360847, "author_profile": "https://Stackoverflow.com/users/6360847", "pm_score": -1, "selected": false, "text": "declare @StartDate datetime = '2016-01-31'\ndeclare @EndDate datetime = '2016-02-01'\nSELECT @StartDate AS [StartDate]\n ,@EndDate AS [EndDate]\n ,DATEDIFF(Year,@StartDate,@EndDate) - CASE WHEN DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate), @StartDate) > @EndDate THEN 1 ELSE 0 END AS [Years]\n ,DATEDIFF(Month,(DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate) - CASE WHEN DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate), @StartDate) > @EndDate THEN 1 ELSE 0 END,@StartDate)),@EndDate) - CASE WHEN DATEADD(Month, DATEDIFF(Month,DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate) - CASE WHEN DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate), @StartDate) > @EndDate THEN 1 ELSE 0 END,@StartDate),@EndDate) , @StartDate) > @EndDate THEN 1 ELSE 0 END AS [Months]\n ,DATEDIFF(Day, DATEADD(Month,DATEDIFF(Month, (DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate) - CASE WHEN DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate), @StartDate) > @EndDate THEN 1 ELSE 0 END,@StartDate)),@EndDate) - CASE WHEN DATEADD(Month, DATEDIFF(Month,DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate) - CASE WHEN DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate), @StartDate) > @EndDate THEN 1 ELSE 0 END,@StartDate),@EndDate) , @StartDate) > @EndDate THEN 1 ELSE 0 END ,DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate) - CASE WHEN DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate), @StartDate) > @EndDate THEN 1 ELSE 0 END,@StartDate)) ,@EndDate) - CASE WHEN DATEADD(Day,DATEDIFF(Day, DATEADD(Month,DATEDIFF(Month, (DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate) - CASE WHEN DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate), @StartDate) > @EndDate THEN 1 ELSE 0 END,@StartDate)),@EndDate) - CASE WHEN DATEADD(Month, DATEDIFF(Month,DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate) - CASE WHEN DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate), @StartDate) > @EndDate THEN 1 ELSE 0 END,@StartDate),@EndDate) , @StartDate) > @EndDate THEN 1 ELSE 0 END ,DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate) - CASE WHEN DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate), @StartDate) > @EndDate THEN 1 ELSE 0 END,@StartDate)) ,@EndDate),DATEADD(Month,DATEDIFF(Month, (DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate) - CASE WHEN DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate), @StartDate) > @EndDate THEN 1 ELSE 0 END,@StartDate)),@EndDate) - CASE WHEN DATEADD(Month, DATEDIFF(Month,DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate) - CASE WHEN DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate), @StartDate) > @EndDate THEN 1 ELSE 0 END,@StartDate),@EndDate) , @StartDate) > @EndDate THEN 1 ELSE 0 END ,DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate) - CASE WHEN DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate), @StartDate) > @EndDate THEN 1 ELSE 0 END,@StartDate))) > @EndDate THEN 1 ELSE 0 END AS [Days]\n" }, { "answer_id": 37915012, "author": "Prince Jain", "author_id": 6487482, "author_profile": "https://Stackoverflow.com/users/6487482", "pm_score": -1, "selected": false, "text": "select DOB as Birthdate,\n YEAR(GETDATE()) as ThisYear, \n YEAR(getdate()) - EAR(date1) as Age \nfrom TableName\n" }, { "answer_id": 37915082, "author": "Prince Jain", "author_id": 6487482, "author_profile": "https://Stackoverflow.com/users/6487482", "pm_score": -1, "selected": false, "text": "SELECT DOB AS Birthdate ,\n YEAR(GETDATE()) AS ThisYear,\n YEAR(getdate()) - YEAR(DOB) AS Age\nFROM tableprincejain\n" }, { "answer_id": 51813114, "author": "Adal H. Vega", "author_id": 2097023, "author_profile": "https://Stackoverflow.com/users/2097023", "pm_score": 2, "selected": false, "text": "CREATE FUNCTION dbo.EdadAMD\n (\n @FECHA DATETIME\n )\n RETURNS NVARCHAR(10)\n AS\n BEGIN\n DECLARE\n @tmpdate DATETIME\n , @years INT\n , @months INT\n , @days INT\n , @EdadAMD NVARCHAR(10);\n\n SELECT @tmpdate = @FECHA;\n\n SELECT @years = DATEDIFF(yy, @tmpdate, GETDATE()) - CASE\n WHEN (MONTH(@FECHA) > MONTH(GETDATE()))\n OR (\n MONTH(@FECHA) = MONTH(GETDATE())\n AND DAY(@FECHA) > DAY(GETDATE())\n ) THEN\n 1\n ELSE\n 0\n END;\n SELECT @tmpdate = DATEADD(yy, @years, @tmpdate);\n SELECT @months = DATEDIFF(m, @tmpdate, GETDATE()) - CASE\n WHEN DAY(@FECHA) > DAY(GETDATE()) THEN\n 1\n ELSE\n 0\n END;\n SELECT @tmpdate = DATEADD(m, @months, @tmpdate);\n\n IF MONTH(@FECHA) = MONTH(GETDATE())\n AND DAY(@FECHA) > DAY(GETDATE())\n SELECT @days = \n DAY(EOMONTH(GETDATE(), -1)) - (DAY(@FECHA) - DAY(GETDATE()));\n ELSE\n SELECT @days = DATEDIFF(d, @tmpdate, GETDATE());\n\n SELECT @EdadAMD = CONCAT(@years, 'a', @months, 'm', @days, 'd');\n\n RETURN @EdadAMD;\n\nEND; \nGO\n" }, { "answer_id": 54178003, "author": "Sai Krishnan Harish", "author_id": 7906457, "author_profile": "https://Stackoverflow.com/users/7906457", "pm_score": 0, "selected": false, "text": " FirstName LastName DOB\n sai krishnan 1991-11-04\n Harish S A 1998-10-11\n Select datediff(MONTH,DOB,getdate())/12 as dates from [Organization].[Employee]\n firstname dates\nsai 27\nHarish 20\n" }, { "answer_id": 59627199, "author": "Sanket Doshi", "author_id": 5934456, "author_profile": "https://Stackoverflow.com/users/5934456", "pm_score": -1, "selected": false, "text": "declare @BirthDate datetime\ndeclare @TotalYear int\ndeclare @TotalMonths int\ndeclare @TotalDays int\ndeclare @TotalWeeks int\ndeclare @TotalHours int\ndeclare @TotalMinute int\ndeclare @TotalSecond int\ndeclare @CurrentDtTime datetime\nset @BirthDate='1998/01/05 05:04:00' -- Set Your date here\nset @TotalYear= FLOOR(DATEDIFF(DAY, @BirthDate, GETDATE()) / 365.25)\nset @TotalMonths= FLOOR(DATEDIFF(DAY,DATEADD(year, @TotalYear,@BirthDate),GetDate()) / 30.436875E)\nset @TotalDays= FLOOR(DATEDIFF(DAY, DATEADD(month, @TotalMonths,DATEADD(year, \n @TotalYear,@BirthDate)), GETDATE()))\nset @CurrentDtTime=CONVERT(datetime,CONVERT(varchar(50), DATEPART(year, \n GetDate()))+'/' +CONVERT(varchar(50), DATEPART(MONTH, GetDate()))\n +'/'+ CONVERT(varchar(50),DATEPART(DAY, GetDate()))+' '\n + CONVERT(varchar(50),DATEPART(HOUR, @BirthDate))+':'+ \n CONVERT(varchar(50),DATEPART(MINUTE, @BirthDate))+\n ':'+ CONVERT(varchar(50),DATEPART(Second, @BirthDate)))\nset @TotalHours = DATEDIFF(hour, @CurrentDtTime, GETDATE())\nif(@TotalHours < 0)\nbegin\n set @TotalHours = DATEDIFF(hour,DATEADD(Day,-1, @CurrentDtTime), GETDATE())\n set @TotalDays= @TotalDays -1 \n end\nset @TotalMinute= DATEPART(MINUTE, GETDATE())-DATEPART(MINUTE, @BirthDate)\n if(@TotalMinute < 0)\nset @TotalMinute = DATEPART(MINUTE, DATEADD(hour,-1,GETDATE()))+(60-DATEPART(MINUTE, \n @BirthDate))\n\nset @TotalSecond= DATEPART(Second, GETDATE())-DATEPART(Second, @BirthDate)\n\n Print 'Your age are'+ CHAR(13)\n + CONVERT(varchar(50), @TotalYear)+' Years, ' +\n CONVERT(varchar(50),@TotalMonths) +' Months, ' +\n CONVERT(varchar(50),@TotalDays)+' Days, ' +\n CONVERT(varchar(50),@TotalHours)+' Hours, ' +\n CONVERT(varchar(50),@TotalMinute)+' Minutes, ' + \n CONVERT(varchar(50),@TotalSecond)+' Seconds. ' +char(13)+\n 'Your are born at day of week was - ' + CONVERT(varchar(50),DATENAME(dw , \n @BirthDate ))\n +char(13)+char(13)+\n+'Your Birthdate to till date your '+ CHAR(13)\n+'Years - ' + CONVERT(varchar(50), FLOOR(DATEDIFF(DAY, @BirthDate, GETDATE()) / \n 365.25))\n+' , Months - ' + CONVERT(varchar(50),DATEDIFF(MM,@BirthDate,getdate())) \n+' , Weeks - ' + CONVERT(varchar(50),DATEDIFF(wk,@BirthDate,getdate()))\n+' , Days - ' + CONVERT(varchar(50),DATEDIFF(dd,@BirthDate,getdate()))+char(13)+\n+'Hours - ' + CONVERT(varchar(50),DATEDIFF(HH,@BirthDate,getdate()))\n+' , Minutes - ' + CONVERT(varchar(50),DATEDIFF(mi,@BirthDate,getdate()))\n+' , Seconds - ' + CONVERT(varchar(50),DATEDIFF(ss,@BirthDate,getdate()))\n Your age are\n22 Years, 0 Months, 2 Days, 11 Hours, 30 Minutes, 16 Seconds. \nYour are born at day of week was - Monday\n\nYour Birthdate to till date your \nYears - 22 , Months - 264 , Weeks - 1148 , Days - 8037\nHours - 192899 , Minutes - 11573970 , Seconds - 694438216\n" }, { "answer_id": 73035178, "author": "Mohan Kethireddigari", "author_id": 19533588, "author_profile": "https://Stackoverflow.com/users/19533588", "pm_score": 0, "selected": false, "text": "calculateAge dateOfBirth CREATE FUNCTION calculateAge(dateOfBirth datetime) RETURNS varchar(40)\nBEGIN\n set @currentdatetime = CURRENT_TIMESTAMP;\n set @years = TIMESTAMPDIFF(YEAR,dateOfBirth,@currentdatetime);\n set @months = TIMESTAMPDIFF(MONTH,dateOfBirth,@currentdatetime) - @years*12 ;\n set @dayOfBirth = EXTRACT(DAY FROM dateOfBirth);\n set @today = EXTRACT(DAY FROM @currentdatetime);\n set @days = 0;\n if (@today > @dayOfBirth) then\n set @days = @today - @dayOfBirth;\n else\n set @decreaseMonth = DATE_SUB(@currentdatetime, INTERVAL 1 MONTH);\n set @days = DATEDIFF(dateOfBirth, @decreaseMonth);\n end if;\n RETURN concat(concat( concat(@years , \"years\\n\") , concat(@months , \"months\\n\")), concat(@days , \"days\"));\nEND\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57599", "https://Stackoverflow.com", "https://Stackoverflow.com/users/845/" ]
57,600
<p>Should developers avoid using <a href="http://msdn.microsoft.com/en-us/library/923ahwt1.aspx" rel="nofollow noreferrer">continue</a> in C# or its equivalent in other languages to force the next iteration of a loop? Would arguments for or against overlap with arguments about <a href="https://stackoverflow.com/questions/46586/goto-still-considered-harmful">Goto</a>? </p>
[ { "answer_id": 57611, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 7, "selected": true, "text": "for (...)\n{\n if (!cond1)\n {\n if (!cond2)\n {\n ... highly indented lines ...\n }\n }\n}\n for (...)\n{\n if (cond1 || cond2)\n {\n continue;\n }\n\n ...\n}\n" }, { "answer_id": 57616, "author": "dF.", "author_id": 3002, "author_profile": "https://Stackoverflow.com/users/3002", "pm_score": 5, "selected": false, "text": "continue break" }, { "answer_id": 57657, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": -1, "selected": false, "text": "continue break continue continue break for (String str : strs) contLp: {\n ...\n break contLp;\n ...\n}\n break continue continue for (char c : cs) {\n final int i;\n if ('0' <= c && c <= '9') {\n i = c - '0';\n } else if ('a' <= c && c <= 'z') {\n i = c - 'a' + 10;\n } else {\n continue;\n }\n ... use i ...\n}\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57600", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2831/" ]
57,609
<p>I'm working on a WinCE 6.0 system with a touchscreen that stores its calibration data (x-y location, offset, etc.) in the system registry (HKLM\HARDWARE\TOUCH). Right now, I'm placing the cal values into registry keys that get put into the OS image at build time. That works fine for the monitor that I get the original cal values from, but when I load this image into another system with a different monitor, the touchscreen pointer location is (understandably) off, because the two monitors do not have the same cal values.</p> <p>My problem is that I don't know how to properly store values into the registry so that they persist after a power cycle. See, I can recalibrate the screen on the second system, but the new values only exist in volatile memory. I suggested to my boss that we could just tell our customer to leave the power on the unit at all times -- that didn't go over well.</p> <p>I need advice on how to save the new constants into the registry, so that we can calibrate the monitors once before shipping them out to our customer, and not have to make separate OS images for each unit we build.</p> <p>A C# method that is known to work in CE6.0 would be helpful. Thanks.</p> <p>-Odbasta</p>
[ { "answer_id": 59995, "author": "odbasta", "author_id": 2488, "author_profile": "https://Stackoverflow.com/users/2488", "pm_score": 3, "selected": false, "text": "[HKEY_LOCAL_MACHINE\\init\\BootVars]\n\"SystemHive\"=\"\\\\Hard Disk\\\\system.hv\"\n\"ProfileDir\"=\"\\\\Documents and Settings\"\n\"RegistryFlags\"=dword:1 ; Flush hive on every RegCloseKey call\n\"SystemHiveInitialSize\"=dword:19000 ; Initial size for hive-registry file \n\"Start DevMgr\"=dword:1\n ;HIVE BOOT SECTION\n[HKEY_LOCAL_MACHINE\\Drivers\\PCCARD\\PCMCIA\\TEMPLATE\\PCMCIA]\n \"Dll\"=\"pcmcia.dll\"\n \"NoConfig\"=dword:1\n \"IClass\"=multi_sz:\"{6BEAB08A-8914-42fd-B33F-61968B9AAB32}=PCMCIA Card Services\"\n \"Flags\"=dword:1000\n;END HIVE BOOT SECTION\n" }, { "answer_id": 66608, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": " /// <summary>\n /// store a key value in registry. if it don't exist it will be created. \n /// </summary>\n /// <param name=\"mainKey\">the main key of key path</param>\n /// <param name=\"subKey\">the path below the main key</param>\n /// <param name=\"keyName\">the key name</param>\n /// <param name=\"value\">the value to be stored</param>\n public static void SetRegistry(int mainKey, String subKey, String keyName, object value)\n {\n if (mainKey != CURRENT_USER && mainKey != LOCAL_MACHINE)\n {\n throw new ArgumentOutOfRangeException(\"mainKey\", \"\\'mainKey\\' argument can only be AppUtils.CURRENT_USER or AppUtils.LOCAL_MACHINE values\");\n }\n\n if (subKey == null)\n {\n throw new ArgumentNullException(\"subKey\", \"\\'subKey\\' argument cannot be null\");\n }\n\n if (keyName == null)\n {\n throw new ArgumentNullException(\"keyName\", \"\\'keyName\\' argument cannot be null\");\n }\n\n const Boolean WRITABLE = true;\n RegistryKey key = null;\n\n if (mainKey == CURRENT_USER)\n {\n key = Registry.CurrentUser.OpenSubKey(subKey, WRITABLE);\n\n if (key == null)\n {\n key = Registry.CurrentUser.CreateSubKey(subKey);\n }\n }\n else if (mainKey == LOCAL_MACHINE)\n {\n key = Registry.LocalMachine.OpenSubKey(subKey, WRITABLE);\n\n if (key == null)\n {\n key = Registry.LocalMachine.CreateSubKey(subKey);\n }\n }\n\n key.SetValue(keyName, value);\n\n }\n\n /// <summary>\n /// find a key value in registry. if it don't exist the default value will be returned.\n /// </summary>\n /// <param name=\"mainKey\">the main key of key path</param>\n /// <param name=\"subKey\">the path below the main key</param>\n /// <param name=\"keyName\">the key name</param>\n /// <param name=\"defaultValue\">the value to be stored</param>\n\n public static object GetRegistry(int mainKey, String subKey, String keyName, object defaultValue)\n {\n if (mainKey != CURRENT_USER && mainKey != LOCAL_MACHINE)\n {\n throw new ArgumentOutOfRangeException(\"mainKey\", \"\\'mainKey\\' argument can only be AppUtils.CURRENT_USER or AppUtils.LOCAL_MACHINE values\");\n }\n\n if (subKey == null)\n {\n throw new ArgumentNullException(\"subKey\", \"\\'subKey\\' argument cannot be null\");\n }\n\n if (keyName == null)\n {\n throw new ArgumentNullException(\"keyName\", \"\\'keyName\\' argument cannot be null\");\n }\n\n RegistryKey key = Registry.CurrentUser.OpenSubKey(subKey);\n\n if (mainKey == CURRENT_USER)\n {\n key = Registry.CurrentUser.OpenSubKey(subKey);\n }\n else if (mainKey == LOCAL_MACHINE)\n {\n key = Registry.LocalMachine.OpenSubKey(subKey);\n }\n\n object result = defaultValue;\n\n if (key != null)\n {\n result = key.GetValue(keyName, defaultValue);\n }\n\n return result;\n }\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57609", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2488/" ]
57,615
<p>I have a console app in which I want to give the user <em>x</em> seconds to respond to the prompt. If no input is made after a certain period of time, program logic should continue. We assume a timeout means empty response.</p> <p>What is the most straightforward way of approaching this?</p>
[ { "answer_id": 57655, "author": "Gulzar Nazim", "author_id": 4337, "author_profile": "https://Stackoverflow.com/users/4337", "pm_score": 5, "selected": false, "text": "class Sample \n{\n public static void Main() \n {\n ConsoleKeyInfo cki = new ConsoleKeyInfo();\n\n do {\n Console.WriteLine(\"\\nPress a key to display; press the 'x' key to quit.\");\n\n// Your code could perform some useful task in the following loop. However, \n// for the sake of this example we'll merely pause for a quarter second.\n\n while (Console.KeyAvailable == false)\n Thread.Sleep(250); // Loop until input is entered.\n cki = Console.ReadKey(true);\n Console.WriteLine(\"You pressed the '{0}' key.\", cki.Key);\n } while(cki.Key != ConsoleKey.X);\n }\n}\n" }, { "answer_id": 57711, "author": "Jesse C. Slicer", "author_id": 3312, "author_profile": "https://Stackoverflow.com/users/3312", "pm_score": 2, "selected": false, "text": "namespace TimedReadLine\n{\n public static class Console\n {\n private delegate string ReadLineInvoker();\n\n public static string ReadLine(int timeout)\n {\n return ReadLine(timeout, null);\n }\n\n public static string ReadLine(int timeout, string @default)\n {\n using (var process = new System.Diagnostics.Process\n {\n StartInfo =\n {\n FileName = \"ReadLine.exe\",\n RedirectStandardOutput = true,\n UseShellExecute = false\n }\n })\n {\n process.Start();\n\n var rli = new ReadLineInvoker(process.StandardOutput.ReadLine);\n var iar = rli.BeginInvoke(null, null);\n\n if (!iar.AsyncWaitHandle.WaitOne(new System.TimeSpan(0, 0, timeout)))\n {\n process.Kill();\n return @default;\n }\n\n return rli.EndInvoke(iar);\n }\n }\n }\n}\n namespace ReadLine\n{\n internal static class Program\n {\n private static void Main()\n {\n System.Console.WriteLine(System.Console.ReadLine());\n }\n }\n}\n" }, { "answer_id": 57775, "author": "Brannon", "author_id": 5745, "author_profile": "https://Stackoverflow.com/users/5745", "pm_score": 3, "selected": false, "text": "System.Console.WriteLine(\"Enter your first name [John]:\");\n\nstring firstName = Console.ReadLine(5, \"John\");\n\nSystem.Console.WriteLine(\"Enter your last name [Doe]:\");\n\nstring lastName = Console.ReadLine(5, \"Doe\");\n" }, { "answer_id": 231333, "author": "Ryan", "author_id": 29762, "author_profile": "https://Stackoverflow.com/users/29762", "pm_score": 2, "selected": false, "text": "// Get configurable wait time\nTimeSpan waitTime = TimeSpan.FromSeconds(15.0);\nint configWaitTimeSec;\nif (int.TryParse(ConfigManager.AppSetting[\"DefaultWaitTime\"], out configWaitTimeSec))\n waitTime = TimeSpan.FromSeconds(configWaitTimeSec);\n\nbool keyPressed = false;\nDateTime expireTime = DateTime.Now + waitTime;\n\n// Timer and key processor\nConsoleKeyInfo cki;\n// EDIT: adding a missing ! below\nwhile (!keyPressed && (DateTime.Now < expireTime))\n{\n if (Console.KeyAvailable)\n {\n cki = Console.ReadKey(true);\n // TODO: Process key\n keyPressed = true;\n }\n Thread.Sleep(10);\n}\n" }, { "answer_id": 885542, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": " using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Threading;\n\nnamespace PipedInfo\n{\n class Program\n {\n static void Main(string[] args)\n {\n StreamReader buffer = ReadPipedInfo();\n\n Console.WriteLine(buffer.ReadToEnd());\n }\n\n #region ReadPipedInfo\n public static StreamReader ReadPipedInfo()\n {\n //call with a default value of 5 milliseconds\n return ReadPipedInfo(5);\n }\n\n public static StreamReader ReadPipedInfo(int waitTimeInMilliseconds)\n {\n //allocate the class we're going to callback to\n ReadPipedInfoCallback callbackClass = new ReadPipedInfoCallback();\n\n //to indicate read complete or timeout\n AutoResetEvent readCompleteEvent = new AutoResetEvent(false);\n\n //open the StdIn so that we can read against it asynchronously\n Stream stdIn = Console.OpenStandardInput();\n\n //allocate a one-byte buffer, we're going to read off the stream one byte at a time\n byte[] singleByteBuffer = new byte[1];\n\n //allocate a list of an arbitary size to store the read bytes\n List<byte> byteStorage = new List<byte>(4096);\n\n IAsyncResult asyncRead = null;\n int readLength = 0; //the bytes we have successfully read\n\n do\n {\n //perform the read and wait until it finishes, unless it's already finished\n asyncRead = stdIn.BeginRead(singleByteBuffer, 0, singleByteBuffer.Length, new AsyncCallback(callbackClass.ReadCallback), readCompleteEvent);\n if (!asyncRead.CompletedSynchronously)\n readCompleteEvent.WaitOne(waitTimeInMilliseconds);\n\n //end the async call, one way or another\n\n //if our read succeeded we store the byte we read\n if (asyncRead.IsCompleted)\n {\n readLength = stdIn.EndRead(asyncRead);\n if (readLength > 0)\n byteStorage.Add(singleByteBuffer[0]);\n }\n\n } while (asyncRead.IsCompleted && readLength > 0);\n //we keep reading until we fail or read nothing\n\n //return results, if we read zero bytes the buffer will return empty\n return new StreamReader(new MemoryStream(byteStorage.ToArray(), 0, byteStorage.Count));\n }\n\n private class ReadPipedInfoCallback\n {\n public void ReadCallback(IAsyncResult asyncResult)\n {\n //pull the user-defined variable and strobe the event, the read finished successfully\n AutoResetEvent readCompleteEvent = asyncResult.AsyncState as AutoResetEvent;\n readCompleteEvent.Set();\n }\n }\n #endregion ReadPipedInfo\n }\n}\n" }, { "answer_id": 2041489, "author": "gp.", "author_id": 247843, "author_profile": "https://Stackoverflow.com/users/247843", "pm_score": 5, "selected": false, "text": "string ReadLine(int timeoutms)\n{\n ReadLineDelegate d = Console.ReadLine;\n IAsyncResult result = d.BeginInvoke(null, null);\n result.AsyncWaitHandle.WaitOne(timeoutms);//timeout e.g. 15000 for 15 secs\n if (result.IsCompleted)\n {\n string resultstr = d.EndInvoke(result);\n Console.WriteLine(\"Read: \" + resultstr);\n return resultstr;\n }\n else\n {\n Console.WriteLine(\"Timed out!\");\n throw new TimedoutException(\"Timed Out!\");\n }\n}\n\ndelegate string ReadLineDelegate();\n" }, { "answer_id": 2282672, "author": "mphair", "author_id": 191299, "author_profile": "https://Stackoverflow.com/users/191299", "pm_score": 1, "selected": false, "text": "Thread readKeyThread = new Thread(ReadKeyMethod);\nstatic ConsoleKeyInfo cki = null;\n\nvoid Main()\n{\n readKeyThread.Start();\n bool keyEntered = false;\n for(int ii = 0; ii < 10; ii++)\n {\n Thread.Sleep(1000);\n if(readKeyThread.ThreadState == ThreadState.Stopped)\n keyEntered = true;\n }\n if(keyEntered)\n { //do your stuff for a key entered\n }\n}\n\nvoid ReadKeyMethod()\n{\n cki = Console.ReadKey();\n}\n" }, { "answer_id": 2967469, "author": "Jamie Kitson", "author_id": 139560, "author_profile": "https://Stackoverflow.com/users/139560", "pm_score": 2, "selected": false, "text": " while (Console.KeyAvailable == false)\n {\n Thread.Sleep(250);\n i++;\n if (i > 3)\n throw new Exception(\"Timedout waiting for input.\");\n }\n input = Console.ReadLine();\n" }, { "answer_id": 2974065, "author": "Sasha", "author_id": 197897, "author_profile": "https://Stackoverflow.com/users/197897", "pm_score": 1, "selected": false, "text": "public static ManualResetEvent evtToWait = new ManualResetEvent(false);\n\nprivate static void ReadDataFromConsole( object state )\n{\n Console.WriteLine(\"Enter \\\"x\\\" to exit or wait for 5 seconds.\");\n\n while (Console.ReadKey().KeyChar != 'x')\n {\n Console.Out.WriteLine(\"\");\n Console.Out.WriteLine(\"Enter again!\");\n }\n\n evtToWait.Set();\n}\n\nstatic void Main(string[] args)\n{\n Thread status = new Thread(ReadDataFromConsole);\n status.Start();\n\n evtToWait = new ManualResetEvent(false);\n\n evtToWait.WaitOne(5000); // wait for evtToWait.Set() or timeOut\n\n status.Abort(); // exit anyway\n return;\n}\n" }, { "answer_id": 3591551, "author": "Glenn Slayden", "author_id": 147511, "author_profile": "https://Stackoverflow.com/users/147511", "pm_score": 3, "selected": false, "text": "// Wait for 'Enter' to be pressed or 5 seconds to elapse\nusing (Stream s = Console.OpenStandardInput())\n{\n ManualResetEvent stop_waiting = new ManualResetEvent(false);\n s.BeginRead(new Byte[1], 0, 1, ar => stop_waiting.Set(), null);\n\n // ...do anything else, or simply...\n\n stop_waiting.WaitOne(5000);\n // If desired, other threads could also set 'stop_waiting' \n // Disposing the stream cancels the async read operation. It can be\n // re-opened if needed.\n}\n" }, { "answer_id": 7318974, "author": "Contango", "author_id": 107409, "author_profile": "https://Stackoverflow.com/users/107409", "pm_score": 0, "selected": false, "text": "string readline = \"?\";\nThreadPool.QueueUserWorkItem(\n delegate\n {\n readline = Console.ReadLine();\n }\n);\ndo\n{\n Thread.Sleep(100);\n} while (readline == \"?\");\n" }, { "answer_id": 7664463, "author": "user980750", "author_id": 980750, "author_profile": "https://Stackoverflow.com/users/980750", "pm_score": 4, "selected": false, "text": "ConsoleKeyInfo k = new ConsoleKeyInfo();\nConsole.WriteLine(\"Press any key in the next 5 seconds.\");\nfor (int cnt = 5; cnt > 0; cnt--)\n {\n if (Console.KeyAvailable)\n {\n k = Console.ReadKey();\n break;\n }\n else\n {\n Console.WriteLine(cnt.ToString());\n System.Threading.Thread.Sleep(1000);\n }\n }\nConsole.WriteLine(\"The key pressed was \" + k.Key);\n" }, { "answer_id": 9016896, "author": "Contango", "author_id": 107409, "author_profile": "https://Stackoverflow.com/users/107409", "pm_score": 3, "selected": false, "text": " InputSimulator.SimulateKeyPress(VirtualKeyCode.RETURN);\n" }, { "answer_id": 16503766, "author": "John Atac", "author_id": 2374141, "author_profile": "https://Stackoverflow.com/users/2374141", "pm_score": 1, "selected": false, "text": "if (SpinWait.SpinUntil(() => Console.KeyAvailable, millisecondsTimeout))\n{\n ConsoleKeyInfo keyInfo = Console.ReadKey();\n\n // Handle keyInfo value here...\n}\n" }, { "answer_id": 17627972, "author": "mikemay", "author_id": 96167, "author_profile": "https://Stackoverflow.com/users/96167", "pm_score": 1, "selected": false, "text": "public static void Main() {\n bool readInProgress = false;\n System.IAsyncResult result = null;\n var stop_waiting = new System.Threading.ManualResetEvent(false);\n byte[] buffer = new byte[256];\n var s = System.Console.OpenStandardInput();\n while (true) {\n if (!readInProgress) {\n readInProgress = true;\n result = s.BeginRead(buffer, 0, buffer.Length\n , ar => stop_waiting.Set(), null);\n\n }\n bool signaled = true;\n if (!result.IsCompleted) {\n stop_waiting.Reset();\n signaled = stop_waiting.WaitOne(5000);\n }\n else {\n signaled = true;\n }\n if (signaled) {\n readInProgress = false;\n int numBytes = s.EndRead(result);\n string text = System.Text.Encoding.UTF8.GetString(buffer\n , 0, numBytes);\n System.Console.Out.Write(string.Format(\n \"Thank you for typing: {0}\", text));\n }\n else {\n System.Console.Out.WriteLine(\"oy, type something!\");\n }\n }\n" }, { "answer_id": 17946497, "author": "David Kirkland", "author_id": 41621, "author_profile": "https://Stackoverflow.com/users/41621", "pm_score": 0, "selected": false, "text": "ConsoleKeyInfo keyInfo;\nbool keyPressed = AsyncConsole.ReadKey(500, out keyInfo);\n// where 500 is the timeout\n public class AsyncConsole // not thread safe\n{\n private static readonly Lazy<AsyncConsole> Instance =\n new Lazy<AsyncConsole>();\n\n private bool _keyPressed;\n private ConsoleKeyInfo _keyInfo;\n\n private bool DoReadKey(\n int millisecondsTimeout,\n out ConsoleKeyInfo keyInfo)\n {\n _keyPressed = false;\n _keyInfo = new ConsoleKeyInfo();\n\n Thread readKeyThread = new Thread(ReadKeyThread);\n readKeyThread.IsBackground = false;\n readKeyThread.Start();\n\n Thread.Sleep(millisecondsTimeout);\n\n if (readKeyThread.IsAlive)\n {\n try\n {\n IntPtr stdin = GetStdHandle(StdHandle.StdIn);\n CloseHandle(stdin);\n readKeyThread.Join();\n }\n catch { }\n }\n\n readKeyThread = null;\n\n keyInfo = _keyInfo;\n return _keyPressed;\n }\n\n private void ReadKeyThread()\n {\n try\n {\n _keyInfo = Console.ReadKey();\n _keyPressed = true;\n }\n catch (InvalidOperationException) { }\n }\n\n public static bool ReadKey(\n int millisecondsTimeout,\n out ConsoleKeyInfo keyInfo)\n {\n return Instance.Value.DoReadKey(millisecondsTimeout, out keyInfo);\n }\n\n private enum StdHandle { StdIn = -10, StdOut = -11, StdErr = -12 };\n\n [DllImport(\"kernel32.dll\")]\n private static extern IntPtr GetStdHandle(StdHandle std);\n\n [DllImport(\"kernel32.dll\")]\n private static extern bool CloseHandle(IntPtr hdl);\n}\n" }, { "answer_id": 18342182, "author": "JSQuareD", "author_id": 1370541, "author_profile": "https://Stackoverflow.com/users/1370541", "pm_score": 8, "selected": true, "text": "class Reader {\n private static Thread inputThread;\n private static AutoResetEvent getInput, gotInput;\n private static string input;\n\n static Reader() {\n getInput = new AutoResetEvent(false);\n gotInput = new AutoResetEvent(false);\n inputThread = new Thread(reader);\n inputThread.IsBackground = true;\n inputThread.Start();\n }\n\n private static void reader() {\n while (true) {\n getInput.WaitOne();\n input = Console.ReadLine();\n gotInput.Set();\n }\n }\n\n // omit the parameter to read a line without a timeout\n public static string ReadLine(int timeOutMillisecs = Timeout.Infinite) {\n getInput.Set();\n bool success = gotInput.WaitOne(timeOutMillisecs);\n if (success)\n return input;\n else\n throw new TimeoutException(\"User did not provide input within the timelimit.\");\n }\n}\n try {\n Console.WriteLine(\"Please enter your name within the next 5 seconds.\");\n string name = Reader.ReadLine(5000);\n Console.WriteLine(\"Hello, {0}!\", name);\n} catch (TimeoutException) {\n Console.WriteLine(\"Sorry, you waited too long.\");\n}\n TryXX(out) public static bool TryReadLine(out string line, int timeOutMillisecs = Timeout.Infinite) {\n getInput.Set();\n bool success = gotInput.WaitOne(timeOutMillisecs);\n if (success)\n line = input;\n else\n line = null;\n return success;\n }\n Console.WriteLine(\"Please enter your name within the next 5 seconds.\");\nstring name;\nbool success = Reader.TryReadLine(out name, 5000);\nif (!success)\n Console.WriteLine(\"Sorry, you waited too long.\");\nelse\n Console.WriteLine(\"Hello, {0}!\", name);\n Reader Console.ReadLine Reader ReadLine ReadLine Reader Reader.ReadLine" }, { "answer_id": 19321114, "author": "Brian Gideon", "author_id": 158779, "author_profile": "https://Stackoverflow.com/users/158779", "pm_score": 0, "selected": false, "text": "Console.KeyAvailable public static class ConsoleEx\n{\n public static string ReadLine(TimeSpan timeout)\n {\n var cts = new CancellationTokenSource();\n return ReadLine(timeout, cts.Token);\n }\n\n public static string ReadLine(TimeSpan timeout, CancellationToken cancellation)\n {\n string line = \"\";\n DateTime latest = DateTime.UtcNow.Add(timeout);\n do\n {\n cancellation.ThrowIfCancellationRequested();\n if (Console.KeyAvailable)\n {\n ConsoleKeyInfo cki = Console.ReadKey();\n if (cki.Key == ConsoleKey.Enter)\n {\n return line;\n }\n else\n {\n line += cki.KeyChar;\n }\n }\n Thread.Sleep(1);\n }\n while (DateTime.UtcNow < latest);\n return null;\n }\n}\n ReadLine" }, { "answer_id": 20631955, "author": "Frank Rem", "author_id": 450467, "author_profile": "https://Stackoverflow.com/users/450467", "pm_score": 0, "selected": false, "text": "static void Main(string[] args)\n{\n Console.WriteLine(\"Hit q to continue or wait 10 seconds.\");\n\n Task task = Task.Factory.StartNew(() => loop());\n\n Console.WriteLine(\"Started waiting\");\n task.Wait(10000);\n Console.WriteLine(\"Stopped waiting\");\n}\n\nstatic void loop()\n{\n while (true)\n {\n if ('q' == Console.ReadKey().KeyChar) break;\n }\n}\n" }, { "answer_id": 26184541, "author": "Tono Nam", "author_id": 637142, "author_profile": "https://Stackoverflow.com/users/637142", "pm_score": 0, "selected": false, "text": " /// <summary>\n /// Reads Line from console with timeout. \n /// </summary>\n /// <exception cref=\"System.TimeoutException\">If user does not enter line in the specified time.</exception>\n /// <param name=\"timeout\">Time to wait in milliseconds. Negative value will wait forever.</param> \n /// <returns></returns> \n public static string ReadLine(int timeout = -1)\n {\n ConsoleKeyInfo cki = new ConsoleKeyInfo();\n StringBuilder sb = new StringBuilder();\n\n // if user does not want to spesify a timeout\n if (timeout < 0)\n return Console.ReadLine();\n\n int counter = 0;\n\n while (true)\n {\n while (Console.KeyAvailable == false)\n {\n counter++;\n Thread.Sleep(1);\n if (counter > timeout)\n throw new System.TimeoutException(\"Line was not entered in timeout specified\");\n }\n\n cki = Console.ReadKey(false);\n\n if (cki.Key == ConsoleKey.Enter)\n {\n Console.WriteLine();\n return sb.ToString();\n }\n else\n sb.Append(cki.KeyChar); \n } \n }\n" }, { "answer_id": 31089330, "author": "cprcrack", "author_id": 423171, "author_profile": "https://Stackoverflow.com/users/423171", "pm_score": 0, "selected": false, "text": "Console.KeyAvailable Console.WriteLine(\"Press any key during the next 2 seconds...\");\nThread.Sleep(2000);\nif (Console.KeyAvailable)\n{\n Console.WriteLine(\"Key pressed\");\n}\nelse\n{\n Console.WriteLine(\"You were too slow\");\n}\n" }, { "answer_id": 34749067, "author": "StevoInco", "author_id": 1812688, "author_profile": "https://Stackoverflow.com/users/1812688", "pm_score": 2, "selected": false, "text": " Private Function AskUser() As String\n Console.Write(\"Answer my question: \")\n Return Console.ReadLine()\n End Function\n Dim askTask As Task(Of String) = New TaskFactory().StartNew(Function() AskUser())\n askTask.Wait(TimeSpan.FromSeconds(30))\n If Not askTask.IsCompleted Then\n Console.WriteLine(\"User failed to respond.\")\n Else\n Console.WriteLine(String.Format(\"You responded, '{0}'.\", askTask.Result))\n End If\n" }, { "answer_id": 37907735, "author": "Shonn Lyga", "author_id": 1951795, "author_profile": "https://Stackoverflow.com/users/1951795", "pm_score": 0, "selected": false, "text": "public string ReadLine(int timeOutMillisecs)\n{\n var inputBuilder = new StringBuilder();\n\n var task = Task.Factory.StartNew(() =>\n {\n while (true)\n {\n var consoleKey = Console.ReadKey(true);\n if (consoleKey.Key == ConsoleKey.Enter)\n {\n return inputBuilder.ToString();\n }\n\n inputBuilder.Append(consoleKey.KeyChar);\n }\n });\n\n\n var success = task.Wait(timeOutMillisecs);\n if (!success)\n {\n throw new TimeoutException(\"User did not provide input within the timelimit.\");\n }\n\n return inputBuilder.ToString();\n}\n" }, { "answer_id": 39154725, "author": "JJS", "author_id": 26877, "author_profile": "https://Stackoverflow.com/users/26877", "pm_score": 0, "selected": false, "text": "Environment.IsInteractive Console.ReadKey(false) using System;\nusing System.Diagnostics;\n\ninternal class PressAnyKey\n{\n private static Thread inputThread;\n private static AutoResetEvent getInput;\n private static AutoResetEvent gotInput;\n private static CancellationTokenSource cancellationtoken;\n\n static PressAnyKey()\n {\n // Static Constructor called when WaitOne is called (technically Cancel too, but who cares)\n getInput = new AutoResetEvent(false);\n gotInput = new AutoResetEvent(false);\n inputThread = new Thread(ReaderThread);\n inputThread.IsBackground = true;\n inputThread.Name = \"PressAnyKey\";\n inputThread.Start();\n }\n\n private static void ReaderThread()\n {\n while (true)\n {\n // ReaderThread waits until PressAnyKey is called\n getInput.WaitOne();\n // Get here \n // Inner loop used when a caller uses PressAnyKey\n while (!Console.KeyAvailable && !cancellationtoken.IsCancellationRequested)\n {\n Thread.Sleep(50);\n }\n // Release the thread that called PressAnyKey\n gotInput.Set();\n }\n }\n\n /// <summary>\n /// Signals the thread that called WaitOne should be allowed to continue\n /// </summary>\n public static void Cancel()\n {\n // Trigger the alternate ending condition to the inner loop in ReaderThread\n if(cancellationtoken== null) throw new InvalidOperationException(\"Must call WaitOne before Cancelling\");\n cancellationtoken.Cancel();\n }\n\n /// <summary>\n /// Wait until a key is pressed or <see cref=\"Cancel\"/> is called by another thread\n /// </summary>\n public static void WaitOne()\n {\n if(cancellationtoken==null || cancellationtoken.IsCancellationRequested) throw new InvalidOperationException(\"Must cancel a pending wait\");\n cancellationtoken = new CancellationTokenSource();\n // Release the reader thread\n getInput.Set();\n // Calling thread will wait here indefiniately \n // until a key is pressed, or Cancel is called\n gotInput.WaitOne();\n } \n}\n" }, { "answer_id": 42940552, "author": "Igorium", "author_id": 6268624, "author_profile": "https://Stackoverflow.com/users/6268624", "pm_score": 1, "selected": false, "text": "var inputLine = ReadLine(5);\n\npublic static string ReadLine(uint timeoutSeconds, Func<uint, string> countDownMessage, uint samplingFrequencyMilliseconds)\n{\n if (timeoutSeconds == 0)\n return null;\n\n var timeoutMilliseconds = timeoutSeconds * 1000;\n\n if (samplingFrequencyMilliseconds > timeoutMilliseconds)\n throw new ArgumentException(\"Sampling frequency must not be greater then timeout!\", \"samplingFrequencyMilliseconds\");\n\n CancellationTokenSource cts = new CancellationTokenSource();\n\n Task.Factory\n .StartNew(() => SpinUserDialog(timeoutMilliseconds, countDownMessage, samplingFrequencyMilliseconds, cts.Token), cts.Token)\n .ContinueWith(t => {\n var hWnd = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle;\n PostMessage(hWnd, 0x100, 0x0D, 9);\n }, TaskContinuationOptions.NotOnCanceled);\n\n\n var inputLine = Console.ReadLine();\n cts.Cancel();\n\n return inputLine;\n}\n\n\nprivate static void SpinUserDialog(uint countDownMilliseconds, Func<uint, string> countDownMessage, uint samplingFrequencyMilliseconds,\n CancellationToken token)\n{\n while (countDownMilliseconds > 0)\n {\n token.ThrowIfCancellationRequested();\n\n Thread.Sleep((int)samplingFrequencyMilliseconds);\n\n countDownMilliseconds -= countDownMilliseconds > samplingFrequencyMilliseconds\n ? samplingFrequencyMilliseconds\n : countDownMilliseconds;\n }\n}\n\n\n[DllImport(\"User32.Dll\", EntryPoint = \"PostMessageA\")]\nprivate static extern bool PostMessage(IntPtr hWnd, uint msg, int wParam, int lParam);\n" }, { "answer_id": 43651242, "author": "georgiosd", "author_id": 165656, "author_profile": "https://Stackoverflow.com/users/165656", "pm_score": 0, "selected": false, "text": " static Task<string> ReadLineAsync(CancellationToken cancellation)\n {\n return Task.Run(() =>\n {\n while (!Console.KeyAvailable)\n {\n if (cancellation.IsCancellationRequested)\n return null;\n\n Thread.Sleep(100);\n }\n return Console.ReadLine();\n });\n }\n static void Main(string[] args)\n {\n AsyncContext.Run(async () =>\n {\n CancellationTokenSource cancelSource = new CancellationTokenSource();\n cancelSource.CancelAfter(1000);\n Console.WriteLine(await ReadLineAsync(cancelSource.Token) ?? \"null\");\n });\n }\n" }, { "answer_id": 44760134, "author": "kwl", "author_id": 2846791, "author_profile": "https://Stackoverflow.com/users/2846791", "pm_score": 3, "selected": false, "text": "Main() await Task.WaitAny() var task = Task.Factory.StartNew(Console.ReadLine);\nvar result = Task.WaitAny(new Task[] { task }, TimeSpan.FromSeconds(5)) == 0\n ? task.Result : string.Empty;\n Main() Task.WhenAny() var task = Task.Factory.StartNew(Console.ReadLine);\nvar completedTask = await Task.WhenAny(task, Task.Delay(TimeSpan.FromSeconds(5)));\nvar result = object.ReferenceEquals(task, completedTask) ? task.Result : string.Empty;\n" }, { "answer_id": 46226327, "author": "Nicholas Petersen", "author_id": 264031, "author_profile": "https://Stackoverflow.com/users/264031", "pm_score": 2, "selected": false, "text": " public static string ConsoleReadLineWithTimeout(TimeSpan timeout)\n {\n Task<string> task = Task.Factory.StartNew(Console.ReadLine);\n\n string result = Task.WaitAny(new Task[] { task }, timeout) == 0\n ? task.Result \n : string.Empty;\n return result;\n }\n static void Main()\n {\n Console.WriteLine(\"howdy\");\n string result = ConsoleReadLineWithTimeout(TimeSpan.FromSeconds(8.5));\n Console.WriteLine(\"bye\");\n }\n" }, { "answer_id": 55320462, "author": "Sergio Cabral", "author_id": 1396511, "author_profile": "https://Stackoverflow.com/users/1396511", "pm_score": 2, "selected": false, "text": "Stopwatch Console.ReadKey() Console.ReadLine() class Program\n{\n static void Main(string[] args)\n {\n Console.WriteLine(\"What is the answer? (5 secs.)\");\n try\n {\n var answer = ConsoleReadLine.ReadLine(5000);\n Console.WriteLine(\"Answer is: {0}\", answer);\n }\n catch\n {\n Console.WriteLine(\"No answer\");\n }\n Console.ReadKey();\n }\n}\n\nclass ConsoleReadLine\n{\n private static string inputLast;\n private static Thread inputThread = new Thread(inputThreadAction) { IsBackground = true };\n private static AutoResetEvent inputGet = new AutoResetEvent(false);\n private static AutoResetEvent inputGot = new AutoResetEvent(false);\n\n static ConsoleReadLine()\n {\n inputThread.Start();\n }\n\n private static void inputThreadAction()\n {\n while (true)\n {\n inputGet.WaitOne();\n inputLast = Console.ReadLine();\n inputGot.Set();\n }\n }\n\n // omit the parameter to read a line without a timeout\n public static string ReadLine(int timeout = Timeout.Infinite)\n {\n if (timeout == Timeout.Infinite)\n {\n return Console.ReadLine();\n }\n else\n {\n var stopwatch = new Stopwatch();\n stopwatch.Start();\n\n while (stopwatch.ElapsedMilliseconds < timeout && !Console.KeyAvailable) ;\n\n if (Console.KeyAvailable)\n {\n inputGet.Set();\n inputGot.WaitOne();\n return inputLast;\n }\n else\n {\n throw new TimeoutException(\"User did not provide input within the timelimit.\");\n }\n }\n }\n}\n" }, { "answer_id": 66821954, "author": "scott", "author_id": 1769757, "author_profile": "https://Stackoverflow.com/users/1769757", "pm_score": 1, "selected": false, "text": "using System;\nusing System.Runtime.InteropServices;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace ConsoleHelper\n{\n public static class ConsoleHelper\n {\n public static string ReadLine(TimeSpan timeout)\n {\n return ReadLine(Task.Delay(timeout));\n }\n\n public static string ReadLine(Task cancel_trigger)\n {\n var status = new Status();\n\n var cancel_task = Task.Run(async () =>\n {\n await cancel_trigger;\n\n status.Mutex.WaitOne();\n bool io_done = status.IODone;\n if (!io_done)\n status.CancellationStarted = true;\n status.Mutex.ReleaseMutex();\n\n while (!status.IODone)\n {\n var success = CancelStdIn(out int error_code);\n\n if (!success && error_code != 0x490) // 0x490 is what happens when you call cancel and there is not a pending I/O request\n throw new Exception($\"Canceling IO operation on StdIn failed with error {error_code} ({error_code:x})\");\n }\n });\n\n ReadLineWithStatus(out string input, out bool read_canceled);\n \n if (!read_canceled)\n {\n status.Mutex.WaitOne();\n bool must_wait = status.CancellationStarted;\n status.IODone = true;\n status.Mutex.ReleaseMutex();\n\n if (must_wait)\n cancel_task.Wait();\n\n return input;\n }\n else // read_canceled == true\n {\n status.Mutex.WaitOne();\n bool cancel_started = status.CancellationStarted;\n status.IODone = true;\n status.Mutex.ReleaseMutex();\n\n if (!cancel_started)\n throw new Exception(\"Received cancelation not triggered by this method.\");\n else\n cancel_task.Wait();\n\n return null;\n }\n }\n\n private const int STD_INPUT_HANDLE = -10;\n\n [DllImport(\"kernel32.dll\", SetLastError = true)]\n private static extern IntPtr GetStdHandle(int nStdHandle);\n\n [DllImport(\"kernel32.dll\", SetLastError = true)]\n private static extern bool CancelIoEx(IntPtr handle, IntPtr lpOverlapped);\n\n\n private static bool CancelStdIn(out int error_code)\n {\n var handle = GetStdHandle(STD_INPUT_HANDLE);\n bool success = CancelIoEx(handle, IntPtr.Zero);\n\n if (success)\n {\n error_code = 0;\n return true;\n }\n else\n {\n var rc = Marshal.GetLastWin32Error();\n error_code = rc;\n return false;\n }\n }\n\n private class Status\n {\n public Mutex Mutex = new Mutex(false);\n public volatile bool IODone;\n public volatile bool CancellationStarted;\n }\n\n private static void ReadLineWithStatus(out string result, out bool operation_canceled)\n {\n try\n {\n result = Console.ReadLine();\n operation_canceled = false;\n }\n catch (OperationCanceledException)\n {\n result = null;\n operation_canceled = true;\n }\n }\n }\n}\n\n CancelStdIn Console.ReadLine cancel_trigger CancelStdIn CancelStdIn" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/337/" ]
57,622
<p>I have a start of a webapp that I wrote without using the Object Oriented features of PHP.</p> <p>I don't really know if it is worth it to go back and rewrite the parts I have finished. Is object oriented PHP worth rewriting all or part of a decent working app?</p>
[ { "answer_id": 7279484, "author": "diyism", "author_id": 264181, "author_profile": "https://Stackoverflow.com/users/264181", "pm_score": 0, "selected": false, "text": "<?php\n$array1->array_flip(this);\n?>\n ->mode() <?php\n$array1->mode('class1', $success);\n?>\n ->construct() ->validate() ->mode('class1', $success); $array_man1 cls_normal_man cls_crazy_man <?php\n$array_man1->mode('cls_normal_man')->normal_method1()->mode('cls_crazy_man')->crazy_method1();\n?>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/673/" ]
57,625
<p>This one will take some explaining. What I've done is create a specific custom message queue in SQL Server 2005. I have a table with messages that contain timestamps for both acknowledgment and completion. The stored procedure that callers execute to obtain the next message in their queue also acknowledges the message. So far so good. Well, if the system is experiencing a massive amount of transactions (thousands per minute), isn't it possible for a message to be acknowledged by another execution of the stored procedure while another is prepared to so itself? Let me help by showing my SQL code in the stored proc:</p> <pre><code>--Grab the next message id declare @MessageId uniqueidentifier set @MessageId = (select top(1) ActionMessageId from UnacknowledgedDemands); --Acknowledge the message update ActionMessages set AcknowledgedTime = getdate() where ActionMessageId = @MessageId --Select the entire message ... ... </code></pre> <p>In the above code, couldn't another stored procedure running at the same time obtain the same id and attempt to acknowledge it at the same time? Could I (or should I) implement some sort of locking to prevent another stored proc from acknowledging messages that another stored proc is querying? </p> <p>Wow, did any of this even make sense? It's a bit difficult to put to words...</p>
[ { "answer_id": 57637, "author": "Blorgbeard", "author_id": 369, "author_profile": "https://Stackoverflow.com/users/369", "pm_score": -1, "selected": false, "text": "begin transaction\n\n--Grab the next message id\ndeclare @MessageId uniqueidentifier\nset @MessageId = (select top(1) ActionMessageId from UnacknowledgedDemands);\n\n--Acknowledge the message\nupdate ActionMessages\nset AcknowledgedTime = getdate()\nwhere ActionMessageId = @MessageId\n\ncommit transaction\n\n--Select the entire message\n...\n" }, { "answer_id": 57664, "author": "SQLMenace", "author_id": 740, "author_profile": "https://Stackoverflow.com/users/740", "pm_score": 4, "selected": true, "text": "--Grab the next message id\nbegin tran\ndeclare @MessageId uniqueidentifier\nselect top 1 @MessageId = ActionMessageId from UnacknowledgedDemands with(holdlock, updlock);\n\n--Acknowledge the message\nupdate ActionMessages\nset AcknowledgedTime = getdate()\nwhere ActionMessageId = @MessageId\n\n-- some error checking\ncommit tran\n\n--Select the entire message\n...\n...\n" }, { "answer_id": 126970, "author": "Constantin", "author_id": 20310, "author_profile": "https://Stackoverflow.com/users/20310", "pm_score": 1, "selected": false, "text": "declare @MessageId uniqueidentifier\nselect top 1 @MessageId = ActionMessageId from UnacknowledgedDemands\n\nupdate ActionMessages\n set AcknowledgedTime = getdate()\n where ActionMessageId = @MessageId and AcknowledgedTime is null\n\nif @@rowcount > 0\n /* acknoweldge succeeded */\nelse\n /* concurrent query acknowledged message before us,\n go back and try another one */\n" }, { "answer_id": 6746381, "author": "T.J. Crowder", "author_id": 157247, "author_profile": "https://Stackoverflow.com/users/157247", "pm_score": 2, "selected": false, "text": "OUTPUT -- Acknowledge and grab the next message\ndeclare @message table (\n -- ...your `ActionMessages` columns here...\n)\nupdate ActionMessages\nset AcknowledgedTime = getdate()\noutput INSERTED.* into @message\nwhere ActionMessageId in (select top(1) ActionMessageId from UnacknowledgedDemands)\n and AcknowledgedTime is null\n\n-- Use the data in @message, which will have zero or one rows assuming\n-- `ActionMessageId` uniquely identifies a row (strongly implied in your question)\n...\n...\n INSERTED OUTPUT UPDATE ActionMessages UnacknowledgedDemands and AcknowledgedTime is null ActionMessages where AcknowledgedTime is null top update UnacknowledgedDemands OUTPUT" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57625", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5469/" ]
57,652
<p>Scenario:</p> <ol> <li>The user has two monitors.</li> <li>Their browser is open on the secondary monitor.</li> <li>They click a link in the browser which calls window.open() with a specific top and left window offset.</li> <li>The popup window always opens on their primary monitor.</li> </ol> <p>Is there any way in JavaScript to get the popup window to open on the same monitor as the initial browser window (the opener)?</p>
[ { "answer_id": 57680, "author": "Jared", "author_id": 1980, "author_profile": "https://Stackoverflow.com/users/1980", "pm_score": -1, "selected": false, "text": "var x = 0;\nvar y = 0;\nvar myWin = window.open(''+self.location,'mywin','left='+x+',top='+y+',width=500,height=500,toolbar=1,resizable=0');\n" }, { "answer_id": 57684, "author": "rp.", "author_id": 2536, "author_profile": "https://Stackoverflow.com/users/2536", "pm_score": 5, "selected": false, "text": "function getMouseXY( e ) {\n if ( event.clientX ) { // Grab the x-y pos.s if browser is IE.\n CurrentLeft = event.clientX + document.body.scrollLeft;\n CurrentTop = event.clientY + document.body.scrollTop;\n }\n else { // Grab the x-y pos.s if browser isn't IE.\n CurrentLeft = e.pageX;\n CurrentTop = e.pageY;\n } \n if ( CurrentLeft < 0 ) { CurrentLeft = 0; };\n if ( CurrentTop < 0 ) { CurrentTop = 0; }; \n\n return true;\n}\n" }, { "answer_id": 4682246, "author": "Chase Seibert", "author_id": 7679, "author_profile": "https://Stackoverflow.com/users/7679", "pm_score": 4, "selected": false, "text": "function popup_params(width, height) {\n var a = typeof window.screenX != 'undefined' ? window.screenX : window.screenLeft;\n var i = typeof window.screenY != 'undefined' ? window.screenY : window.screenTop;\n var g = typeof window.outerWidth!='undefined' ? window.outerWidth : document.documentElement.clientWidth;\n var f = typeof window.outerHeight != 'undefined' ? window.outerHeight: (document.documentElement.clientHeight - 22);\n var h = (a < 0) ? window.screen.width + a : a;\n var left = parseInt(h + ((g - width) / 2), 10);\n var top = parseInt(i + ((f-height) / 2.5), 10);\n return 'width=' + width + ',height=' + height + ',left=' + left + ',top=' + top + ',scrollbars=1';\n} \n\nwindow.open(url, \"window name\", \"location=1,toolbar=0,\" + popup_params(modal_width, modal_height));\n" }, { "answer_id": 4786990, "author": "Ruan Mendes", "author_id": 227299, "author_profile": "https://Stackoverflow.com/users/227299", "pm_score": 3, "selected": false, "text": "// Pops a window relative to the current window position\nfunction popup(url, winName, xOffset, yOffset) {\n var x = (window.screenX || window.screenLeft || 0) + (xOffset || 0);\n var y = (window.screenY || window.screenTop || 0) + (yOffset || 0);\n return window.open(url, winName, 'top=' +y+ ',left=' +x))\n}\n popup('http://www.google.com', 'my-win');\n popup('http://www.google.com', 'my-win', 30, 30);\n /**\n * Finds the screen element for the monitor that the browser window is currently in.\n * This is required because window.screen is the screen that the page was originally\n * loaded in. This method works even after the window has been moved across monitors.\n * \n * @param {function} cb The function that will be called (asynchronously) once the screen \n * object has been discovered. It will be passed a single argument, the screen object.\n */\nfunction getScreenProps (cb) {\n if (!window.frames.testiframe) {\n var iframeEl = document.createElement('iframe');\n iframeEl.name = 'testiframe';\n iframeEl.src = \"about:blank\";\n iframeEl.id = 'iframe-test'\n document.body.appendChild(iframeEl);\n }\n\n // Callback when the iframe finishes reloading, it will have the \n // correct screen object\n document.getElementById('iframe-test').onload = function() {\n cb( window.frames.testiframe.screen );\n delete document.getElementById('iframe-test').onload;\n };\n // reload the iframe so that the screen object is reloaded\n window.frames.testiframe.location.reload();\n};\n function openAtTopLeftOfSameMonitor(url, winName) {\n getScreenProps(function(scr){\n window.open(url, winName, 'top=0,left=' + scr.left);\n })\n}\n" }, { "answer_id": 14290277, "author": "Suvi Vignarajah", "author_id": 1417588, "author_profile": "https://Stackoverflow.com/users/1417588", "pm_score": 0, "selected": false, "text": "window.screen availWidth availHeight availLeft availTop width height window.screen availLeft availLeft offsetLeft = availableLeft + ( (availableWidth - modalWidth) / 2 )\n" }, { "answer_id": 26549914, "author": "user11153", "author_id": 1795426, "author_profile": "https://Stackoverflow.com/users/1795426", "pm_score": 2, "selected": false, "text": "function popupOnCurrentScreenCenter(url, title, w, h) {\n var dualScreenLeft = typeof window.screenLeft !== \"undefined\" ? window.screenLeft : screen.left;\n var dualScreenTop = typeof window.screenTop !== \"undefined\" ? window.screenTop : screen.top;\n\n var width = window.innerWidth ? window.innerWidth :\n document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width;\n var height = window.innerHeight ? window.innerHeight :\n document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height;\n\n var left = ((width / 2) - (w / 2)) + dualScreenLeft;\n var top = ((height / 2) - (h / 2)) + dualScreenTop;\n var newWindow =\n window.open(url, title, 'scrollbars=yes, width=' + w + ', height=' + h + ', top=' + top + ', left=' + left);\n\n // Puts focus on the newWindow\n if (window.focus) {\n newWindow.focus();\n }\n}\n" }, { "answer_id": 52249716, "author": "hirano", "author_id": 5113353, "author_profile": "https://Stackoverflow.com/users/5113353", "pm_score": 0, "selected": false, "text": "popupOnCurrentScreenCenter(url: string, title: string, w: number, h: number): Window|null {\n var dualScreenLeft = typeof window.screenLeft !== \"undefined\" ? window.screenLeft : (<any>screen).left;\n var dualScreenTop = typeof window.screenTop !== \"undefined\" ? window.screenTop : (<any>screen).top;\n\n var width = window.innerWidth ? window.innerWidth :\n document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width;\n var height = window.innerHeight ? window.innerHeight :\n document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height;\n\n var left = ((width / 2) - (w / 2)) + dualScreenLeft;\n var top = ((height / 2) - (h / 2)) + dualScreenTop;\n var newWindow =\n window.open(url, title, 'scrollbars=yes, width=' + w + ', height=' + h + ', top=' + top + ', left=' + left);\n\n // Puts focus on the newWindow\n if (window.focus && newWindow) {\n newWindow.focus();\n }\n return newWindow;\n}\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57652", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1436/" ]
57,665
<p>Is there an easy way to return data to web service clients in JSON using Rails?</p>
[ { "answer_id": 57761, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 2, "selected": false, "text": "#to_json to_json" }, { "answer_id": 245486, "author": "JasonOng", "author_id": 6048, "author_profile": "https://Stackoverflow.com/users/6048", "pm_score": 5, "selected": true, "text": "class Contact < ActiveRecord::Base\n ...\nend\n map.resources :contacts\n class ContactsController < ApplicationController\n ...\n def show\n @contact = Contact.find(params[:id]\n\n respond_to do |format|\n format.html \n format.xml {render :xml => @contact}\n format.js {render :json => @contact.json}\n end\n end\n ...\nend\n /contacts/1 # Responds with regular html page\n\n/contacts/1.xml # Responds with xml output of Contact.find(1) and its attributes\n\n/contacts/1.js # Responds with json output of Contact.find(1) and its attributes\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5988/" ]
57,679
<p>I'm trying to determine, based on the result of this call, if it was successful. The <code>successFunction</code> doesn't get called, so I'm assuming it was not. How do I know what went wrong?</p> <pre><code>xmlRequest = $.post("/url/file/", { 'id' : object.id }, successFunction, 'json'); </code></pre> <p>Do I use the xmlRequest object?</p>
[ { "answer_id": 57997, "author": "defrex", "author_id": 6007, "author_profile": "https://Stackoverflow.com/users/6007", "pm_score": 4, "selected": true, "text": "$.ajax({\n url:\"/url/file/\",\n dataType:\"json\"\n data:{ 'id' : object.id }\n error:function(request){alert(request.statusText)}\n success:successFunction\n})\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57679", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5261/" ]
57,689
<p>Is there an easy way to return data to web service clients in JSON using java? I'm fine with servlets, spring, etc.</p>
[ { "answer_id": 57737, "author": "Stu Thompson", "author_id": 2961, "author_profile": "https://Stackoverflow.com/users/2961", "pm_score": 2, "selected": false, "text": "private String getJsonDocumenent(Object myObj) (\n String result = \"oops\";\n try {\n JSONArray jsonArray = JSONArray.fromObject(myObj);\n\n result = jsonArray.toString(2); //indent = 2\n\n } catch (net.sf.json.JSONException je) {\n\n throw je;\n }\n return result;\n}\n" }, { "answer_id": 58047, "author": "Geekygecko", "author_id": 6009, "author_profile": "https://Stackoverflow.com/users/6009", "pm_score": 3, "selected": false, "text": "public String searchCars() {\n List<Car> cars = carsService.getCars(manufacturerId);\n return new JSONSerializer().serialize(cars);\n}\n new JSONSerializer().deepSerialize(user); \n new JSONSerializer().transform(\n new DateTransformer(\"dd/MM/yyyy\"),\"startDate\",\"endDate\"\n).serialize(contract);\n" }, { "answer_id": 73959, "author": "blahspam", "author_id": 8290, "author_profile": "https://Stackoverflow.com/users/8290", "pm_score": 4, "selected": false, "text": "@XmlType(name = \"\", propOrder = { \"id\", \"text\" })\n@XmlRootElement(name = \"blah\")\npublic class Blah implements Serializable {\n private Integer id;\n private String text;\n\n public Blah(Integer id, String text) {\n this.id = id;\n this.text = text;\n } \n\n @XmlElement\n public Integer getId() { return id; }\n public void setId(Integer id) { this.id = id; }\n\n @XmlElement\n public String getText() { return text; }\n public void setText(String value) { this.text = value; }\n}\n @Path(\"/blah\")\npublic class BlahResource {\n private Set<Blah> blahs = new HashSet<Blah>();\n\n @Context\n private UriInfo context;\n\n public BlahResource() {\n blahs.add(new Blah(1, \"blah the first\"));\n blahs.add(new Blah(2, \"blah the second\"));\n }\n\n @GET\n @Path(\"/{id}\")\n @ProduceMime({\"application/json\", \"application/xml\"})\n public Blah getBlah(@PathParam(\"id\") Integer id) {\n for (Blah blah : blahs) {\n if (blah.getId().equals(id)) {\n return blah;\n }\n }\n throw new NotFoundException(\"not found\");\n }\n}\n <servlet>\n <servlet-name>jersey</servlet-name>\n <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>\n <load-on-startup>1</load-on-startup>\n</servlet>\n\n<servlet-mapping>\n <servlet-name>jersey</servlet-name>\n <url-pattern>/*</url-pattern>\n</servlet-mapping>\n accept application/json" }, { "answer_id": 2365261, "author": "jon", "author_id": 226846, "author_profile": "https://Stackoverflow.com/users/226846", "pm_score": 2, "selected": false, "text": "/*\n* we're looking for results in the form\n* {\"id\":123,\"name\":thename},{\"id\":456,\"name\":theOtherName},...\n*\n* TypeToken is Gson--allows us to tell Gson the data we're dealing with\n* for easier serialization.\n*/\nType mapType = new TypeToken<List<Map<String, String>>>(){}.getType();\n\nList<Map<String, String>> resultList = new LinkedList<Map<String, String>>();\n\nfor (Map.Entry<String, String> pair : sortedMap.entrySet()) {\n Map<String, String> idNameMap = new HashMap<String, String>();\n idNameMap.put(\"id\", pair.getKey());\n idNameMap.put(\"name\", pair.getValue());\n resultList.add(idNameMap);\n}\n\nreturn (new Gson()).toJson(resultList, mapType);\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57689", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5988/" ]
57,701
<p>It's <a href="http://www.codeproject.com/KB/cs/csharpcasts.aspx" rel="noreferrer">shown</a> that 'as' casting is much faster than prefix casting, but what about 'is' reflection? How bad is it? As you can imagine, searching for 'is' on Google isn't terribly effective.</p>
[ { "answer_id": 57713, "author": "swilliams", "author_id": 736, "author_profile": "https://Stackoverflow.com/users/736", "pm_score": 3, "selected": false, "text": "if (obj is Foo) {\n Foo f = (Foo)obj;\n f.doSomething();\n}\n Foo f = obj as Foo;\nif (f != null) {\n f.doSomething();\n}\n" }, { "answer_id": 57828, "author": "Daniel Fortunov", "author_id": 5975, "author_profile": "https://Stackoverflow.com/users/5975", "pm_score": 5, "selected": true, "text": "Foo foo = (Foo)bar as Foo foo = bar as Foo is bool is = bar is Foo bar Foo as bar null is bar boolean is as bar Foo is bar Foo as is is as is" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57701", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3279/" ]
57,708
<p>I'm doing some web scraping and sites frequently use HTML entities to represent non ascii characters. Does Python have a utility that takes a string with HTML entities and returns a unicode type?</p> <p>For example:</p> <p>I get back:</p> <pre><code>&amp;#x01ce; </code></pre> <p>which represents an "ǎ" with a tone mark. In binary, this is represented as the 16 bit 01ce. I want to convert the html entity into the value <code>u'\u01ce'</code></p>
[ { "answer_id": 57745, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 3, "selected": false, "text": "BeautifulSoup import copy, re\nfrom BeautifulSoup import BeautifulSoup\n\nhexentityMassage = copy.copy(BeautifulSoup.MARKUP_MASSAGE)\n# replace hexadecimal character reference by decimal one\nhexentityMassage += [(re.compile('&#x([^;]+);'), \n lambda m: '&#%d;' % int(m.group(1), 16))]\n\ndef convert(html):\n return BeautifulSoup(html,\n convertEntities=BeautifulSoup.HTML_ENTITIES,\n markupMassage=hexentityMassage).contents[0].string\n\nhtml = '<html>&#x01ce;&#462;</html>'\nprint repr(convert(html))\n# u'\\u01ce\\u01ce'\n unescape() htmlentitydefs unichr()" }, { "answer_id": 57877, "author": "chryss", "author_id": 5169, "author_profile": "https://Stackoverflow.com/users/5169", "pm_score": 4, "selected": false, "text": "unichr >>> entity = '&#x01ce'\n>>> unichr(int(entity[3:],16))\nu'\\u01ce'\n" }, { "answer_id": 58125, "author": "dF.", "author_id": 3002, "author_profile": "https://Stackoverflow.com/users/3002", "pm_score": 6, "selected": false, "text": "import re, htmlentitydefs\n\n##\n# Removes HTML or XML character references and entities from a text string.\n#\n# @param text The HTML (or XML) source text.\n# @return The plain text, as a Unicode string, if necessary.\n\ndef unescape(text):\n def fixup(m):\n text = m.group(0)\n if text[:2] == \"&#\":\n # character reference\n try:\n if text[:3] == \"&#x\":\n return unichr(int(text[3:-1], 16))\n else:\n return unichr(int(text[2:-1]))\n except ValueError:\n pass\n else:\n # named entity\n try:\n text = unichr(htmlentitydefs.name2codepoint[text[1:-1]])\n except KeyError:\n pass\n return text # leave as is\n return re.sub(\"&#?\\w+;\", fixup, text)\n" }, { "answer_id": 573629, "author": "karlcow", "author_id": 62262, "author_profile": "https://Stackoverflow.com/users/62262", "pm_score": 3, "selected": false, "text": "def unescape(text):\n \"\"\"Removes HTML or XML character references \n and entities from a text string.\n @param text The HTML (or XML) source text.\n @return The plain text, as a Unicode string, if necessary.\n from Fredrik Lundh\n 2008-01-03: input only unicode characters string.\n http://effbot.org/zone/re-sub.htm#unescape-html\n \"\"\"\n def fixup(m):\n text = m.group(0)\n if text[:2] == \"&#\":\n # character reference\n try:\n if text[:3] == \"&#x\":\n return unichr(int(text[3:-1], 16))\n else:\n return unichr(int(text[2:-1]))\n except ValueError:\n print \"Value Error\"\n pass\n else:\n # named entity\n # reescape the reserved characters.\n try:\n if text[1:-1] == \"amp\":\n text = \"&amp;amp;\"\n elif text[1:-1] == \"gt\":\n text = \"&amp;gt;\"\n elif text[1:-1] == \"lt\":\n text = \"&amp;lt;\"\n else:\n print text[1:-1]\n text = unichr(htmlentitydefs.name2codepoint[text[1:-1]])\n except KeyError:\n print \"keyerror\"\n pass\n return text # leave as is\n return re.sub(\"&#?\\w+;\", fixup, text)\n" }, { "answer_id": 4438857, "author": "rogerhu", "author_id": 541895, "author_profile": "https://Stackoverflow.com/users/541895", "pm_score": 2, "selected": false, "text": "import re\nfrom BeautifulSoup import BeautifulSoup\n\nhtml_string='<a href=\"/cgi-bin/article.cgi?f=/c/a/2010/12/13/BA3V1GQ1CI.DTL\"title=\"\">&#x27;Blackout in a can; on some shelves despite ban</a>'\n\nhexentityMassage = [(re.compile('&#x([^;]+);'), \nlambda m: '&#%d;' % int(m.group(1), 16))]\n\nsoup = BeautifulSoup(html_string, \nconvertEntities=BeautifulSoup.HTML_ENTITIES, \nmarkupMassage=hexentityMassage)\n" }, { "answer_id": 9216990, "author": "pragmar", "author_id": 1196188, "author_profile": "https://Stackoverflow.com/users/1196188", "pm_score": 4, "selected": false, "text": ">>> import lxml.html\n>>> lxml.html.fromstring('&#x01ce').text\nu'\\u01ce'\n" }, { "answer_id": 12614706, "author": "Vladislav", "author_id": 1164730, "author_profile": "https://Stackoverflow.com/users/1164730", "pm_score": 7, "selected": true, "text": "import HTMLParser\nh = HTMLParser.HTMLParser()\nh.unescape('&copy; 2010') # u'\\xa9 2010'\nh.unescape('&#169; 2010') # u'\\xa9 2010'\n import html\nhtml.unescape('&copy; 2010') # u'\\xa9 2010'\nhtml.unescape('&#169; 2010') # u'\\xa9 2010'\n" }, { "answer_id": 27424874, "author": "Markus Amalthea Magnuson", "author_id": 11403, "author_profile": "https://Stackoverflow.com/users/11403", "pm_score": 4, "selected": false, "text": "html.unescape import html\n\ns = html.unescape(s)\n" }, { "answer_id": 33486253, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "from xml.sax.saxutils import unescape\n\nescaped_text = unescape(text_to_escape)\n" }, { "answer_id": 34463462, "author": "Victor", "author_id": 2086547, "author_profile": "https://Stackoverflow.com/users/2086547", "pm_score": 0, "selected": false, "text": "import re\nimport html.entities\n\ndef unescape(text):\n \"\"\"\n Removes HTML or XML character references and entities from a text string.\n\n :param text: The HTML (or XML) source text.\n :return: The plain text, as a Unicode string, if necessary.\n \"\"\"\n def fixup(m):\n text = m.group(0)\n if text[:2] == \"&#\":\n # character reference\n try:\n if text[:3] == \"&#x\":\n return chr(int(text[3:-1], 16))\n else:\n return chr(int(text[2:-1]))\n except ValueError:\n pass\n else:\n # named entity\n try:\n text = chr(html.entities.name2codepoint[text[1:-1]])\n except KeyError:\n pass\n return text # leave as is\n return re.sub(\"&#?\\w+;\", fixup, text)\n htmlentitydefs html.entities unichr chr" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57708", "https://Stackoverflow.com", "https://Stackoverflow.com/users/680/" ]
57,718
<p>Has anyone actually shipped an Entity Framework project that does O/R mapping into conceptual classes that are quite different from the tables in the datastore?</p> <p>I mean collapse junction (M:M) tables into other entities to form <strong>Conceptual</strong> classes that exist in the business domain but are organized as <strong>multiple tables</strong> in the datastore. All the examples that I see on the MSDN have little use of inheritance, collapsing junction tables into other entities, or collapsing lookup tables into entities.</p> <p>I'd love to hear of or see examples of the below which support all the CRUD operations you would typically expect to do on a business object.:</p> <ol> <li><p>Vehicle table and a Color table. A Color can appear in many Vehicles (1:M). They form the conceptual class UsedCar which has the property Color. </p></li> <li><p>Doctor, DoctorPatients, and Patients tables (form a many to many). Doctors have many Patients, Patients can have many Doctors (M:M). Map out the two conceptual classes Doctor (which has a Patients collection) and Patients (which has a Doctors collection).</p></li> </ol> <p><strong>Anyone seen/done this with CSDL AND SSDL in the Entity Framework? The CSDL is no good if it doesn't actaully map to anything!</strong></p>
[ { "answer_id": 58181, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 2, "selected": false, "text": "<edmx:ConceptualModels>\n <Schema xmlns=\"http://schemas.microsoft.com/ado/2006/04/edm\" Namespace=\"Model1\" Alias=\"Self\">\n <EntityContainer Name=\"Model1Container\" >\n <EntitySet Name=\"ColorSet\" EntityType=\"Model1.Color\" />\n <EntitySet Name=\"DoctorSet\" EntityType=\"Model1.Doctor\" />\n <EntitySet Name=\"PatientSet\" EntityType=\"Model1.Patient\" />\n <EntitySet Name=\"UsedCarSet\" EntityType=\"Model1.UsedCar\" />\n <AssociationSet Name=\"Vehicle_Color\" Association=\"Model1.Vehicle_Color\">\n <End Role=\"Colors\" EntitySet=\"ColorSet\" />\n <End Role=\"Vehicles\" EntitySet=\"UsedCarSet\" /></AssociationSet>\n <AssociationSet Name=\"DoctorPatient\" Association=\"Model1.DoctorPatient\">\n <End Role=\"Doctor\" EntitySet=\"DoctorSet\" />\n <End Role=\"Patient\" EntitySet=\"PatientSet\" /></AssociationSet>\n </EntityContainer>\n <EntityType Name=\"Color\">\n <Key>\n <PropertyRef Name=\"ColorID\" /></Key>\n <Property Name=\"ColorID\" Type=\"Int32\" Nullable=\"false\" />\n <NavigationProperty Name=\"Vehicles\" Relationship=\"Model1.Vehicle_Color\" FromRole=\"Colors\" ToRole=\"Vehicles\" /></EntityType>\n <EntityType Name=\"Doctor\">\n <Key>\n <PropertyRef Name=\"DoctorID\" /></Key>\n <Property Name=\"DoctorID\" Type=\"Int32\" Nullable=\"false\" />\n <NavigationProperty Name=\"Patients\" Relationship=\"Model1.DoctorPatient\" FromRole=\"Doctor\" ToRole=\"Patient\" /></EntityType>\n <EntityType Name=\"Patient\">\n <Key>\n <PropertyRef Name=\"PatientID\" /></Key>\n <Property Name=\"PatientID\" Type=\"Int32\" Nullable=\"false\" />\n <NavigationProperty Name=\"Doctors\" Relationship=\"Model1.DoctorPatient\" FromRole=\"Patient\" ToRole=\"Doctor\" />\n </EntityType>\n <EntityType Name=\"UsedCar\">\n <Key>\n <PropertyRef Name=\"VehicleID\" /></Key>\n <Property Name=\"VehicleID\" Type=\"Int32\" Nullable=\"false\" />\n <NavigationProperty Name=\"Color\" Relationship=\"Model1.Vehicle_Color\" FromRole=\"Vehicles\" ToRole=\"Colors\" /></EntityType>\n <Association Name=\"Vehicle_Color\">\n <End Type=\"Model1.Color\" Role=\"Colors\" Multiplicity=\"1\" />\n <End Type=\"Model1.UsedCar\" Role=\"Vehicles\" Multiplicity=\"*\" /></Association>\n <Association Name=\"DoctorPatient\">\n <End Type=\"Model1.Doctor\" Role=\"Doctor\" Multiplicity=\"*\" />\n <End Type=\"Model1.Patient\" Role=\"Patient\" Multiplicity=\"*\" /></Association>\n </Schema>\n</edmx:ConceptualModels>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57718", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5642/" ]
57,725
<p>Let's say I want a way to display just the the center 50x50px of an image that's 250x250px in HTML. How can I do that. Also, is there a way to do this for css:url() references? <p> I'm aware of <em>clip</em> in CSS, but that seems to only work when used with absolute positioning.</p>
[ { "answer_id": 4639862, "author": "David Thomas", "author_id": 82548, "author_profile": "https://Stackoverflow.com/users/82548", "pm_score": 8, "selected": false, "text": "clip position: absolute; .container {\n position: relative;\n}\n#clip {\n position: absolute;\n clip: rect(0, 100px, 200px, 0);\n /* clip: shape(top, right, bottom, left); NB 'rect' is the only available option */\n} <div class=\"container\">\n <img src=\"http://lorempixel.com/200/200/nightlife/3\" />\n</div>\n<div class=\"container\">\n <img id=\"clip\" src=\"http://lorempixel.com/200/200/nightlife/3\" />\n</div> clip-path clip clip-path clip inset (top right bottom left) circle circle(diameter at x-coordinate y-coordinate) ellipse ellipse(x-axis-length y-axis-length at x-coordinate y-coordinate) polygon x y polygon(x-coordinate1 y-coordinate1, x-coordinate2 y-coordinate2, x-coordinate3 y-coordinate3, [etc...]) url div.container {\n display: inline-block;\n}\n#rectangular {\n -webkit-clip-path: inset(30px 10px 30px 10px);\n clip-path: inset(30px 10px 30px 10px);\n}\n#circle {\n -webkit-clip-path: circle(75px at 50% 50%);\n clip-path: circle(75px at 50% 50%)\n}\n#ellipse {\n -webkit-clip-path: ellipse(75px 50px at 50% 50%);\n clip-path: ellipse(75px 50px at 50% 50%);\n}\n#polygon {\n -webkit-clip-path: polygon(50% 0, 100% 38%, 81% 100%, 19% 100%, 0 38%);\n clip-path: polygon(50% 0, 100% 38%, 81% 100%, 19% 100%, 0 38%);\n} <div class=\"container\">\n <img id=\"control\" src=\"http://lorempixel.com/150/150/people/1\" />\n</div>\n<div class=\"container\">\n <img id=\"rectangular\" src=\"http://lorempixel.com/150/150/people/1\" />\n</div>\n<div class=\"container\">\n <img id=\"circle\" src=\"http://lorempixel.com/150/150/people/1\" />\n</div>\n<div class=\"container\">\n <img id=\"ellipse\" src=\"http://lorempixel.com/150/150/people/1\" />\n</div>\n<div class=\"container\">\n <img id=\"polygon\" src=\"http://lorempixel.com/150/150/people/1\" />\n</div> clip clip-path clip-path" }, { "answer_id": 23220895, "author": "Vincent", "author_id": 859631, "author_profile": "https://Stackoverflow.com/users/859631", "pm_score": 5, "selected": false, "text": "<header class=\"siteHeader\">\n <img src=\"img\" class=\"siteLogo\" />\n</header>\n .siteHeader{\n width: 50px;\n height: 50px;\n overflow: hidden;\n}\n\n.siteHeader .siteLogo{\n margin: -100px;\n}\n" }, { "answer_id": 63898815, "author": "Codemaker", "author_id": 7103882, "author_profile": "https://Stackoverflow.com/users/7103882", "pm_score": 2, "selected": false, "text": "div div { \n background-image: url('image url');\n background-position: 0 -250px; \n}\n" }, { "answer_id": 72934311, "author": "amateur", "author_id": 19524105, "author_profile": "https://Stackoverflow.com/users/19524105", "pm_score": 0, "selected": false, "text": "div{\nwidth: 50px;\nheight: 50px;\nbackground: no-repeat -100px -100px/500% url(\"https://qce.quantum.ieee.org/2022/wp-content/uploads/sites/6/2022/02/[email protected]\")\n }; <html>\n<head>\n</head>\n<body>\n<div></div>\n</body>\n</html>" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57725", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4489/" ]
57,751
<p>I want to find any text in a file that matches a regexp of the form <em>t</em><code>[A-Z]</code><em>u</em> (i.e., a match <em>t</em> followed by a capital letter and another match <em>u</em>, and transform the matched text so that the capital letter is lowercase. For example, for the regexp <code>x[A-Z]y</code></p> <pre><code>xAy </code></pre> <p>becomes</p> <pre><code>xay </code></pre> <p>and</p> <pre><code>xZy </code></pre> <p>becomes</p> <pre><code>xzy </code></pre> <p>Emacs' <code>query-replace</code> function allows back-references, but AFAIK not the transformation of the matched text. Is there a built-in function that does this? Does anybody have a short Elisp function I could use?</p> <p><strong>UPDATE</strong></p> <p>@Marcel Levy has it: <code>\,</code> in a replacement expression introduces an (arbitrary?) Elisp expression. E.g., the solution to the above is</p> <pre><code>M-x replace-regexp &lt;RET&gt; x\([A-Z]\)z &lt;RET&gt; x\,(downcase \1)z </code></pre>
[ { "answer_id": 57794, "author": "Marcel Levy", "author_id": 676, "author_profile": "https://Stackoverflow.com/users/676", "pm_score": 5, "selected": true, "text": "replace-regexp \\,(capitalize \\1)" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57751", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1412/" ]
57,766
<p>I am getting the below error and call stack at the same time everyday after several hours of application use. Can anyone shed some light on what is happening?</p> <pre><code>System.InvalidOperationException: BufferedGraphicsContext cannot be disposed of because a buffer operation is currently in progress. at System.Drawing.BufferedGraphicsContext.Dispose(Boolean disposing) at System.Drawing.BufferedGraphicsContext.Dispose() at System.Drawing.BufferedGraphicsContext.AllocBufferInTempManager(Graphics targetGraphics, IntPtr targetDC, Rectangle targetRectangle) at System.Drawing.BufferedGraphicsContext.Allocate(IntPtr targetDC, Rectangle targetRectangle) at System.Windows.Forms.Control.WmPaint(Message&amp; m) at System.Windows.Forms.Control.WndProc(Message&amp; m) at System.Windows.Forms.ScrollableControl.WndProc(Message&amp; m) at System.Windows.Forms.ToolStrip.WndProc(Message&amp; m) at System.Windows.Forms.MenuStrip.WndProc(Message&amp; m) at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message&amp; m) at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message&amp; m) at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) </code></pre>
[ { "answer_id": 21282876, "author": "TheQaa", "author_id": 2028568, "author_profile": "https://Stackoverflow.com/users/2028568", "pm_score": 0, "selected": false, "text": "BufferedGraphicsContext _BackbufferContext = BufferedGraphicsManager.Current;\n BufferedGraphicsContext _BackbufferContext = new BufferedGraphicsContext();\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4770/" ]
57,776
<p>I have a free standing set of files not affiliated with any C# project at all that reside in a complicated nested directory structure.</p> <p>I want to add them in that format to a different directory in an ASP.NET web application I am working on; while retaining the same structure. So, I copied the folder into the target location of my project and I tried to “add existing item” only to lose the previous folder hierarchy.</p> <p>Usually I have re-created the directories by hand, copied across on a one-to-one basis, and then added existing items. There are simply too many directories/items in this case.</p> <p>So how do you add existing directories and files in Visual Studio 2008?</p>
[ { "answer_id": 13624351, "author": "Boris_P_", "author_id": 1395598, "author_profile": "https://Stackoverflow.com/users/1395598", "pm_score": 0, "selected": false, "text": "*.cs *.cpp" }, { "answer_id": 30772845, "author": "Bjego", "author_id": 3337035, "author_profile": "https://Stackoverflow.com/users/3337035", "pm_score": 3, "selected": false, "text": "<ItemGroup>\n <Item Include=\"$([System.IO.Directory]::GetFiles(&quot;$(MSBuildProjectDirectory)\\node_modules&quot;,&quot;*&quot;,SearchOption.AllDirectories))\"></Item>\n</ItemGroup>\n <Project>\n</Project>\n" }, { "answer_id": 42975811, "author": "Naren", "author_id": 2256349, "author_profile": "https://Stackoverflow.com/users/2256349", "pm_score": 2, "selected": false, "text": "devenv.exe <source folder>" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57776", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2213/" ]
57,791
<p>I have a page which does quite a bit of work and I don't want the user to be able to navigate away from that page (close browser, hit back button, etc.) without getting a warning. I found that the onbeforeunload event (which I think is IE-specific, which works fine for me as the project uses lots of ActiveX) works great.</p> <p>Problem is, I want the user to be able to click on a little "help" icon in the upper-right corner and pop up a help window at any time. This causes onbeforeunload to fire, even though the main window never goes anywhere and the page never unloads. </p> <p>The JavaScript function that runs when the onbeforeunload event runs just puts text into event.returnValue. If I could ascertain, somehow, that the help icon is the one that was clicked then I could just not put text into event.returnValue in that situation. But how could I have the page figure that out?</p>
[ { "answer_id": 57827, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 4, "selected": true, "text": "javascript: <!-- clicking this link will do nothing. No onbeforeunload handler triggered. \nNothing. \nAnd you could put something in before the return false bit...\n...and the onunload handler would still not get called... -->\n<a href=\"http://www.google.com/\" onclick=\"return false;\">blah1</a>\n<!-- this should also do nothing, but IE will trigger the onbeforeunload \nhandler -->\n<a href=\"javascript:void(0)\">blah2</a>\n" }, { "answer_id": 221423, "author": "Kevin Dark", "author_id": 26151, "author_profile": "https://Stackoverflow.com/users/26151", "pm_score": -1, "selected": false, "text": "<html>\n<head>\n<script language=\"Javascript\" type=\"text/javascript\">\n window.onbeforeunload = exitCheck;\n window.onunload = onCloseDoSomething;\n\n function onCloseDoSomething()\n {\n alert(\"This is executed at unload\");\n }\n\n function exitCheck(evt)\n {\n return \"Any string here.\"}\n </script>\n </head>\n\n <frameset rows=\"100%\">\n <FRAME name=\"main\" src=\"http://www.yourDomain.com/yourActualPage.aspx\">\n </frameset>\n<body>\n</body>\n</html>\n" }, { "answer_id": 415369, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "Page.ClientScript.RegisterStartupScript(typeof(String), \"ConfirmClose\", @\" <script> window.onbeforeunload = confirmExit; function confirmExit() { if(postback == false) return \"\"Please don't leave this page without clicking the 'Save Changes' or 'Discard Changes' buttons.\"\"; } </script>\");\n OnClientClick=\"postback=true;return true;\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57791", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2577/" ]
57,803
<p>How do you convert decimal values to their hexadecimal equivalent in JavaScript?</p>
[ { "answer_id": 57805, "author": "Prestaul", "author_id": 5628, "author_profile": "https://Stackoverflow.com/users/5628", "pm_score": 13, "selected": true, "text": "hexString = yourNumber.toString(16);\n yourNumber = parseInt(hexString, 16);\n" }, { "answer_id": 57807, "author": "Luke Smith", "author_id": 5556, "author_profile": "https://Stackoverflow.com/users/5556", "pm_score": 7, "selected": false, "text": "function decimalToHex(d, padding) {\n var hex = Number(d).toString(16);\n padding = typeof (padding) === \"undefined\" || padding === null ? padding = 2 : padding;\n\n while (hex.length < padding) {\n hex = \"0\" + hex;\n }\n\n return hex;\n}\n" }, { "answer_id": 57814, "author": "Danny Wilson", "author_id": 5364, "author_profile": "https://Stackoverflow.com/users/5364", "pm_score": 4, "selected": false, "text": "var number = 3200;\nvar hexString = number.toString(16);\n" }, { "answer_id": 697841, "author": "Tod", "author_id": 16679, "author_profile": "https://Stackoverflow.com/users/16679", "pm_score": 7, "selected": false, "text": "toString(16) function decimalToHexString(number)\n{\n if (number < 0)\n {\n number = 0xFFFFFFFF + number + 1;\n }\n\n return number.toString(16).toUpperCase();\n}\n\nconsole.log(decimalToHexString(27));\nconsole.log(decimalToHexString(48.6));" }, { "answer_id": 930315, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "function dec2hex(i)\n{\n var result = \"0000\";\n if (i >= 0 && i <= 15) { result = \"000\" + i.toString(16); }\n else if (i >= 16 && i <= 255) { result = \"00\" + i.toString(16); }\n else if (i >= 256 && i <= 4095) { result = \"0\" + i.toString(16); }\n else if (i >= 4096 && i <= 65535) { result = i.toString(16); }\n return result\n}\n" }, { "answer_id": 1446578, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "function decimalToHex(d, padding) {\n var hex = Number(d).toString(16);\n padding = typeof (padding) === \"undefined\" || padding === null ? padding = 2 : padding;\n\n while (hex.length < padding) {\n hex = \"0\" + hex;\n }\n\n return hex;\n}\n" }, { "answer_id": 3689638, "author": "mystifeid", "author_id": 444910, "author_profile": "https://Stackoverflow.com/users/444910", "pm_score": 4, "selected": false, "text": "function decimalToHex(d) {\n var hex = Number(d).toString(16);\n hex = \"000000\".substr(0, 6 - hex.length) + hex;\n return hex;\n}\n\n// Or \"#000000\".substr(0, 7 - hex.length) + hex;\n// Or whatever\n// *Thanks to MSDN\n for (var i = 0; i < hex.length; i++){}\n for (var i = 0, var j = hex.length; i < j; i++){}\n" }, { "answer_id": 6680530, "author": "Fabio Ferrari", "author_id": 87648, "author_profile": "https://Stackoverflow.com/users/87648", "pm_score": 5, "selected": false, "text": "function dec2hex(i) {\n return (i+0x10000).toString(16).substr(-4).toUpperCase();\n}\n" }, { "answer_id": 9034019, "author": "Adamarla", "author_id": 1167359, "author_profile": "https://Stackoverflow.com/users/1167359", "pm_score": 4, "selected": false, "text": "function decimalToHex(decimal, chars) {\n return (decimal + Math.pow(16, chars)).toString(16).slice(-chars).toUpperCase();\n}\n" }, { "answer_id": 11012314, "author": "korona", "author_id": 25731, "author_profile": "https://Stackoverflow.com/users/25731", "pm_score": 3, "selected": false, "text": "function toHexString(n) {\n if(n < 0) {\n n = 0xFFFFFFFF + n + 1;\n }\n return \"0x\" + (\"00000000\" + n.toString(16).toUpperCase()).substr(-8);\n}\n" }, { "answer_id": 12995874, "author": "Eliarh", "author_id": 1762728, "author_profile": "https://Stackoverflow.com/users/1762728", "pm_score": 3, "selected": false, "text": "function hexdec (hex_string) {\n hex_string=((hex_string.charAt(1)!='X' && hex_string.charAt(1)!='x')?hex_string='0X'+hex_string : hex_string);\n hex_string=(hex_string.charAt(2)<8 ? hex_string =hex_string-0x00000000 : hex_string=hex_string-0xFFFFFFFF-1);\n return parseInt(hex_string, 10);\n}\n" }, { "answer_id": 13240395, "author": "Baznr", "author_id": 1801365, "author_profile": "https://Stackoverflow.com/users/1801365", "pm_score": 6, "selected": false, "text": "function toHex(d) {\n return (\"0\"+(Number(d).toString(16))).slice(-2).toUpperCase()\n}\n" }, { "answer_id": 13397771, "author": "Keith Mashinter", "author_id": 1826649, "author_profile": "https://Stackoverflow.com/users/1826649", "pm_score": 4, "selected": false, "text": "# function rgb2hex(r,g,b) {\n if (g !== undefined)\n return Number(0x1000000 + r*0x10000 + g*0x100 + b).toString(16).substring(1);\n else\n return Number(0x1000000 + r[0]*0x10000 + r[1]*0x100 + r[2]).toString(16).substring(1);\n}\n" }, { "answer_id": 13865336, "author": "almaz", "author_id": 460477, "author_profile": "https://Stackoverflow.com/users/460477", "pm_score": 3, "selected": false, "text": ".toString(16) symbols var hex = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];\nfunction getHexRepresentation(num, symbols) {\n var result = '';\n while (symbols--) {\n result = hex[num & 0xF] + result;\n num >>= 4;\n }\n return result;\n}\n .toString(16) symbols" }, { "answer_id": 17023332, "author": "R D", "author_id": 2448914, "author_profile": "https://Stackoverflow.com/users/2448914", "pm_score": 3, "selected": false, "text": "var hex = dec.toString(16) \"12\".toString(16) // Avoids a hard-to-track-down bug by returning `c` instead of `12`\n(+\"12\").toString(16);\n var dec = +(\"0x\" + hex);\n" }, { "answer_id": 17106974, "author": "Alberto", "author_id": 413020, "author_profile": "https://Stackoverflow.com/users/413020", "pm_score": 6, "selected": false, "text": ">>> > (-1).toString(16)\n\"-1\"\n\n> ((-2)>>>0).toString(16)\n\"fffffffe\"\n" }, { "answer_id": 20483568, "author": "realkstrawn93", "author_id": 1118706, "author_profile": "https://Stackoverflow.com/users/1118706", "pm_score": 2, "selected": false, "text": "function toHex(i, pad) {\n\n if (typeof(pad) === 'undefined' || pad === null) {\n pad = 2;\n } \n\n var strToParse = i.toString(16);\n\n while (strToParse.length < pad) {\n strToParse = \"0\" + strToParse;\n }\n\n var finalVal = parseInt(strToParse, 16);\n\n if ( finalVal < 0 ) {\n finalVal = 0xFFFFFFFF + finalVal + 1;\n }\n\n return finalVal;\n}\n" }, { "answer_id": 26784300, "author": "Mark Manning", "author_id": 928121, "author_profile": "https://Stackoverflow.com/users/928121", "pm_score": 5, "selected": false, "text": "function numHex(s)\n{\n var a = s.toString(16);\n if ((a.length % 2) > 0) {\n a = \"0\" + a;\n }\n return a;\n}\n function strHex(s)\n{\n var a = \"\";\n for (var i=0; i<s.length; i++) {\n a = a + numHex(s.charCodeAt(i));\n }\n\n return a;\n}\n function toHex(s)\n{\n var re = new RegExp(/^\\s*(\\+|-)?((\\d+(\\.\\d+)?)|(\\.\\d+))\\s*$/);\n\n if (re.test(s)) {\n return '#' + strHex( s.toString());\n }\n else {\n return 'A' + strHex(s);\n }\n}\n /////////////////////////////////////////////////////////////////////////////\n// toHex(). Convert an ASCII string to hexadecimal.\n/////////////////////////////////////////////////////////////////////////////\ntoHex(s)\n{\n if (s.substr(0,2).toLowerCase() == \"0x\") {\n return s;\n }\n\n var l = \"0123456789ABCDEF\";\n var o = \"\";\n\n if (typeof s != \"string\") {\n s = s.toString();\n }\n for (var i=0; i<s.length; i++) {\n var c = s.charCodeAt(i);\n\n o = o + l.substr((c>>4),1) + l.substr((c & 0x0f),1);\n }\n\n return \"0x\" + o;\n}\n /////////////////////////////////////////////////////////////////////////////\n// fromHex(). Convert a hex string to ASCII text.\n/////////////////////////////////////////////////////////////////////////////\nfromHex(s)\n{\n var start = 0;\n var o = \"\";\n\n if (s.substr(0,2).toLowerCase() == \"0x\") {\n start = 2;\n }\n\n if (typeof s != \"string\") {\n s = s.toString();\n }\n for (var i=start; i<s.length; i+=2) {\n var c = s.substr(i, 2);\n\n o = o + String.fromCharCode(parseInt(c, 16));\n }\n\n return o;\n}\n <?php\n\n echo <<<EOD\n<html>\n <head><title>Test</title>\n <script>\n var a = -3.14159265;\n alert( \"A = \" + a );\n var b = a.toString();\n alert( \"B = \" + b );\n </script>\n </head>\n <body>\n </body>\n</html>\nEOD;\n\n?>\n" }, { "answer_id": 33622834, "author": "Hat", "author_id": 2203482, "author_profile": "https://Stackoverflow.com/users/2203482", "pm_score": 4, "selected": false, "text": "function decToHex(dec) {\n return (dec + Math.pow(16, 6)).toString(16).substr(-6)\n}\n let c = 4210330 // your color in decimal format\nlet rgb = [(c & 0xff0000) >> 16, (c & 0x00ff00) >> 8, (c & 0x0000ff)]\n\n// Vanilla JS:\ndocument..getElementById('some-element').style.color = 'rgb(' + rgb + ')'\n// jQuery:\n$('#some-element').css('color', 'rgb(' + rgb + ')')\n #some-element color rgb(64, 62, 154)" }, { "answer_id": 35251679, "author": "JonLikeSquirrel", "author_id": 5763792, "author_profile": "https://Stackoverflow.com/users/5763792", "pm_score": 2, "selected": false, "text": "function DecToHex(decimal) { // Data (decimal)\n\n length = -1; // Base string length\n string = ''; // Source 'string'\n\n characters = [ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' ]; // character array\n\n do { // Grab each nibble in reverse order because JavaScript has no unsigned left shift\n\n string += characters[decimal & 0xF]; // Mask byte, get that character\n ++length; // Increment to length of string\n\n } while (decimal >>>= 4); // For next character shift right 4 bits, or break on 0\n\n decimal += 'x'; // Convert that 0 into a hex prefix string -> '0x'\n\n do\n decimal += string[length];\n while (length--); // Flip string forwards, with the prefixed '0x'\n\n return (decimal); // return (hexadecimal);\n}\n\n/* Original: */\n\nD = 3678; // Data (decimal)\nC = 0xF; // Check\nA = D; // Accumulate\nB = -1; // Base string length\nS = ''; // Source 'string'\nH = '0x'; // Destination 'string'\n\ndo {\n ++B;\n A& = C;\n\n switch(A) {\n case 0xA: A='A'\n break;\n\n case 0xB: A='B'\n break;\n\n case 0xC: A='C'\n break;\n\n case 0xD: A='D'\n break;\n\n case 0xE: A='E'\n break;\n\n case 0xF: A='F'\n break;\n\n A = (A);\n }\n S += A;\n\n D >>>= 0x04;\n A = D;\n} while(D)\n\ndo\n H += S[B];\nwhile (B--)\n\nS = B = A = C = D; // Zero out variables\nalert(H); // H: holds hexadecimal equivalent\n" }, { "answer_id": 47125022, "author": "Francisco Manuel Garca Botella", "author_id": 4285108, "author_profile": "https://Stackoverflow.com/users/4285108", "pm_score": 2, "selected": false, "text": "((0xFF + number +1) & 0x0FF).toString(16);\n FF ((0xFFFF + number +1) & 0x0FFFF).toString(16);\n s = \"\";\nfor(var i = 0; i < arrayNumber.length; ++i) {\n s += ((0xFF + arrayNumber[i] +1) & 0x0FF).toString(16);\n}\n" }, { "answer_id": 49264490, "author": "dhc", "author_id": 2868394, "author_profile": "https://Stackoverflow.com/users/2868394", "pm_score": 2, "selected": false, "text": " numToHex = function(num) {\n var r=((0xff0000&num)>>16).toString(16),\n g=((0x00ff00&num)>>8).toString(16),\n b=(0x0000ff&num).toString(16);\n if (r.length==1) { r = '0'+r; }\n if (g.length==1) { g = '0'+g; }\n if (b.length==1) { b = '0'+b; }\n return '0x'+r+g+b; // ('#' instead of'0x' for CSS)\n };\n\n var dec = 5974678;\n console.log( numToHex(dec) ); // 0x5b2a96\n" }, { "answer_id": 53389207, "author": "Hypersoft Systems", "author_id": 3370790, "author_profile": "https://Stackoverflow.com/users/3370790", "pm_score": -1, "selected": false, "text": "hex = function(number) {\n return '0x' + Math.abs(number).toString(16);\n}\n" }, { "answer_id": 54441205, "author": "Alireza", "author_id": 5423108, "author_profile": "https://Stackoverflow.com/users/5423108", "pm_score": 2, "selected": false, "text": "const toHex = num => (num).toString(16).toUpperCase();\n" }, { "answer_id": 56180356, "author": "Abhilash Nayak", "author_id": 5950470, "author_profile": "https://Stackoverflow.com/users/5950470", "pm_score": 2, "selected": false, "text": "const hugeNumber = \"9007199254740991873839\" // Make sure its in String\nconst hexOfHugeNumber = BigInt(hugeNumber).toString(16);\nconsole.log(hexOfHugeNumber)" }, { "answer_id": 57551796, "author": "Brian", "author_id": 2850957, "author_profile": "https://Stackoverflow.com/users/2850957", "pm_score": 2, "selected": false, "text": "function decimalToPaddedHexString(number, bitsize)\n{ \n let byteCount = Math.ceil(bitsize/8);\n let maxBinValue = Math.pow(2, bitsize)-1;\n\n /* In node.js this function fails for bitsize above 32bits */\n if (bitsize > 32)\n throw \"number above maximum value\";\n\n /* Conversion to unsigned form based on */\n if (number < 0)\n number = maxBinValue + number + 1;\n\n return \"0x\"+(number >>> 0).toString(16).toUpperCase().padStart(byteCount*2, '0');\n}\n for (let n = 0 ; n < 64 ; n++ ) { \n let s=decimalToPaddedHexString(-1, n); \n console.log(`decimalToPaddedHexString(-1,${(n+\"\").padStart(2)}) = ${s.padStart(10)} = ${(\"0b\"+parseInt(s).toString(2)).padStart(34)}`);\n }\n decimalToPaddedHexString(-1, 0) = 0x0 = 0b0\ndecimalToPaddedHexString(-1, 1) = 0x01 = 0b1\ndecimalToPaddedHexString(-1, 2) = 0x03 = 0b11\ndecimalToPaddedHexString(-1, 3) = 0x07 = 0b111\ndecimalToPaddedHexString(-1, 4) = 0x0F = 0b1111\ndecimalToPaddedHexString(-1, 5) = 0x1F = 0b11111\ndecimalToPaddedHexString(-1, 6) = 0x3F = 0b111111\ndecimalToPaddedHexString(-1, 7) = 0x7F = 0b1111111\ndecimalToPaddedHexString(-1, 8) = 0xFF = 0b11111111\ndecimalToPaddedHexString(-1, 9) = 0x01FF = 0b111111111\ndecimalToPaddedHexString(-1,10) = 0x03FF = 0b1111111111\ndecimalToPaddedHexString(-1,11) = 0x07FF = 0b11111111111\ndecimalToPaddedHexString(-1,12) = 0x0FFF = 0b111111111111\ndecimalToPaddedHexString(-1,13) = 0x1FFF = 0b1111111111111\ndecimalToPaddedHexString(-1,14) = 0x3FFF = 0b11111111111111\ndecimalToPaddedHexString(-1,15) = 0x7FFF = 0b111111111111111\ndecimalToPaddedHexString(-1,16) = 0xFFFF = 0b1111111111111111\ndecimalToPaddedHexString(-1,17) = 0x01FFFF = 0b11111111111111111\ndecimalToPaddedHexString(-1,18) = 0x03FFFF = 0b111111111111111111\ndecimalToPaddedHexString(-1,19) = 0x07FFFF = 0b1111111111111111111\ndecimalToPaddedHexString(-1,20) = 0x0FFFFF = 0b11111111111111111111\ndecimalToPaddedHexString(-1,21) = 0x1FFFFF = 0b111111111111111111111\ndecimalToPaddedHexString(-1,22) = 0x3FFFFF = 0b1111111111111111111111\ndecimalToPaddedHexString(-1,23) = 0x7FFFFF = 0b11111111111111111111111\ndecimalToPaddedHexString(-1,24) = 0xFFFFFF = 0b111111111111111111111111\ndecimalToPaddedHexString(-1,25) = 0x01FFFFFF = 0b1111111111111111111111111\ndecimalToPaddedHexString(-1,26) = 0x03FFFFFF = 0b11111111111111111111111111\ndecimalToPaddedHexString(-1,27) = 0x07FFFFFF = 0b111111111111111111111111111\ndecimalToPaddedHexString(-1,28) = 0x0FFFFFFF = 0b1111111111111111111111111111\ndecimalToPaddedHexString(-1,29) = 0x1FFFFFFF = 0b11111111111111111111111111111\ndecimalToPaddedHexString(-1,30) = 0x3FFFFFFF = 0b111111111111111111111111111111\ndecimalToPaddedHexString(-1,31) = 0x7FFFFFFF = 0b1111111111111111111111111111111\ndecimalToPaddedHexString(-1,32) = 0xFFFFFFFF = 0b11111111111111111111111111111111\nThrown: 'number above maximum value'\n" }, { "answer_id": 65859562, "author": "Bohdan Sych", "author_id": 4768564, "author_profile": "https://Stackoverflow.com/users/4768564", "pm_score": 2, "selected": false, "text": " function rgb(...values){\n return values.reduce((acc, cur) => {\n let val = cur >= 255 ? 'ff' : cur <= 0 ? '00' : Number(cur).toString(16);\n return acc + (val.length === 1 ? '0'+val : val);\n }, '').toUpperCase();\n }\n" }, { "answer_id": 66126345, "author": "Kamil Kiełczewski", "author_id": 860099, "author_profile": "https://Stackoverflow.com/users/860099", "pm_score": 0, "selected": false, "text": "s i f -123.75 s=true i=123 f=75 i='0' m=i%16 m i=i/16 n k=f*16 k n f d d // @param decStr - string with non-negative integer\n// @param divisor - positive integer\nfunction dec2HexArbitrary(decStr, fracDigits=0) { \n // Helper: divide arbitrary precision number by js number\n // @param decStr - string with non-negative integer\n // @param divisor - positive integer\n function arbDivision(decStr, divisor) \n { \n // algorithm https://www.geeksforgeeks.org/divide-large-number-represented-string/\n let ans=''; \n let idx = 0; \n let temp = +decStr[idx]; \n while (temp < divisor) temp = temp * 10 + +decStr[++idx]; \n\n while (decStr.length > idx) { \n ans += (temp / divisor)|0 ; \n temp = (temp % divisor) * 10 + +decStr[++idx]; \n } \n\n if (ans.length == 0) return \"0\"; \n\n return ans; \n } \n\n // Helper: calc module of arbitrary precision number\n // @param decStr - string with non-negative integer\n // @param mod - positive integer\n function arbMod(decStr, mod) { \n // algorithm https://www.geeksforgeeks.org/how-to-compute-mod-of-a-big-number/\n let res = 0; \n\n for (let i = 0; i < decStr.length; i++) \n res = (res * 10 + +decStr[i]) % mod; \n\n return res; \n } \n\n // Helper: multiply arbitrary precision integer by js number\n // @param decStr - string with non-negative integer\n // @param mult - positive integer\n function arbMultiply(decStr, mult) {\n let r='';\n let m=0;\n for (let i = decStr.length-1; i >=0 ; i--) {\n let n = m+mult*(+decStr[i]);\n r= (i ? n%10 : n) + r \n m= n/10|0;\n }\n return r;\n }\n \n \n // dec2hex algorithm starts here\n \n let h= '0123456789abcdef'; // hex 'alphabet'\n let m= decStr.match(/-?(.*?)\\.(.*)?/) || decStr.match(/-?(.*)/); // separate sign,integer,ractional\n let i= m[1].replace(/^0+/,'').replace(/^$/,'0'); // integer part (without sign and leading zeros)\n let f= (m[2]||'0').replace(/0+$/,'').replace(/^$/,'0'); // fractional part (without last zeros)\n let s= decStr[0]=='-'; // sign\n\n let r=''; // result\n \n if(i=='0') r='0';\n \n while(i!='0') { // integer part\n r=h[arbMod(i,16)]+r; \n i=arbDivision(i,16);\n }\n \n if(fracDigits) r+=\".\";\n \n let n = f.length;\n \n for(let j=0; j<fracDigits; j++) { // frac part\n let k= arbMultiply(f,16);\n f = k.slice(-n);\n let d= k.slice(0,k.length-n); \n r+= d.length ? h[+d] : '0';\n }\n \n return (s?'-':'')+r;\n}\n\n\n\n\n\n\n\n\n// -----------\n// TESTS\n// -----------\n\n\n\nlet tests = [\n [\"0\",2],\n [\"000\",2], \n [\"123\",0],\n [\"-123\",0], \n [\"00.000\",2],\n \n [\"255.75\",5],\n [\"-255.75\",5], \n [\"127.999\",32], \n];\n\nconsole.log('Input Standard Abitrary');\ntests.forEach(t=> {\n let nonArb = (+t[0]).toString(16).padEnd(17,' ');\n let arb = dec2HexArbitrary(t[0],t[1]);\n console.log(t[0].padEnd(10,' '), nonArb, arb); \n});\n\n\n// Long Example (40 digits after dot)\nlet example = \"123456789012345678901234567890.09876543210987654321\"\nconsole.log(`\\nLong Example:`);\nconsole.log('dec:',example);\nconsole.log('hex: ',dec2HexArbitrary(example,40));" }, { "answer_id": 71171818, "author": "Wilt", "author_id": 1697459, "author_profile": "https://Stackoverflow.com/users/1697459", "pm_score": 2, "selected": false, "text": "toString padStart const string = `#${color.toString(16).padStart(6, '0')}`;\n 0x000000 #000000 0xFFFFFF #FFFFFF" }, { "answer_id": 71523192, "author": "aGuegu", "author_id": 1764290, "author_profile": "https://Stackoverflow.com/users/1764290", "pm_score": 0, "selected": false, "text": "01 11 import { Buffer } from 'buffer';\n\nfunction toHex(n) { // 4byte\n const buff = Buffer.alloc(4);\n buff.writeInt32BE(n);\n return buff.toString('hex');\n}\n\n > toHex(1)\n'00000001'\n> toHex(17)\n'00000011'\n> toHex(-1)\n'ffffffff'\n> toHex(-1212)\n'fffffb44'\n> toHex(1212)\n'000004bc'\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5556/" ]
57,804
<p>Now, before you say it: I <strong>did</strong> Google and my <code>hbm.xml</code> file <strong>is</strong> an Embedded Resource. </p> <p>Here is the code I am calling:</p> <pre><code>ISession session = GetCurrentSession(); var returnObject = session.Get&lt;T&gt;(Id); </code></pre> <p>Here is my mapping file for the class:</p> <pre class="lang-xml prettyprint-override"><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"&gt; &lt;class name="HQData.Objects.SubCategory, HQData" table="SubCategory" lazy="true"&gt; &lt;id name="ID" column="ID" unsaved-value="0"&gt; &lt;generator class="identity" /&gt; &lt;/id&gt; &lt;property name="Name" column="Name" /&gt; &lt;property name="NumberOfBuckets" column="NumberOfBuckets" /&gt; &lt;property name="SearchCriteriaOne" column="SearchCriteriaOne" /&gt; &lt;bag name="_Businesses" cascade="all"&gt; &lt;key column="SubCategoryId"/&gt; &lt;one-to-many class="HQData.Objects.Business, HQData"/&gt; &lt;/bag&gt; &lt;bag name="_Buckets" cascade="all"&gt; &lt;key column="SubCategoryId"/&gt; &lt;one-to-many class="HQData.Objects.Bucket, HQData"/&gt; &lt;/bag&gt; &lt;/class&gt; &lt;/hibernate-mapping&gt; </code></pre> <p>Has anyone run to this issue before?</p> <p>Here is the full error message:</p> <blockquote> <pre>MappingException: No persister for: HQData.Objects.SubCategory]NHibernate.Impl.SessionFactoryImpl.GetEntityPersister(String entityName, Boolean throwIfNotFound) in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionFactoryImpl.cs:766 NHibernate.Impl.SessionFactoryImpl.GetEntityPersister(String entityName) in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionFactoryImpl.cs:752 NHibernate.Event.Default.DefaultLoadEventListener.OnLoad(LoadEvent event, LoadType loadType) in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Event\Default\DefaultLoadEventListener.cs:37 NHibernate.Impl.SessionImpl.FireLoad(LoadEvent event, LoadType loadType) in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionImpl.cs:2054 NHibernate.Impl.SessionImpl.Get(String entityName, Object id) in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionImpl.cs:1029 NHibernate.Impl.SessionImpl.Get(Type entityClass, Object id) in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionImpl.cs:1020 NHibernate.Impl.SessionImpl.Get(Object id) in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionImpl.cs:985 HQData.DataAccessUtils.NHibernateObjectHelper.LoadDataObject(Int32 Id) in C:\Development\HQChannelRepo\HQ Channel Application\HQChannel\HQData\DataAccessUtils\NHibernateObjectHelper.cs:42 HQWebsite.LocalSearch.get_subCategory() in C:\Development\HQChannelRepo\HQ Channel Application\HQChannel\HQWebsite\LocalSearch.aspx.cs:17 HQWebsite.LocalSearch.Page_Load(Object sender, EventArgs e) in C:\Development\HQChannelRepo\HQ Channel Application\HQChannel\HQWebsite\LocalSearch.aspx.cs:27 System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +15 System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +33 System.Web.UI.Control.OnLoad(EventArgs e) +99 System.Web.UI.Control.LoadRecursive() +47 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1436</pre> </blockquote> <p><strong>Update</strong>, here's what the solution for <em>my</em> scenario was: I had changed some code and I wasn't adding the Assembly to the config file during runtime. </p>
[ { "answer_id": 57860, "author": "Matt Hinze", "author_id": 2676, "author_profile": "https://Stackoverflow.com/users/2676", "pm_score": 2, "selected": false, "text": "name=\"Id\"" }, { "answer_id": 57995, "author": "Andy S", "author_id": 3759, "author_profile": "https://Stackoverflow.com/users/3759", "pm_score": 8, "selected": true, "text": ".\n.\n <property name=\"show_sql\">true</property>\n <property name=\"query.substitutions\">true 1, false 0, yes 'Y', no 'N'</property>\n <mapping assembly=\"Project.DomainModel\"/> <!-- Here -->\n</session-factory>\n.\n.\n" }, { "answer_id": 660099, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "find(\"Class\",id)\n find(\"assemblyName.Class\",id)\n" }, { "answer_id": 3542235, "author": "basarat", "author_id": 390330, "author_profile": "https://Stackoverflow.com/users/390330", "pm_score": 6, "selected": false, "text": "public class UserMap : ClassMap<user> // note the public!\n class UserMap : ClassMap<user>\n" }, { "answer_id": 6112707, "author": "Seth", "author_id": 521662, "author_profile": "https://Stackoverflow.com/users/521662", "pm_score": 2, "selected": false, "text": "cfg.AddAssembly(..." }, { "answer_id": 7360026, "author": "Amol", "author_id": 189654, "author_profile": "https://Stackoverflow.com/users/189654", "pm_score": 0, "selected": false, "text": "CreateCriteria(typeof(DomainObjectType))" }, { "answer_id": 23153675, "author": "Arkadas Kilic", "author_id": 3276913, "author_profile": "https://Stackoverflow.com/users/3276913", "pm_score": 2, "selected": false, "text": ".Mappings(m => m.FluentMappings.AddFromAssemblyOf<YourEntityClassName>())\n" }, { "answer_id": 60490552, "author": "Robetto", "author_id": 3631770, "author_profile": "https://Stackoverflow.com/users/3631770", "pm_score": 0, "selected": false, "text": " OBJEKTE t = _mapper.Map<OBJEKTE>(inparam);\n OBJEKTE res = await _objRepo.UpdateAsync(t);\n t.GetType()\n{Name = \"OBJEKTE\" FullName = \"MyComp.Persistence.OBJEKTE\"}\n\ninparam.GetType()\n{Name = \"OBJEKTEProxyForFieldInterceptor\" FullName = \"OBJEKTEProxyForFieldInterceptor\"}\n inparam" }, { "answer_id": 65218643, "author": "xhafan", "author_id": 379279, "author_profile": "https://Stackoverflow.com/users/379279", "pm_score": 0, "selected": false, "text": "await var company = _unitOfWork.Session.GetAsync<Company>(id);\n await _unitOfWork.Session.DeleteAsync(company);\n Task<Company> Company" }, { "answer_id": 71228041, "author": "Mitja", "author_id": 1651498, "author_profile": "https://Stackoverflow.com/users/1651498", "pm_score": 0, "selected": false, "text": "ISessionFactory ISession" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57804", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4140/" ]
57,812
<p>I have a div with <code>id="a"</code> that may have any number of classes attached to it, from several groups. Each group has a specific prefix. In the javascript, I don't know which class from the group is on the div. I want to be able to clear all classes with a given prefix and then add a new one. If I want to remove all of the classes that begin with "bg", how do I do that? Something like this, but that actually works:</p> <pre><code>$("#a").removeClass("bg*"); </code></pre>
[ { "answer_id": 57819, "author": "Prestaul", "author_id": 5628, "author_profile": "https://Stackoverflow.com/users/5628", "pm_score": 4, "selected": false, "text": "$(\"#a\").className = $(\"#a\").className.replace(/\\bbg.*?\\b/g, '');\n function removeClassByPrefix(el, prefix) {\n var regx = new RegExp('\\\\b' + prefix + '.*?\\\\b', 'g');\n el.className = el.className.replace(regx, '');\n return el;\n}\n" }, { "answer_id": 58097, "author": "Brad", "author_id": 5464, "author_profile": "https://Stackoverflow.com/users/5464", "pm_score": 0, "selected": false, "text": "document.getElementById(\"a\").className\n $(\"#a\").className\n" }, { "answer_id": 58533, "author": "Pat", "author_id": 238, "author_profile": "https://Stackoverflow.com/users/238", "pm_score": 7, "selected": true, "text": "$('#a')[0].className = $('#a')[0].className.replace(/\\bbg.*?\\b/g, '');\n" }, { "answer_id": 3284637, "author": "jamland", "author_id": 344306, "author_profile": "https://Stackoverflow.com/users/344306", "pm_score": 0, "selected": false, "text": "$('#a')[0].className = $('#a')[0].className.replace(/\\bbg.\\d-*?\\b/g, '');\n" }, { "answer_id": 8624674, "author": "Pete B", "author_id": 263643, "author_profile": "https://Stackoverflow.com/users/263643", "pm_score": 5, "selected": false, "text": "$( '#foo' ).alterClass( 'foo-* bar-*', 'foobar' ) \n" }, { "answer_id": 10835425, "author": "Kabir Sarin", "author_id": 1181570, "author_profile": "https://Stackoverflow.com/users/1181570", "pm_score": 7, "selected": false, "text": "\\b var prefix = \"prefix\";\nvar classes = el.className.split(\" \").filter(function(c) {\n return c.lastIndexOf(prefix, 0) !== 0;\n});\nel.className = classes.join(\" \").trim();\n $.fn.removeClassPrefix = function(prefix) {\n this.each(function(i, el) {\n var classes = el.className.split(\" \").filter(function(c) {\n return c.lastIndexOf(prefix, 0) !== 0;\n });\n el.className = $.trim(classes.join(\" \"));\n });\n return this;\n};\n const prefix = \"prefix\";\nconst classes = el.className.split(\" \").filter(c => !c.startsWith(prefix));\nel.className = classes.join(\" \").trim();\n" }, { "answer_id": 12635031, "author": "Jan.J", "author_id": 937367, "author_profile": "https://Stackoverflow.com/users/937367", "pm_score": 1, "selected": false, "text": "$('#a')[0].className = $('#a')[0].className\n .replace(/(^|\\s)bg.*?(\\s|$)/g, ' ')\n .replace(/\\s\\s+/g, ' ')\n .replace(/(^\\s|\\s$)/g, '');\n" }, { "answer_id": 13944814, "author": "Rob", "author_id": 1200670, "author_profile": "https://Stackoverflow.com/users/1200670", "pm_score": 0, "selected": false, "text": "(function($)\n{\n return this.each(function()\n {\n var classes = $(this).attr('class');\n\n if(!classes || !regex) return false;\n\n var classArray = [];\n\n classes = classes.split(' ');\n\n for(var i=0, len=classes.length; i<len; i++) if(!classes[i].match(regex)) classArray.push(classes[i]);\n\n $(this).attr('class', classArray.join(' '));\n });\n})(jQuery);\n" }, { "answer_id": 14855671, "author": "majorsk8", "author_id": 2068678, "author_profile": "https://Stackoverflow.com/users/2068678", "pm_score": -1, "selected": false, "text": "$(\"#element\").removeAttr(\"class\").addClass(\"yourClass\");\n" }, { "answer_id": 15235183, "author": "abernier", "author_id": 133327, "author_profile": "https://Stackoverflow.com/users/133327", "pm_score": 3, "selected": false, "text": "$.fn.removeClass // Considering:\nvar $el = $('<div class=\" foo-1 a b foo-2 c foo\"/>');\n\nfunction makeRemoveClassHandler(regex) {\n return function (index, classes) {\n return classes.split(/\\s+/).filter(function (el) {return regex.test(el);}).join(' ');\n }\n}\n\n$el.removeClass(makeRemoveClassHandler(/^foo-/));\n//> [<div class=​\"a b c foo\">​</div>​]\n" }, { "answer_id": 19368577, "author": "Pawel", "author_id": 696535, "author_profile": "https://Stackoverflow.com/users/696535", "pm_score": 2, "selected": false, "text": "(function ($) {\n $.fn.removePrefixedClasses = function (prefix) {\n var classNames = $(this).attr('class').split(' '),\n className,\n newClassNames = [],\n i;\n //loop class names\n for(i = 0; i < classNames.length; i++) {\n className = classNames[i];\n // if prefix not found at the beggining of class name\n if(className.indexOf(prefix) !== 0) {\n newClassNames.push(className);\n continue;\n }\n }\n // write new list excluding filtered classNames\n $(this).attr('class', newClassNames.join(' '));\n };\n }(fQuery));\n $('#elementId').removePrefixedClasses('prefix-of-classes_');\n" }, { "answer_id": 29002847, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "function removeclasses(controlIndex,classPrefix){\n var classes = $(\"#\"+controlIndex).attr(\"class\").split(\" \");\n $.each(classes,function(index) {\n if(classes[index].indexOf(classPrefix)==0) {\n $(\"#\"+controlIndex).removeClass(classes[index]);\n }\n });\n}\n removeclasses(\"a\",\"bg\");\n" }, { "answer_id": 44884314, "author": "Adam111p", "author_id": 3058581, "author_profile": "https://Stackoverflow.com/users/3058581", "pm_score": 2, "selected": false, "text": "$('#my_element_id').removeClass( function() { return (this.className.match(/someRegExp/g) || []).join(' ').replace(prog.status.toLowerCase(),'');});\n" }, { "answer_id": 53002208, "author": "Max", "author_id": 2944332, "author_profile": "https://Stackoverflow.com/users/2944332", "pm_score": 3, "selected": false, "text": "let element = $('#a')[0];\nlet cls = 'bg';\n\nelement.classList.remove.apply(element.classList, Array.from(element.classList).filter(v=>v.startsWith(cls)));\n" }, { "answer_id": 68063824, "author": "danday74", "author_id": 1205871, "author_profile": "https://Stackoverflow.com/users/1205871", "pm_score": 0, "selected": false, "text": "const prefix = 'prefix'\nconst classes = el.attr('class').split(' ').filter(c => !c.startsWith(prefix))\nel.attr('class', classes.join(' ').trim())\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5464/" ]
57,840
<p>I have a wrapper around a C++ function call which I call from C# code. How do I attach a debugger in Visual Studio to step into the native C++ code?</p> <p>This is the wrapper that I have which calls GetData() defined in a C++ file:</p> <pre><code> [DllImport("Unmanaged.dll", CallingConvention=CallingConvention.Cdecl, EntryPoint = "GetData", BestFitMapping = false)] public static extern String GetData(String url); </code></pre> <p>The code is crashing and I want to investigate the root cause.</p> <p>Thanks, Nikhil</p>
[ { "answer_id": 58954, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": ".sympath\n.sympath+ \n.symfix\n .srcpath\n .extpath \n sxe ld:mscorwks\n .chain\n .loadby sos mscorwks\n .reload\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57840", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5734/" ]
57,845
<p>Is it possible to use BackGroundWorker thread in <a href="http://en.wikipedia.org/wiki/ASP.NET" rel="nofollow noreferrer">ASP.NET</a> 2.0 for the following scenario, so that the user at the browser's end does not have to wait for long time?</p> <h2>Scenario</h2> <ol> <li>The browser requests a page, say SendEmails.aspx</li> <li>SendEmails.aspx page creates a BackgroundWorker thread, and supplies the thread with enough context to create and send emails.</li> <li>The browser receives the response from the ComposeAndSendEmails.aspx, saying that emails are being sent.</li> <li>Meanwhile, the background thread is engaged in a process of creating and sending emails which could take some considerable time to complete.</li> </ol> <p>My main concern is about keeping the BackgroundWorker thread running, trying to send, say 50 emails while the ASP.NET workerprocess threadpool thread is long gone.</p>
[ { "answer_id": 57847, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 3, "selected": false, "text": "ThreadPool.QueueUserWorkItem(delegateThatSendsEmails)\n" }, { "answer_id": 431015, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "{\n System.Threading.Thread _thread = new Thread(new ThreadStart(Activity_DoWork));\n _thred.Start();\n}\nActivity_DoWork()\n{\n /*Do some things...\n}\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1647/" ]
57,849
<p>There doesn't seem to be a way to change the padding (or row height) for all rows in a .NET ListView. Does anybody have an elegant hack-around?</p>
[ { "answer_id": 13072438, "author": "Quinn Johns", "author_id": 1539718, "author_profile": "https://Stackoverflow.com/users/1539718", "pm_score": 4, "selected": false, "text": "using System.Runtime.InteropServices;\n [DllImport(\"user32.dll\")]\npublic static extern int SendMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);\n public int MakeLong(short lowPart, short highPart)\n{\n return (int)(((ushort)lowPart) | (uint)(highPart << 16));\n}\n\npublic void ListViewItem_SetSpacing(ListView listview, short leftPadding, short topPadding) \n{ \n const int LVM_FIRST = 0x1000; \n const int LVM_SETICONSPACING = LVM_FIRST + 53; \n SendMessage(listview.Handle, LVM_SETICONSPACING, IntPtr.Zero, (IntPtr)MakeLong(leftPadding, topPadding)); \n} \n ListViewItem_SetSpacing(this.listView1, 64 + 32, 100 + 16);\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57849", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
57,854
<p>How can I close a browser window without receiving the <em>Do you want to close this window</em> prompt?</p> <p>The prompt occurs when I use the <code>window.close();</code> function.</p>
[ { "answer_id": 57857, "author": "Derek", "author_id": 5440, "author_profile": "https://Stackoverflow.com/users/5440", "pm_score": -1, "selected": false, "text": "this.focus();\nself.opener=this;\nself.close();\n" }, { "answer_id": 57868, "author": "Harley Holcombe", "author_id": 1057, "author_profile": "https://Stackoverflow.com/users/1057", "pm_score": 3, "selected": false, "text": "<a href=\"javascript:window.opener='x';window.close();\">Close</a>\n window.opener" }, { "answer_id": 57872, "author": "Billy Jo", "author_id": 3447, "author_profile": "https://Stackoverflow.com/users/3447", "pm_score": 0, "selected": false, "text": "window.open('foo.html');" }, { "answer_id": 713230, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "window.opener=window;\nwindow.close();\n" }, { "answer_id": 1412097, "author": "Nick", "author_id": 56256, "author_profile": "https://Stackoverflow.com/users/56256", "pm_score": 6, "selected": false, "text": "window.close() alert(\"No whammies!\");\nwindow.open(\"closer.htm\", '_self');\n <script type=\"text/javascript\">\n window.close();\n</script>\n" }, { "answer_id": 2730590, "author": "Arabam", "author_id": 326958, "author_profile": "https://Stackoverflow.com/users/326958", "pm_score": 6, "selected": false, "text": "window.open('', '_self', ''); window.close();\n" }, { "answer_id": 4432315, "author": "JimB", "author_id": 256960, "author_profile": "https://Stackoverflow.com/users/256960", "pm_score": 4, "selected": false, "text": "<body onload=\"window.open('', '_self', '');\">\n <a href=\"javascript:window.close();\">\n" }, { "answer_id": 7262745, "author": "jbabey", "author_id": 386152, "author_profile": "https://Stackoverflow.com/users/386152", "pm_score": 3, "selected": false, "text": "_self window.open('', '_self', '');\nwindow.close();\n" }, { "answer_id": 13914234, "author": "Niloofar", "author_id": 1814925, "author_profile": "https://Stackoverflow.com/users/1814925", "pm_score": 2, "selected": false, "text": "<script type=\"text/javascript\">\n function closeme() {\n window.open('', '_self', '');\n window.close();\n }\n</script>\n <a href=\"Help.aspx\" target=\"_blank\" onclick=\"closeme();\">Help</a>\n <a href=\"\" onclick=\"closeme();\">close</a>\n" }, { "answer_id": 15917784, "author": "Danny Beckett", "author_id": 1563422, "author_profile": "https://Stackoverflow.com/users/1563422", "pm_score": 4, "selected": false, "text": "<script type=\"text/javascript\">\n window.open('javascript:window.open(\"\", \"_self\", \"\");window.close();', '_self');\n</script>\n window.open" }, { "answer_id": 16412945, "author": "Kuldip D Gandhi", "author_id": 2357159, "author_profile": "https://Stackoverflow.com/users/2357159", "pm_score": 5, "selected": false, "text": " function closeWindows() {\n var browserName = navigator.appName;\n var browserVer = parseInt(navigator.appVersion);\n //alert(browserName + \" : \"+browserVer);\n\n //document.getElementById(\"flashContent\").innerHTML = \"<br>&nbsp;<font face='Arial' color='blue' size='2'><b> You have been logged out of the Game. Please Close Your Browser Window.</b></font>\";\n\n if(browserName == \"Microsoft Internet Explorer\"){\n var ie7 = (document.all && !window.opera && window.XMLHttpRequest) ? true : false; \n if (ie7)\n { \n //This method is required to close a window without any prompt for IE7 & greater versions.\n window.open('','_parent','');\n window.close();\n }\n else\n {\n //This method is required to close a window without any prompt for IE6\n this.focus();\n self.opener = this;\n self.close();\n }\n }else{ \n //For NON-IE Browsers except Firefox which doesnt support Auto Close\n try{\n this.focus();\n self.opener = this;\n self.close();\n }\n catch(e){\n\n }\n\n try{\n window.open('','_self','');\n window.close();\n }\n catch(e){\n\n }\n }\n }\n" }, { "answer_id": 18863981, "author": "Vivek", "author_id": 2373500, "author_profile": "https://Stackoverflow.com/users/2373500", "pm_score": 3, "selected": false, "text": "<script type=\"text/javascript\">\nfunction closeWP() {\n var Browser = navigator.appName;\n var indexB = Browser.indexOf('Explorer');\n\n if (indexB > 0) {\n var indexV = navigator.userAgent.indexOf('MSIE') + 5;\n var Version = navigator.userAgent.substring(indexV, indexV + 1);\n\n if (Version >= 7) {\n window.open('', '_self', '');\n window.close();\n }\n else if (Version == 6) {\n window.opener = null;\n window.close();\n }\n else {\n window.opener = '';\n window.close();\n }\n\n }\nelse {\n window.close();\n }\n}\n</script>\n" }, { "answer_id": 26864113, "author": "Kamleshkumar Gujarathi", "author_id": 4239394, "author_profile": "https://Stackoverflow.com/users/4239394", "pm_score": 0, "selected": false, "text": "<script language=javascript>\nfunction CloseWindow() \n{\n window.open('', '_self', '');\n window.close();\n}\n</script>\n string myclosescript = \"<script language='javascript' type='text/javascript'>CloseWindow();</script>\";\n\nPage.ClientScript.RegisterStartupScript(GetType(), \"myclosescript\", myclosescript);\n OnClientClick=\"CloseWindow();\"\n" }, { "answer_id": 33018553, "author": "Logan Hasbrouck", "author_id": 3609893, "author_profile": "https://Stackoverflow.com/users/3609893", "pm_score": -1, "selected": false, "text": "<html>\n <head>\n </head>\n <body onload=\"window.close();\">\n </body>\n</html>\n onload=\"window.close();\"" }, { "answer_id": 35335816, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<script type=\"text/javascript\">\nfunction closeWindowNoPrompt()\n{\nwindow.open('', '_parent', '');\nwindow.close();\n}\n</script>\n" }, { "answer_id": 43452197, "author": "nurmurat", "author_id": 887620, "author_profile": "https://Stackoverflow.com/users/887620", "pm_score": 1, "selected": false, "text": "var PreventExitPop = true;\nfunction ExitPop() {\n if (PreventExitPop != false) {\n return \"Hold your horses! \\n\\nTake the time to reserve your place.Registrations might become paid or closed completely to newcomers!\"\n }\n}\nwindow.onbeforeunload = ExitPop;\n PreventExitPop = false\n" }, { "answer_id": 48854816, "author": "Mada Aryakusumah", "author_id": 1837643, "author_profile": "https://Stackoverflow.com/users/1837643", "pm_score": 3, "selected": false, "text": "window.open('', '_self', '').close();" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57854", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5440/" ]
57,855
<p>I'm troubleshooting a problem with creating Vista shortcuts.</p> <p>I want to make sure that our Installer is reading the Programs folder from the right registry key.</p> <p>It's reading it from:</p> <pre><code>HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders\Programs </code></pre> <p>And it's showing this directory for Programs:</p> <pre><code>C:\Users\NonAdmin2 UAC OFF\AppData\Roaming\Microsoft\Windows\Start Menu\Programs </code></pre> <p>From what I've read, this seems correct, but I wanted to double check.</p>
[ { "answer_id": 58261, "author": "Clay Nichols", "author_id": 4906, "author_profile": "https://Stackoverflow.com/users/4906", "pm_score": 0, "selected": false, "text": "public class Utilities\n{\n\n public enum FolderPaths\n {\n CSIDL_DESKTOP = 0x0000, // <desktop>\n CSIDL_INTERNET = 0x0001, // Internet Explorer (icon on desktop)\n CSIDL_PROGRAMS = 0x0002, // Start Menu\\Programs\n CSIDL_CONTROLS = 0x0003, // My Computer\\Control Panel\n CSIDL_PRINTERS = 0x0004, // My Computer\\Printers\n CSIDL_PERSONAL = 0x0005, // My Documents\n CSIDL_FAVORITES = 0x0006, // <user name>\\Favorites\n CSIDL_STARTUP = 0x0007, // Start Menu\\Programs\\Startup\n CSIDL_RECENT = 0x0008, // <user name>\\Recent\n CSIDL_SENDTO = 0x0009, // <user name>\\SendTo\n CSIDL_BITBUCKET = 0x000a, // <desktop>\\Recycle Bin\n CSIDL_STARTMENU = 0x000b, // <user name>\\Start Menu\n CSIDL_MYDOCUMENTS = CSIDL_PERSONAL, // Personal was just a silly name for My Documents\n CSIDL_MYMUSIC = 0x000d, // \"My Music\" folder\n CSIDL_MYVIDEO = 0x000e, // \"My Videos\" folder\n CSIDL_DESKTOPDIRECTORY = 0x0010, // <user name>\\Desktop\n CSIDL_DRIVES = 0x0011, // My Computer\n CSIDL_NETWORK = 0x0012, // Network Neighborhood (My Network Places)\n CSIDL_NETHOOD = 0x0013, // <user name>\\nethood\n CSIDL_FONTS = 0x0014, // windows\\fonts\n CSIDL_TEMPLATES = 0x0015,\n CSIDL_COMMON_STARTMENU = 0x0016, // All Users\\Start Menu\n CSIDL_COMMON_PROGRAMS = 0X0017, // All Users\\Start Menu\\Programs\n CSIDL_COMMON_STARTUP = 0x0018, // All Users\\Startup\n CSIDL_COMMON_DESKTOPDIRECTORY = 0x0019, // All Users\\Desktop\n CSIDL_APPDATA = 0x001a, // <user name>\\Application Data\n CSIDL_PRINTHOOD = 0x001b, // <user name>\\PrintHood\n CSIDL_LOCAL_APPDATA = 0x001c // <user name>\\Local Settings\\Applicaiton Data (non roaming)\n }\n\n\n [DllImport(\"shfolder.dll\", CharSet = CharSet.Unicode)]\n public static extern int SHGetFolderPath(IntPtr owner, int folder, IntPtr token, int flags, StringBuilder path);\n}\n\nvoid MyFunction()\n{\n StringBuilder path = new StringBuilder(260);\n\n String folderPath = \"\";\n if (0 == Utilities.SHGetFolderPath(IntPtr.Zero, (int) Utilities.FolderPaths.CSIDL_MYVIDEO, IntPtr.Zero, 0, path))\n {\n folderPath = path.ToString();\n }\n\n}\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57855", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4906/" ]
57,859
<p>The ReSharper reformat code feature is very handy and flexible, particularly with the new code layout templating flexibility JetBrains have added in version 3.0.</p> <p>Is there a standard set of code style settings for ReSharper which match the rules enforced by <a href="http://code.msdn.microsoft.com/sourceanalysis" rel="noreferrer">Microsoft StyleCop</a>, so that StyleCop compliance can be as easy as running the ReSharper "reformat code" feature?</p>
[ { "answer_id": 271495, "author": "KeesDijk", "author_id": 6434, "author_profile": "https://Stackoverflow.com/users/6434", "pm_score": 2, "selected": false, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Patterns xmlns=\"urn:shemas-jetbrains-com:member-reordering-patterns\">\n\n <!--Do not reorder COM interfaces and structs marked by \n StructLayout attribute-->\n <Pattern>\n <Match>\n <Or Weight=\"100\">\n <And>\n <Kind Is=\"interface\"/>\n <HasAttribute CLRName=\"System.Runtime.InteropServices.InterfaceTypeAttribute\"/>\n </And>\n <HasAttribute CLRName=\"System.Runtime.InteropServices.StructLayoutAttribute\"/>\n </Or>\n </Match>\n </Pattern>\n\n <!--Special formatting of NUnit test fixture-->\n <Pattern RemoveAllRegions=\"true\">\n <Match>\n <And Weight=\"100\">\n <Kind Is=\"class\"/>\n <HasAttribute CLRName=\"NUnit.Framework.TestFixtureAttribute\" \n Inherit=\"true\"/>\n </And>\n </Match>\n\n <!--Setup/Teardow-->\n <Entry>\n <Match>\n <And>\n <Kind Is=\"method\"/>\n <Or>\n <HasAttribute CLRName=\"NUnit.Framework.SetUpAttribute\" \n Inherit=\"true\"/>\n <HasAttribute CLRName=\"NUnit.Framework.TearDownAttribute\" \n Inherit=\"true\"/>\n <HasAttribute CLRName=\"NUnit.Framework.FixtureSetUpAttribute\" \n Inherit=\"true\"/>\n <HasAttribute CLRName=\"NUnit.Framework.FixtureTearDownAttribute\" \n Inherit=\"true\"/>\n </Or>\n </And>\n </Match>\n <Group Region=\"Setup/Teardown\"/>\n </Entry>\n\n <!--All other members-->\n <Entry/>\n\n <!--Test methods-->\n <Entry>\n <Match>\n <And Weight=\"100\">\n <Kind Is=\"method\"/>\n <HasAttribute CLRName=\"NUnit.Framework.TestAttribute\" \n Inherit=\"false\"/>\n </And>\n </Match>\n <Sort>\n <Name/>\n </Sort>\n </Entry>\n </Pattern>\n\n <!--Default pattern-->\n <Pattern>\n <!--public delegate-->\n <Entry>\n <Match>\n <And Weight=\"100\">\n <Access Is=\"public\"/>\n <Kind Is=\"delegate\"/>\n </And>\n </Match>\n <Sort>\n <Name/>\n </Sort>\n <Group Region=\"Delegates\"/>\n </Entry>\n\n <!--public enum-->\n <Entry>\n <Match>\n <And Weight=\"100\">\n <Access Is=\"public\"/>\n <Kind Is=\"enum\"/>\n </And>\n </Match>\n <Sort>\n <Name/>\n </Sort>\n <Group>\n <Name Region=\"${Name} enum\"/>\n </Group>\n </Entry>\n\n <!--fields and constants-->\n <Entry>\n <Match>\n <Or>\n <Kind Is=\"constant\"/>\n <Kind Is=\"field\"/>\n </Or>\n </Match>\n <Sort>\n <Kind Order=\"constant field\"/>\n <Readonly/>\n <Static/>\n <Name/>\n </Sort>\n <Group Region=\"Fields\"/>\n </Entry>\n\n <!-- Events-->\n <Entry>\n <Match>\n <Kind Is=\"event\"/>\n </Match>\n <Sort>\n <Name/>\n </Sort>\n <Group Region=\"Events\"/>\n </Entry>\n\n <!--Constructors. Place static one first-->\n <Entry>\n <Match>\n <Kind Is=\"constructor\"/>\n </Match>\n <Sort>\n <Static/>\n </Sort>\n <Group Region=\"Constructors\"/>\n </Entry>\n\n <!--properties, indexers-->\n <Entry>\n <Match>\n <Or>\n <Kind Is=\"property\"/>\n <Kind Is=\"indexer\"/>\n </Or>\n </Match>\n <Sort>\n <Name/>\n </Sort>\n <Group Region=\"Properties\"/>\n </Entry>\n\n <!--interface implementations-->\n <Entry>\n <Match>\n <And Weight=\"100\">\n <Kind Is=\"member\"/>\n <ImplementsInterface/>\n </And>\n </Match>\n <Sort>\n <ImplementsInterface Immediate=\"true\"/>\n <Kind Order=\"property\"/>\n <Name/>\n </Sort>\n <Group>\n <ImplementsInterface Immediate=\"true\" \n Region=\"${ImplementsInterface} Members\"/>\n </Group>\n </Entry>\n\n <!-- public Methods -->\n <Entry>\n <Match>\n <And>\n <Kind Is=\"method\"/>\n <Access Is=\"public\"/>\n </And>\n </Match>\n <Sort>\n <Static/>\n <Name/>\n </Sort>\n <Group>\n </Group>\n </Entry>\n\n <!-- internal Methods -->\n <Entry>\n <Match>\n <And>\n <Kind Is=\"method\"/>\n <Access Is=\"internal\"/>\n </And>\n </Match>\n <Sort>\n <Static/>\n <Name/>\n </Sort>\n <Group>\n </Group>\n </Entry>\n\n <!--protected internal Methods -->\n <Entry>\n <Match>\n <And>\n <Kind Is=\"method\"/>\n <Access Is=\"protected-internal\"/>\n </And>\n </Match>\n <Sort>\n <Static/>\n <Name/>\n </Sort>\n <Group>\n </Group>\n </Entry>\n\n\n <!-- protected Methods -->\n <Entry>\n <Match>\n <And>\n <Kind Is=\"method\"/>\n <Access Is=\"protected\"/>\n </And>\n </Match>\n <Sort>\n <Static/>\n <Name/>\n </Sort>\n <Group>\n </Group>\n </Entry>\n\n <!-- private Methods -->\n <Entry>\n <Match>\n <And>\n <Kind Is=\"method\"/>\n <Access Is=\"private\"/>\n </And>\n </Match>\n <Sort>\n <Static/>\n <Name/>\n </Sort>\n <Group>\n </Group>\n </Entry>\n\n <!--all other members-->\n <Entry/>\n\n <!--nested types-->\n <Entry>\n <Match>\n <Kind Is=\"type\"/>\n </Match>\n <Sort>\n <Name/>\n </Sort>\n <Group>\n <Name Region=\"Nested type: ${Name}\"/>\n </Group>\n </Entry>\n </Pattern>\n</Patterns>\n<!--\nI. Overall\n\nI.1 Each pattern can have <Match>....</Match> element. For the given type \n declaration, the pattern with the match, evaluated to 'true' with the \n largest weight, will be used \nI.2 Each pattern consists of the sequence of <Entry>...</Entry> elements. \n Type member declarations are distributed between entries\nI.3 If pattern has RemoveAllRegions=\"true\" attribute, then all regions \n will be cleared prior to reordering. Otherwise, only auto-generated \n regions will be cleared\nI.4 The contents of each entry is sorted by given keys (First key is \n primary, next key is secondary, etc). Then the declarations are \n grouped and en-regioned by given property\n\nII. Available match operands\n\nEach operand may have Weight=\"...\" attribute. This weight will be added \nto the match weight if the operand is evaluated to 'true'.The default \nweight is 1\n\nII.1 Boolean functions:\nII.1.1 <And>....</And>\nII.1.2 <Or>....</Or>\nII.1.3 <Not>....</Not>\n\nII.2 Operands\nII.2.1 <Kind Is=\"...\"/>. Kinds are: class, struct, interface, enum, \n delegate, type, constructor, destructor, property, indexer, method, \n operator, field, constant, event, member\nII.2.2 <Name Is=\"...\" [IgnoreCase=\"true/false\"] />. The 'Is' attribute \n contains regular expression\nII.2.3 <HasAttribute CLRName=\"...\" [Inherit=\"true/false\"] />. The 'CLRName'\n attribute contains regular expression\nII.2.4 <Access Is=\"...\"/>. The 'Is' values are: public, protected, internal,\n protected internal, private\nII.2.5 <Static/>\nII.2.6 <Abstract/>\nII.2.7 <Virtual/>\nII.2.8 <Override/>\nII.2.9 <Sealed/>\nII.2.10 <Readonly/>\nII.2.11 <ImplementsInterface CLRName=\"...\"/>. The 'CLRName' attribute \n contains regular expression\nII.2.12 <HandlesEvent />\n-->\n // <copyright file=\"$FileName$\" company=\"$Company$\">\n// Copyright (c) 2008 All Right Reserved\n// </copyright>\n// <author>$author$</author>\n// <email>$email$</email>\n// <date>$date$</date>\n// <summary>$summary$</summary>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5975/" ]
57,878
<p>If I create an index on columns (A, B, C), in that order, my understanding is that the database will be able to use it even if I search only on (A), or (A and B), or (A and B and C), but not if I search only on (B), or (C), or (B and C). Is this correct?</p>
[ { "answer_id": 59370, "author": "Ethan Post", "author_id": 4527, "author_profile": "https://Stackoverflow.com/users/4527", "pm_score": 3, "selected": false, "text": "create table mytab nologging as (\nselect mod(rownum, 3) x, rownum y, mod(rownum, 3) z from all_objects, (select 'x' from user_tables where rownum < 4)\n);\n\ncreate index i on mytab (x, y, z);\n\nexec dbms_stats.gather_table_stats(ownname=>'DBADMIN',tabname=>'MYTAB', cascade=>true);\n\nset autot trace exp\n\nselect * from mytab where y=5000;\n\nExecution Plan\n----------------------------------------------------------\n 0 SELECT STATEMENT Optimizer=CHOOSE (Cost=1 Card=1 Bytes=10)\n 1 0 INDEX (SKIP SCAN) OF 'I' (INDEX) (Cost=1 Card=1 Bytes=10)\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5295/" ]
57,910
<p>Grails scaffolding defaults to 10 rows per page. I would like to increase that number without generating the views and changing the 10 in every file. Where do I change the default?</p>
[ { "answer_id": 58239, "author": "codeLes", "author_id": 3030, "author_profile": "https://Stackoverflow.com/users/3030", "pm_score": 1, "selected": false, "text": "class PersonController {\n def scaffold = true\n\n def list = {\n if(!params.max) params.max = 20\n [ personList: Person.list( params ) ]\n }\n}\n" }, { "answer_id": 22386190, "author": "Juan Giménez", "author_id": 1370706, "author_profile": "https://Stackoverflow.com/users/1370706", "pm_score": 0, "selected": false, "text": "?max=<num_rows_desired>\n http://projecthost:8080/Library/Books/list?max=20\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57910", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
57,918
<p>We have a whole bunch of queries that "search" for clients, customers, etc. You can search by first name, email, etc. We're using LIKE statements in the following manner: </p> <pre><code>SELECT * FROM customer WHERE fname LIKE '%someName%' </code></pre> <p>Does full-text indexing help in the scenario? We're using SQL Server 2005.</p>
[ { "answer_id": 58176, "author": "Josef", "author_id": 5581, "author_profile": "https://Stackoverflow.com/users/5581", "pm_score": 5, "selected": false, "text": "LIKE LIKE % CONTAINS FREETEXT LIKE" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57918", "https://Stackoverflow.com", "https://Stackoverflow.com/users/781/" ]
57,919
<p>I'm working on a Windows Forms (.NET 3.5) application that has a built-in exception handler to catch any (heaven forbid) exceptions that may arise. I'd like the exception handler to be able to prompt the user to click a <kbd>Send Error Report</kbd> button, which would then cause the app to send an email to my FogBugz email address.</p> <p>What's the best way to do this, and are there any "gotchas" to watch out for?</p>
[ { "answer_id": 58023, "author": "Dr8k", "author_id": 6014, "author_profile": "https://Stackoverflow.com/users/6014", "pm_score": 3, "selected": false, "text": "<system.net>\n <mailSettings>\n <smtp deliveryMethod=\"Network\" from=\"[email protected]\">\n <network host=\"smtp.somewhere.com.au\" />\n </smtp>\n </mailSettings>\n</system.net>\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57919", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5473/" ]
57,923
<p>I've been writing C / C++ code for almost twenty years, and I know Perl, Python, PHP, and some Java as well, and I'm teaching myself JavaScript. But I've never done any .NET, VB, or C# stuff. What exactly does <strong>managed</strong> code mean?</p> <p>Wikipedia <a href="http://en.wikipedia.org/wiki/Managed_code" rel="noreferrer">describes it</a> simply as</p> <blockquote> <p>Code that executes under the management of a virtual machine</p> </blockquote> <p>and it specifically says that Java is (usually) managed code, so</p> <ul> <li><strong>why does the term only seem to apply to C# / .NET?</strong></li> <li><strong>Can you compile C# into a .exe that contains the VM as well, or do you have to package it up and give it to another .exe (a la java)?</strong></li> </ul> <p>In a similar vein,</p> <ul> <li><strong>is .NET a <em>language</em> or a <em>framework</em>, and what exactly does "framework" mean here?</strong></li> </ul> <p>OK, so that's more than one question, but for someone who's been in the industry as long as I have, I'm feeling rather N00B-ish right now...</p>
[ { "answer_id": 108137, "author": "Josh Smeaton", "author_id": 10583, "author_profile": "https://Stackoverflow.com/users/10583", "pm_score": 3, "selected": false, "text": "class Bar : public Foo {\n private:\n int fubar;\n public:\n Bar(int i) : fubar(i) {}\n int * getFubar() { return * fubar; }\n}\n public ref class Bar : public Foo\n private:\n int fubar;\n public:\n Bar(int i) : fubar(i) {}\n int ^ getFubar() { return ^ fubar; }\n}\n" }, { "answer_id": 108182, "author": "HTTP 410", "author_id": 13118, "author_profile": "https://Stackoverflow.com/users/13118", "pm_score": 2, "selected": false, "text": "o The .NET Framework Class Library (FCL).\no The FCL provides a rich set of high-level functionality for developers.\n o Common Language Runtime (CLR) executes Common Intermediate Language (CIL).\no The CLR is God: it runs, controls, and polices everything.\n o Every development language is compiled to CIL, which is run by the CLR.\no C# and VB are the two main development languages.\n" }, { "answer_id": 108189, "author": "Keith Elder", "author_id": 10624, "author_profile": "https://Stackoverflow.com/users/10624", "pm_score": 4, "selected": false, "text": "using System;\nclass Program\n {\n static void Main(string[] args)\n {\n Console.WriteLine(\"hello world\");\n }\n }\n [HostProtection(SecurityAction.LinkDemand, UI=true)]\npublic static void WriteLine(string value)\n{\n Out.WriteLine(value);\n}\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57923", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1821/" ]
57,927
<p>I have an excel spreadsheet in a format similar to the following...</p> <pre><code>| NAME | CLUB | STATUS | SCORE | | Fred | a | Gent | 145 | | Bert | a | Gent | 150 | | Harry | a | Gent | 195 | | Jim | a | Gent | 150 | | Clare | a | Lady | 99 | | Simon | a | Junior | 130 | | John | b | Junior | 130 | : : | Henry | z | Gent | 200 | </code></pre> <p>I need to convert this table into a list of the "Top Ten" teams. The rules are</p> <ul> <li>Each team score is taken from the sum of four members of that club.</li> <li>These totals should be of the best four scores except... <ul> <li>Each team must consist of at least one Junior or Lady</li> </ul></li> </ul> <p>For example in the table above the team score for club A would be 625 <strong>not</strong> 640 as you would take the scores for Harry(190), Bert(150), Jim(150), and Simon(130). You could not take Fred's(145) score as that would give you only Gents.</p> <p>My question is, can this be done easily as a series of Excel formula, or will I need to resort to using something more procedural?</p> <p>Ideally the solution needs to be automatic in the team selections, I don't want to have to create separate hand crafted formula for each team. I also will not necessarily have a neatly ordered list of each clubs members. Although I could probably generate the list via an extra calculation sheet.</p>
[ { "answer_id": 60187, "author": "Dick Kusleika", "author_id": 4280, "author_profile": "https://Stackoverflow.com/users/4280", "pm_score": 3, "selected": true, "text": "Public Function TopTen(Club As String, Scores As Range)\n\n Dim i As Long\n Dim vaScores As Variant\n Dim bLady As Boolean\n Dim lCnt As Long\n Dim lTotal As Long\n\n vaScores = FilterOnClub(Scores.Value, Club)\n vaScores = SortOnScore(vaScores)\n\n For i = LBound(vaScores, 2) To UBound(vaScores, 2)\n If lCnt = 3 And Not bLady Then\n If vaScores(3, i) <> \"Gent\" Then\n lTotal = lTotal + vaScores(4, i)\n bLady = True\n lCnt = lCnt + 1\n End If\n Else\n lTotal = lTotal + vaScores(4, i)\n lCnt = lCnt + 1\n If vaScores(3, i) <> \"Gent\" Then bLady = True\n End If\n\n If lCnt = 4 Then Exit For\n Next i\n\n TopTen = lTotal\n\nEnd Function\n\nPrivate Function FilterOnClub(vaScores As Variant, sClub As String) As Variant\n\n Dim i As Long, j As Long\n Dim aTemp() As Variant\n\n For i = LBound(vaScores, 1) To UBound(vaScores, 1)\n If vaScores(i, 2) = sClub Then\n j = j + 1\n ReDim Preserve aTemp(1 To 4, 1 To j)\n aTemp(1, j) = vaScores(i, 1)\n aTemp(2, j) = vaScores(i, 2)\n aTemp(3, j) = vaScores(i, 3)\n aTemp(4, j) = vaScores(i, 4)\n End If\n Next i\n\n FilterOnClub = aTemp\n\nEnd Function\n\nPrivate Function SortOnScore(vaScores As Variant) As Variant\n\n Dim i As Long, j As Long, k As Long\n Dim aTemp(1 To 4) As Variant\n\n For i = 1 To UBound(vaScores, 2) - 1\n For j = i To UBound(vaScores, 2)\n If vaScores(4, i) < vaScores(4, j) Then\n For k = 1 To 4\n aTemp(k) = vaScores(k, j)\n vaScores(k, j) = vaScores(k, i)\n vaScores(k, i) = aTemp(k)\n Next k\n End If\n Next j\n Next i\n\n SortOnScore = vaScores\n\nEnd Function\n =TopTen(H2,$B$2:$E$30) H2" }, { "answer_id": 62187, "author": "Mike Woodhouse", "author_id": 1060, "author_profile": "https://Stackoverflow.com/users/1060", "pm_score": 2, "selected": false, "text": "\n A B C D\n 1 NAME CLUB STATUS SCORE\n 2 Kevin a Gent 145\n 3 Lyle a Gent 150\n 4 Martin a Gent 195\n 5 Norm a Gent 150\n 6 Oonagh a Lady 100\n 7 Arthur b Gent 200\n 8 Brian b Gent 210\n 9 Charlie b Gent 190\n10 Donald b Gent 220\n11 Eddie b Junior 150\n12 Quentin c Gent 145\n13 Ryan c Gent 150\n14 Sheila c Lady 195\n15 Trevor c Gent 150\n16 Ursula c Junior 200\n {=LARGE(IF(B2:B16=\"a\",D2:D16,0),1)}\n {=LARGE(IF($B$2:$B$16=$J3,IF($C$2:$C$16=\"Lady\",$D$2:$D$16,0),0),1)}\n \n J K L M N O P\n 1 Club 1 2 3 4 Lady Junior\n 2 a 195 150 150 145 100 0\n =SUM(K2:M2)+MIN(MAX(O2,P2),N2)\n {=LARGE(IF($B$2:$B$16=$J3,$D$2:$D$16,0),1)+\nLARGE(IF($B$2:$B$16=$J3,$D$2:$D$16,0),2)+\nLARGE(IF($B$2:$B$16=$J3,$D$2:$D$16,0),3)+\nMIN(LARGE(IF($B$2:$B$16=$J3,$D$2:$D$16,0),4),\nMAX(LARGE(IF($B$2:$B$18=$J3,IF($C$2:$C$18=\"Lady\",$D$2:$D$18,0),0),1),\nLARGE(IF($B$2:$B$18=$J3,IF($C$2:$C$18=\"Junior\",$D$2:$D$18,0),0),1)))}\n \n Anyone Lady Junior \nClub 1 2 3 4 1 1 Total \na 195 150 150 145 100 0 595 \nb 220 210 200 190 0 150 780 \nc 200 195 150 150 195 200 695 \n \n A B C D E F G H \n1 club Sc Rank UniqRk Pos Club Score\n2 third-equal#1 80 3 79.999980 1 1 best 100 \n3 second 90 2 89.999970 2 2 second 90 \n4 third-equal#2 80 3 79.999960 3 3 third-equal#1 80 \n5 best 100 1 99.999950 4 3 third-equal#2 80 \n6 worst 70 5 69.999940 5 5 worst 70 \n\n C: =RANK(B2,$B$2:$B$6) # what it says, with ties both getting the lower number\nD: =B2-ROW()*0.00001 # score, modified slightly to ensure uniqueness\nF: =SMALL($C$2:$C$6,E2) # first output column, ranks including ties\nG: =INDEX($A$2:$A$6,MATCH(LARGE($D$2:$D$6,E2),$D$2:$D$6,0))\n # club name for position, using the modified score in D\nH: =INDEX($B$2:$B$6,MATCH(LARGE($D$2:$D$6,E2),$D$2:$D$6,0))\n # as G, but indexes into scores\n" }, { "answer_id": 7410198, "author": "drew", "author_id": 943658, "author_profile": "https://Stackoverflow.com/users/943658", "pm_score": 1, "selected": false, "text": "=If(a1=N,b1,0) A1 N B1 N $C$1 largeifs" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57927", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3720/" ]
57,947
<p>I'm really confused by the various configuration options for .Net configuration of dll's, ASP.net websites etc in .Net v2 - especially when considering the impact of a config file at the UI / end-user end of the chain.</p> <p>So, for example, some of the applications I work with use settings which we access with:</p> <pre><code>string blah = AppLib.Properties.Settings.Default.TemplatePath; </code></pre> <p>Now, this option seems cool because the members are stongly typed, and I won't be able to type in a property name that doesn't exist in the Visual Studio 2005 IDE. We end up with lines like this in the App.Config of a command-line executable project:</p> <pre><code>&lt;connectionStrings&gt; &lt;add name="AppConnectionString" connectionString="XXXX" /&gt; &lt;add name="AppLib.Properties.Settings.AppConnectionString" connectionString="XXXX" /&gt; &lt;/connectionStrings&gt; </code></pre> <p>(If we don't have the second setting, someone releasing a debug dll to the live box could have built with the debug connection string embedded in it - eek)</p> <p>We also have settings accessed like this:</p> <pre><code>string blah = System.Configuration.ConfigurationManager.AppSettings["TemplatePath_PDF"]; </code></pre> <p>Now, these seem cool because we can access the setting from the dll code, or the exe / aspx code, and all we need in the Web or App.config is:</p> <pre><code>&lt;appSettings&gt; &lt;add key="TemplatePath_PDF" value="xxx"/&gt; &lt;/appSettings&gt; </code></pre> <p>However, the value of course may not be set in the config files, or the string name may be mistyped, and so we have a different set of problems.</p> <p>So... if my understanding is correct, the former methods give strong typing but bad sharing of values between the dll and other projects. The latter provides better sharing, but weaker typing.</p> <p>I feel like I must be missing something. For the moment, I'm not even concerned with the application being able to write-back values to the configuration files, encryption or anything like that. Also, I had decided that the best way to store any non-connection strings was in the DB... and then the very next thing that I have to do is store phone numbers to text people in case of DB connection issues, so they must be stored outside the DB!</p>
[ { "answer_id": 57980, "author": "Rob Gray", "author_id": 5691, "author_profile": "https://Stackoverflow.com/users/5691", "pm_score": 2, "selected": false, "text": "string phoneNum = Properties.Settings.Default.EmergencyPhoneNumber;\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57947", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6004/" ]
57,958
<p>I like HtmlControls because there is no HTML magic going on... the asp source looks similar to what the client sees. </p> <p>I can't argue with the utility of GridView, Repeater, CheckBoxLists, etc, so I use them when I need that functionality. </p> <p>Also, it looks weird to have code that mixes and matches:</p> <pre><code>&lt;asp:Button id='btnOK' runat='server' Text='OK' /&gt; &lt;input id='btnCancel' runat='server' type='button' value='Cancel' /&gt; </code></pre> <p>(The above case in the event you wanted to bind a server-side event listener to OK but Cancel just runs a javascript that hides the current div)</p> <p>Is there some definitive style guide out there? Should HtmlControls just be avoided? </p>
[ { "answer_id": 57961, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 1, "selected": false, "text": "<input id='btnCancel' type='button' value='Cancel' />\n" }, { "answer_id": 57986, "author": "Tyler", "author_id": 5642, "author_profile": "https://Stackoverflow.com/users/5642", "pm_score": 4, "selected": true, "text": "<input id='btnCancel' runat='server' type='button' value='Cancel' />\n <asp:Button id='btnCancel' runat='server' Text='Cancel' />\n" } ]
2008/09/11
[ "https://Stackoverflow.com/questions/57958", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4435/" ]
57,987
<p>Does anyone know how to write to an excel file (.xls) via OLEDB in C#? I'm doing the following:</p> <pre><code> OleDbCommand dbCmd = new OleDbCommand("CREATE TABLE [test$] (...)", connection); dbCmd.CommandTimeout = mTimeout; results = dbCmd.ExecuteNonQuery(); </code></pre> <p>But I get an OleDbException thrown with message:</p> <blockquote> <p>"Cannot modify the design of table 'test$'. It is in a read-only database."</p> </blockquote> <p>My connection seems fine and I can select data fine but I can't seem to insert data into the excel file, does anyone know how I get read/write access to the excel file via OLEDB?</p>
[ { "answer_id": 184213, "author": "Zorantula", "author_id": 18108, "author_profile": "https://Stackoverflow.com/users/18108", "pm_score": 4, "selected": true, "text": "ReadOnly=False; Provider=Microsoft.Jet.OLEDB.4.0;Data Source=fifa_ng_db.xls;Mode=ReadWrite;ReadOnly=false;Extended Properties=\\\"Excel 8.0;HDR=Yes;IMEX=1\\\";\n" }, { "answer_id": 184271, "author": "Duncan Smart", "author_id": 1278, "author_profile": "https://Stackoverflow.com/users/1278", "pm_score": 0, "selected": false, "text": "Response.Write(Environment.UserDomainName + \"\\\\\" + Environment.UserName);\n" }, { "answer_id": 781193, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "ReadOnly=false IMEX=1 IMEX=1 CREATE TABLE DROP TABLE \"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=workbook.xls;Mode=ReadWrite;Extended Properties=\\\"Excel 8.0;HDR=Yes;\\\";\"\n" }, { "answer_id": 976623, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "Provider=Microsoft.Jet.OLEDB.4.0;Mode=ReadWrite;Extended Properties='Excel 8.0;HDR=Yes;';Data Source=\" + {path to file}; IMEX=1 ReadOnly=false" }, { "answer_id": 6947980, "author": "Erwin Aarnoudse", "author_id": 879400, "author_profile": "https://Stackoverflow.com/users/879400", "pm_score": 2, "selected": false, "text": "IMEX=1" } ]
2008/09/12
[ "https://Stackoverflow.com/questions/57987", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39040/" ]
57,990
<p>After attending a recent Alt.NET group on IoC, I got to thinking about the tools available and how they might work. <code>StructureMap</code> in particular uses both attributes and bootstrapper concepts to map requests for <code>IThing</code> to <code>ConcreteThing</code>. Attributes automatically throw up flags for me that either reflection or IL injection is going on. Does anyone know exactly how this works (for <code>StructureMap</code> or other IoC tools) and what the associated overhead might be either at run-time or compile-time?</p>
[ { "answer_id": 184830, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "IRepository _repository = ObjectFactory.BuildFactory<IRepository>();\n" } ]
2008/09/12
[ "https://Stackoverflow.com/questions/57990", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4541/" ]
57,999
<p>I'm just looking for a simple, concise explanation of the difference between these two. MSDN doesn't go into a hell of a lot of detail here.</p>
[ { "answer_id": 58026, "author": "rpetrich", "author_id": 4007, "author_profile": "https://Stackoverflow.com/users/4007", "pm_score": 7, "selected": true, "text": "__declspec(dllexport) __declspec(dllimport)" }, { "answer_id": 58031, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 7, "selected": false, "text": "__declspec( dllexport ) __declspec( dllimport ) dllimport" } ]
2008/09/12
[ "https://Stackoverflow.com/questions/57999", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3146/" ]
58,000
<p>We have a recurring problem at my company with build breaks in our Flex projects. The problem primarily occurs because the build that the developers do on their local machines is fundamentally different from the build that occurs on the build machine. The devs are building the projects using <code>FlexBuilder/eclipse</code> and the build machine is using the command line compilers. Inevitably, the <code>{projectname}-config.xml</code> and/or the batch file that runs the build get out of sync with the project files used by eclipse, so the the build succeeds on the dev's machine, but fails on the build machine.</p> <p>We started down the path of writing a utility program to convert FlexBuilder's project files into a <code>{projectname}-config.xml</code> file, but it's a) undocumented and b) a horrible hack.</p> <p>I've looked into the -dump-config switch to get the config files, but this has a couple of problems: 1) The generated config file has absolute paths which doesn't work in our environment (some developers use macs, some windows machines), and 2) only works right when run from the IDE, so can't be build into the build process.</p> <p>Tomorrow, we are going to discuss a couple of options, neither of which I'm terribly fond of:</p> <p><strong>a)</strong> Add a post check-in event to Subversion to remove these absolute references, or <br> <strong>b)</strong> add a pre-build process that removes the absolute reference.</p> <p>I can't believe that we are the first group of developers to run across this issue, but I can't find any good solutions on Google. How have other groups dealt with this problem?</p>
[ { "answer_id": 58026, "author": "rpetrich", "author_id": 4007, "author_profile": "https://Stackoverflow.com/users/4007", "pm_score": 7, "selected": true, "text": "__declspec(dllexport) __declspec(dllimport)" }, { "answer_id": 58031, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 7, "selected": false, "text": "__declspec( dllexport ) __declspec( dllimport ) dllimport" } ]
2008/09/12
[ "https://Stackoverflow.com/questions/58000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1946325/" ]
58,024
<p>I'm trying to provide a link to my company's website from a Windows Form. I want to be well behaved and launch using the user's preferred browser.</p> <p>What is the best way to open a URL in the user's default browser from a Windows Forms application?</p>
[ { "answer_id": 58032, "author": "Aaron Wagner", "author_id": 3909, "author_profile": "https://Stackoverflow.com/users/3909", "pm_score": 5, "selected": false, "text": "using System.Diagnostics;\n\nProcess.Start(\"http://www.google.com/\");\n" }, { "answer_id": 58033, "author": "Blorgbeard", "author_id": 369, "author_profile": "https://Stackoverflow.com/users/369", "pm_score": 8, "selected": true, "text": "ProcessStartInfo sInfo = new ProcessStartInfo(\"http://mysite.com/\"); \nProcess.Start(sInfo);\n" }, { "answer_id": 12674404, "author": "ammrin", "author_id": 1711898, "author_profile": "https://Stackoverflow.com/users/1711898", "pm_score": -1, "selected": false, "text": "Process mypr;\nmypr = Process.Start(\"iexplore.exe\", \"pass the name of website\");\n" }, { "answer_id": 18276042, "author": "Rogala", "author_id": 2025711, "author_profile": "https://Stackoverflow.com/users/2025711", "pm_score": 4, "selected": false, "text": "Dim sInfo As New ProcessStartInfo(\"http://www.mysite.com\")\n\nTry\n Process.Start(sInfo)\nCatch ex As Exception\n Process.Start(\"iexplore.exe\", sInfo.FileName)\nEnd Try\n" }, { "answer_id": 62534375, "author": "Daniel", "author_id": 13761054, "author_profile": "https://Stackoverflow.com/users/13761054", "pm_score": 4, "selected": false, "text": "ProcessStartInfo psInfo = new ProcessStartInfo\n{\n FileName = \"https://www.google.com\",\n UseShellExecute = true\n};\nProcess.Start(psInfo);\n" } ]
2008/09/12
[ "https://Stackoverflow.com/questions/58024", "https://Stackoverflow.com", "https://Stackoverflow.com/users/148/" ]
58,054
<p>I have a list of bean objects passed into my JSP page, and one of them is a comment field. This field may contain newlines, and I want to replace them with semicolons using JSTL, so that the field can be displayed in a text input. I have found one solution, but it's not very elegant. I'll post below as a possibility.</p>
[ { "answer_id": 58060, "author": "parkerfath", "author_id": 6027, "author_profile": "https://Stackoverflow.com/users/6027", "pm_score": 7, "selected": true, "text": "<%@ taglib prefix=\"fn\" uri=\"http://java.sun.com/jsp/jstl/functions\" %>\n<% pageContext.setAttribute(\"newLineChar\", \"\\n\"); %>\n\n${fn:replace(item.comments, newLineChar, \"; \")}\n" }, { "answer_id": 58105, "author": "Walter Rumsby", "author_id": 1654, "author_profile": "https://Stackoverflow.com/users/1654", "pm_score": 0, "selected": false, "text": "<%@ taglib prefix=\"ns\" uri=\"...\" %>\n...\n${ns:replace(data)}\n ns replace" }, { "answer_id": 58109, "author": "Geekygecko", "author_id": 6009, "author_profile": "https://Stackoverflow.com/users/6009", "pm_score": 2, "selected": false, "text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<taglib version=\"2.0\" xmlns=\"http://java.sun.com/xml/ns/j2ee\" \n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \n xsi:schemaLocation=\"http://java.sun.com/xml/ns/j2ee web-jsptaglibrary_2_0.xsd\">\n <tlib-version>1.0</tlib-version>\n <short-name>sf</short-name>\n <uri>http://www.stackoverflow.com</uri>\n <function>\n <name>clean</name>\n <function-class>com.stackoverflow.web.tag.function.TagUtils</function-class>\n <function-signature>\n java.lang.String clean(java.lang.String)\n </function-signature>\n </function>\n</taglib>\n package com.stackoverflow.web.tag.function;\n\nimport javax.servlet.jsp.tagext.TagSupport;\n\npublic class TagUtils extends TagSupport {\n public static String clean(String comment) {\n return comment.replaceAll(\"\\n\", \"; \");\n }\n}\n <%@ taglib prefix=\"sf\" uri=\"http://www.stackoverflow.com\"%>\n${sf:clean(item.comments)}\n" }, { "answer_id": 733909, "author": "bousch", "author_id": 89037, "author_profile": "https://Stackoverflow.com/users/89037", "pm_score": 3, "selected": false, "text": "<c:set> <%@ taglib prefix=\"c\" uri=\"http://java.sun.com/jsp/jstl/core\" %>\n<%@ taglib prefix=\"fn\" uri=\"http://java.sun.com/jsp/jstl/functions\" %>\n\n<c:set var=\"newLine\" value=\"\\n\"/>\n${fn:replace(data, newLine, \"; \")}\n ${fn:replace(data, \"\\n\", \";\")}" }, { "answer_id": 920681, "author": "Matt", "author_id": 113719, "author_profile": "https://Stackoverflow.com/users/113719", "pm_score": 2, "selected": false, "text": "pageContext fn:replace <%@ taglib prefix=\"str\" uri=\"http://jakarta.apache.org/taglibs/string-1.1\" %>\n...\n<str:replace var=\"result\" replace=\"~n\" with=\";\" newlineToken=\"~n\">\nText containing newlines\n</str:replace>\n...\n" }, { "answer_id": 1690888, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<c:set var=\"newline\" value=\"\\n\"/>\n${fn:replace(data, newLine, \"; \")}\n <% pageContext.setAttribute(\"newLineChar\", \"\\n\"); %> \n${fn:replace(item.comments, newLineChar, \"; \")}\n" }, { "answer_id": 1690942, "author": "BalusC", "author_id": 157882, "author_profile": "https://Stackoverflow.com/users/157882", "pm_score": 4, "selected": false, "text": "fn:replace() \\n ; ${fn:replace(data, '\\n', ';')}\n ${fn:replace(data, '\\\\n', ';')}\n" }, { "answer_id": 2554822, "author": "wheresrhys", "author_id": 87739, "author_profile": "https://Stackoverflow.com/users/87739", "pm_score": 0, "selected": false, "text": "<% pageContext.setAttribute(\"newLineChar\", \"\\r\"); %> \n<c:set var=\"textAreaDefault\" value=\"${fn:replace(textAreaDefault, newLineChar, '')}\" />\n" }, { "answer_id": 4044412, "author": "brunohop", "author_id": 490275, "author_profile": "https://Stackoverflow.com/users/490275", "pm_score": 1, "selected": false, "text": "<str:replace var=\"your_Var_replaced\" replace=\"\\n\" with=\"Your ney caracter\" newlineToken=\"\\n\">${your_Var_to_replaced}</str:replace> \n" }, { "answer_id": 6960566, "author": "Leonid", "author_id": 264834, "author_profile": "https://Stackoverflow.com/users/264834", "pm_score": 2, "selected": false, "text": "${fn:replace(text, \"\n\", \"<br/>\")}\n <c:set var=\"nl\" value=\"\n\" /><%-- this is a new line --%>\n" }, { "answer_id": 7124466, "author": "andy", "author_id": 846977, "author_profile": "https://Stackoverflow.com/users/846977", "pm_score": 4, "selected": false, "text": "<c:set var=\"newline\" value=\"<%= \\\"\\n\\\" %>\" />\n${fn:replace(myAddress, newline, \"<br />\")}\n <c:set var=\"newline\" value=\"\n\" /><!--this line can't be indented -->\n ${fn:replace(myAddress, newline, \"<br />\")}\n" }, { "answer_id": 31520021, "author": "Thomas Meyer", "author_id": 5135628, "author_profile": "https://Stackoverflow.com/users/5135628", "pm_score": 2, "selected": false, "text": "\"${fn:split(string1, Character.valueOf(10))}\"\n" } ]
2008/09/12
[ "https://Stackoverflow.com/questions/58054", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6027/" ]
58,058
<p>I'm trying to write a small class library for a C++ course.</p> <p>I was wondering if it was possible to define a set of classes in my shared object and then using them directly in my main program that demos the library. Are there any tricks involved? I remember reading this long ago (before I started really programming) that C++ classes only worked with MFC .dlls and not plain ones, but that's just the windows side.</p>
[ { "answer_id": 58061, "author": "Kristopher Johnson", "author_id": 1175, "author_profile": "https://Stackoverflow.com/users/1175", "pm_score": 5, "selected": true, "text": "-fPIC -shared" }, { "answer_id": 58171, "author": "Flame", "author_id": 5387, "author_profile": "https://Stackoverflow.com/users/5387", "pm_score": 3, "selected": false, "text": "#include <string>\n\nclass Cat\n{\n std::string _name;\npublic:\n Cat(const std::string & name);\n void speak();\n};\n #include <iostream>\n#include <string>\n\n#include \"cat.hh\"\n\nusing namespace std;\n\nCat::Cat(const string & name):_name(name){}\nvoid Cat::speak()\n{\n cout << \"Meow! I'm \" << _name << endl;\n}\n #include <iostream>\n#include <string>\n#include \"cat.hh\"\n\nusing std::cout;using std::endl;using std::string;\nint main()\n{\n string name = \"Felix\";\n cout<< \"Meet my cat, \" << name << \"!\" <<endl;\n Cat kitty(name);\n kitty.speak();\n return 0;\n}\n $ g++ -Wall -g -fPIC -c cat.cpp\n$ g++ -shared -Wl,-soname,libcat.so.1 -o libcat.so.1 cat.o\n $ g++ -Wall -g -c main.cpp\n$ g++ -Wall -Wl,-rpath,. -o main main.o libcat.so.1 # -rpath linker option prevents the need to use LD_LIBRARY_PATH when testing\n$ ./main\nMeet my cat, Felix!\nMeow! I'm Felix\n$\n" } ]
2008/09/12
[ "https://Stackoverflow.com/questions/58058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5387/" ]
58,119
<p>I can't tell from the Python documentation whether the re.compile(x) function may throw an exception (assuming you pass in a string). I imagine there is something that could be considered an invalid regular expression. The larger question is, where do I go to find if a given Python library call may throw exception(s) and what those are? </p>
[ { "answer_id": 58129, "author": "Blair Conrad", "author_id": 1199, "author_profile": "https://Stackoverflow.com/users/1199", "pm_score": 5, "selected": true, "text": "re.compile >>> import re\n>>> re.compile('he(lo')\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n File \"C:\\Python25\\lib\\re.py\", line 180, in compile\n return _compile(pattern, flags)\n File \"C:\\Python25\\lib\\re.py\", line 233, in _compile\n raise error, v # invalid expression\nsre_constants.error: unbalanced parenthesis\n error" } ]
2008/09/12
[ "https://Stackoverflow.com/questions/58119", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1892/" ]
58,123
<p>This is actually a two part question. First,does the HttpContext.Current correspond to the current System.UI.Page object?</p> <p>And the second question, which is probably related to the first, is why can't I use the following to see if the current page implements an interface:</p> <pre><code>private IWebBase FindWebBase() { if (HttpContext.Current as IWebBase != null) { return (IWebBase)HttpContext.Current.; } throw new NotImplementedException("Crawling for IWebBase not implemented yet"); } </code></pre> <p>The general context is that some controls need to know whether they are executing as a SharePoint webpart, or as part of an Asp.Net framework.</p> <p>I have solved the problem by requiring the control to pass a reference to itself, and checking the Page property of the control, but I'm still curious why the above does not work.</p> <p>The compiler error is: Cannot convert System.Web.HttpContext to ...IWebBase via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion or null type conversion.</p>
[ { "answer_id": 58128, "author": "Kilhoffer", "author_id": 5469, "author_profile": "https://Stackoverflow.com/users/5469", "pm_score": 5, "selected": false, "text": "HttpContext.Handler HttpContext.Current" }, { "answer_id": 58131, "author": "Ash", "author_id": 5023, "author_profile": "https://Stackoverflow.com/users/5023", "pm_score": 8, "selected": true, "text": "Page page = HttpContext.Current.Handler as Page;\n\nif (page != null)\n{\n // Use page instance.\n}\n" }, { "answer_id": 6617694, "author": "user452427", "author_id": 452427, "author_profile": "https://Stackoverflow.com/users/452427", "pm_score": 4, "selected": false, "text": "HttpContext.Current.CurrentHandler Response.Transfer CurrentHandler HttpContext.Current.Handler" } ]
2008/09/12
[ "https://Stackoverflow.com/questions/58123", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1685/" ]
58,141
<p>I knew of some performance reasons back in the SQL 7 days, but do the same issues still exist in SQL Server 2005? If I have a resultset in a stored procedure that I want to act upon individually, are cursors still a bad choice? If so, why?</p>
[ { "answer_id": 6052778, "author": "Gayan", "author_id": 760195, "author_profile": "https://Stackoverflow.com/users/760195", "pm_score": 2, "selected": false, "text": "DECLARE @commandname NVARCHAR(1000) = '';\n\nSELECT @commandname += 'truncate table ' + tablename + '; ';\nFROM tableNames;\n\nEXEC sp_executesql @commandname;\n" }, { "answer_id": 6768633, "author": "Zorkind", "author_id": 854213, "author_profile": "https://Stackoverflow.com/users/854213", "pm_score": 4, "selected": false, "text": "DECLARE @TAB TABLE(ID INT IDENTITY, COLUMN1 VARCHAR(10), COLUMN2 VARCHAR(10))\n\nDECLARE @COUNT INT,\n @MAX INT, \n @CONCAT VARCHAR(MAX), \n @COLUMN1 VARCHAR(10), \n @COLUMN2 VARCHAR(10)\n\nSET @COUNT = 1\n\nINSERT INTO @TAB VALUES('TE1S', 'TE21')\nINSERT INTO @TAB VALUES('TE1S', 'TE22')\nINSERT INTO @TAB VALUES('TE1S', 'TE23')\nINSERT INTO @TAB VALUES('TE1S', 'TE24')\nINSERT INTO @TAB VALUES('TE1S', 'TE25')\n\nSELECT @MAX = @@IDENTITY\n\nWHILE @COUNT <= @MAX BEGIN\n SELECT @COLUMN1 = COLUMN1, @COLUMN2 = COLUMN2 FROM @TAB WHERE ID = @COUNT\n\n IF @CONCAT IS NULL BEGIN\n SET @CONCAT = '' \n END ELSE BEGIN \n SET @CONCAT = @CONCAT + ',' \n END\n\n SET @CONCAT = @CONCAT + @COLUMN1 + @COLUMN2\n\n SET @COUNT = @COUNT + 1\nEND\n\nSELECT @CONCAT\n" }, { "answer_id": 30964726, "author": "Erik Hart", "author_id": 832306, "author_profile": "https://Stackoverflow.com/users/832306", "pm_score": 3, "selected": false, "text": "SELECT * FROM @temptable WHERE Id=@counter \n SELECT TOP 1 * FROM @temptable WHERE Id>@lastId\n var items = new List<Item>();\nforeach(int oneId in itemIds)\n{\n items.Add(dataAccess.GetItemById(oneId);\n}\n var items = dataAccess.GetItemsByIds(itemIds);\n" } ]
2008/09/12
[ "https://Stackoverflow.com/questions/58141", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5469/" ]
58,146
<p>I am trying to come up with the best way to render some hierarchical data in to a nested unordered list using ASP.NET MVC. Does anyone have any tips on how to do this?</p>
[ { "answer_id": 282066, "author": "Paco", "author_id": 13376, "author_profile": "https://Stackoverflow.com/users/13376", "pm_score": 1, "selected": false, "text": "/// This is the model class\npublic class MyTreeNode<T>\n{\n public ICollection<MyTreeNode> ChildNodes {get;}\n public T MyValue { get; set; }\n bool HasChildren { get { return ChildNodes.Any(); } }\n}\n\n///This is the html helper:\npublic static string RenderTree<T>(this HtmlHelper html, MyTreeNode<T> root, Func<T, string> renderNode)\n{\n var sb = new StringBuilder();\n sb.Append(renderNode(root.MyValue));\n if (root.HasChildren)\n {\n foreach(var child in root.ChildNodes)\n {\n sb.Append(RenderTree<T>(html, child, renderNode));\n }\n }\n return sb.ToString();\n}\n" } ]
2008/09/12
[ "https://Stackoverflow.com/questions/58146", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5360/" ]
58,184
<p>Is there something special about Safari for Windows and AJAX?<br> In other words: Are there some common pitfalls I should keep in mind?</p>
[ { "answer_id": 58287, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 2, "selected": false, "text": "return false event.preventDefault() event.stopPropagation() event return" } ]
2008/09/12
[ "https://Stackoverflow.com/questions/58184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6024/" ]
58,190
<p>My current view is no, prefer Transact SQL stored procedures because they are a lighter weight and (possibly) higher performing option, while CLR procedures allow developers to get up to all sorts of mischief.</p> <p>However recently I have needed to debug some very poorly written TSQL stored procs. As usual I found many of the problems due to the original developer developer having no real TSQL experience, they were ASP.NET / C# focused.</p> <p>So, using CLR procedures would firstly provide a much more familiar toolset to this type of developer, and secondly, the debugging and testing facilities are more powerful (ie Visual Studio instead of SQL Management Studio). </p> <p>I'd be very interested in hearing your experience as it's seems it is not a simple choice. </p>
[ { "answer_id": 24812630, "author": "Solomon Rutzky", "author_id": 577765, "author_profile": "https://Stackoverflow.com/users/577765", "pm_score": 0, "selected": false, "text": "OPENQUERY OPENROWSET OPENQUERY OPENROWSET PRINT RAISERROR" } ]
2008/09/12
[ "https://Stackoverflow.com/questions/58190", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5023/" ]
58,207
<p>To create a playlist for all of the music in a folder, I am using the following command in bash:</p> <pre><code>ls &gt; list.txt </code></pre> <p>I would like to use the result of the <code>pwd</code> command for the name of the playlist.</p> <p>Something like:</p> <pre><code>ls &gt; ${pwd}.txt </code></pre> <p>That doesn't work though - can anyone tell me what syntax I need to use to do something like this?</p> <p><strong>Edit:</strong> As mentioned in the comments pwd will end up giving an absolute path, so my playlist will end up being named .txt in some directory - d'oh! So I'll have to trim the path. Thanks for spotting that - I would probably have spent ages wondering where my files went!</p>
[ { "answer_id": 58212, "author": "John Calsbeek", "author_id": 5696, "author_profile": "https://Stackoverflow.com/users/5696", "pm_score": 8, "selected": true, "text": "\"$(command substitution)\" ls > \"$(pwd).txt\"\n ls > \"`pwd`.txt\"\n pwd .txt basename ls > \"$(basename \"$(pwd)\").txt\"\n" }, { "answer_id": 58214, "author": "John Meagher", "author_id": 3535, "author_profile": "https://Stackoverflow.com/users/3535", "pm_score": 2, "selected": false, "text": "ls > `pwd`.txt\n" }, { "answer_id": 58224, "author": "Thomas Kammeyer", "author_id": 4410, "author_profile": "https://Stackoverflow.com/users/4410", "pm_score": 3, "selected": false, "text": "ls > `pwd`.txt\n ls > $PWD.txt\n ls > ${PWD}.txt\n ls > ${PWD}/${PWD##*/}.txt\n" }, { "answer_id": 58227, "author": "Mark Nold", "author_id": 4134, "author_profile": "https://Stackoverflow.com/users/4134", "pm_score": 2, "selected": false, "text": "#!/bin/sh\n\nMYVAR=`pwd | sed \"s|/|_|g\"`\nls > /playlistdir/$MYVAR-list.txt\n" }, { "answer_id": 58233, "author": "Landon", "author_id": 1597, "author_profile": "https://Stackoverflow.com/users/1597", "pm_score": 3, "selected": false, "text": "ls > $(pwd).txt\n" }, { "answer_id": 58235, "author": "erichui", "author_id": 6034, "author_profile": "https://Stackoverflow.com/users/6034", "pm_score": 3, "selected": false, "text": "ls > \"$(pwd).txt\"\n" }, { "answer_id": 9589723, "author": "technosaurus", "author_id": 1162141, "author_profile": "https://Stackoverflow.com/users/1162141", "pm_score": 0, "selected": false, "text": "ls >/playlistdir/${PWD##/*}.txt\n ls >/playlistdir/${PWD//\\//_}.txt\n ext=.mp3 #leave blank for all files\nfor FILE in \"$PWD/*$ext\"; do echo \"$FILE\";done >/playlistdir/${PWD##/*}.txt\n" } ]
2008/09/12
[ "https://Stackoverflow.com/questions/58207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/840/" ]
58,230
<p>Is there another way to render graphics in C# beyond <a href="https://en.wikipedia.org/wiki/Graphics_Device_Interface#Windows_XP" rel="nofollow noreferrer">GDI+</a> and <a href="http://en.wikipedia.org/wiki/Microsoft_XNA" rel="nofollow noreferrer">XNA</a>? </p> <p>(For the development of a tile map editor.)</p>
[ { "answer_id": 58242, "author": "Ash", "author_id": 5023, "author_profile": "https://Stackoverflow.com/users/5023", "pm_score": 2, "selected": false, "text": "Lock Unlock" } ]
2008/09/12
[ "https://Stackoverflow.com/questions/58230", "https://Stackoverflow.com", "https://Stackoverflow.com/users/568/" ]
58,245
<p>I've got a menu that contains, among other things, some most-recently-used file paths. The paths to these files can be long, so the text sometimes gets clipped like "C:\Progra...\foo.txt"</p> <p>I'd like to pop a tooltip with the full path when the user hovers over the item, but this doesn't seem possible with the <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.tooltip.aspx" rel="noreferrer">Tooltip</a> class in .NET 2.0.</p> <p>Am I missing something obvious?</p>
[ { "answer_id": 58253, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 1, "selected": false, "text": "Tooltip" }, { "answer_id": 58258, "author": "andynil", "author_id": 446, "author_profile": "https://Stackoverflow.com/users/446", "pm_score": 1, "selected": false, "text": "testToolStripMenuItem2.ToolTipText = \"My tooltip text\";\n MenuStrip menuStrip1; \nToolStripMenuItem testToolStripMenuItem; // Menu item on menu bar\nmenuStrip1.Items.Add(testToolStripMenuItem);\n\nToolStripMenuItem testToolStripMenuItem2; // Sub menu item\ntestToolStripMenuItem.DropDownItems.Add(testToolStripMenuItem2)\n" }, { "answer_id": 24709176, "author": "Thunder", "author_id": 232687, "author_profile": "https://Stackoverflow.com/users/232687", "pm_score": 2, "selected": false, "text": "yourMenuStrip.ShowItemToolTips = true;\nyourToolStripMenuItem.ToolTipText = \"some txt\";\n" } ]
2008/09/12
[ "https://Stackoverflow.com/questions/58245", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2773/" ]