qid
int64
4
8.14M
question
stringlengths
20
48.3k
answers
list
date
stringlengths
10
10
metadata
list
input
stringlengths
12
45k
output
stringlengths
2
31.8k
74,092
<p>I have a function in Python which is iterating over the attributes returned from <code>dir(obj)</code>, and I want to check to see if any of the objects contained within is a function, method, built-in function, etc. Normally you could use <code>callable()</code> for this, but I don't want to include classes. The best I've come up with so far is:</p> <pre><code>isinstance(obj, (types.BuiltinFunctionType, types.FunctionType, types.MethodType)) </code></pre> <p>Is there a more future-proof way to do this check?</p> <p><strong>Edit:</strong> I misspoke before when I said: &quot;Normally you could use <code>callable()</code> for this, but I don't want to disqualify classes.&quot; I actually <em>do</em> want to disqualify classes. I want to match <em>only</em> functions, not classes.</p>
[ { "answer_id": 74138, "author": "Jim", "author_id": 8427, "author_profile": "https://Stackoverflow.com/users/8427", "pm_score": 2, "selected": false, "text": "<pre><code>if hasattr(obj, '__call__'): pass\n</code></pre>\n\n<p>This also fits in better with Python's \"duck typing\" philosophy, because you don't really care <em>what</em> it is, so long as you can call it.</p>\n\n<p>It's worth noting that <code>callable()</code> is being removed from Python and is not present in 3.0.</p>\n" }, { "answer_id": 74295, "author": "dF.", "author_id": 3002, "author_profile": "https://Stackoverflow.com/users/3002", "pm_score": 3, "selected": false, "text": "<p>If you want to exclude classes and other random objects that may have a <code>__call__</code> method, and only check for functions and methods, these three functions in the <a href=\"http://docs.python.org/lib/module-inspect.html\" rel=\"noreferrer\"><code>inspect</code> module</a></p>\n\n<pre><code>inspect.isfunction(obj)\ninspect.isbuiltin(obj)\ninspect.ismethod(obj)\n</code></pre>\n\n<p>should do what you want in a future-proof way.</p>\n" }, { "answer_id": 75370, "author": "Matthieu", "author_id": 9310, "author_profile": "https://Stackoverflow.com/users/9310", "pm_score": 1, "selected": false, "text": "<p>Depending on what you mean by 'class':</p>\n\n<pre><code>callable( obj ) and not inspect.isclass( obj )\n</code></pre>\n\n<p>or:</p>\n\n<pre><code>callable( obj ) and not isinstance( obj, types.ClassType )\n</code></pre>\n\n<p>For example, results are different for 'dict':</p>\n\n<pre><code>&gt;&gt;&gt; callable( dict ) and not inspect.isclass( dict )\nFalse\n&gt;&gt;&gt; callable( dict ) and not isinstance( dict, types.ClassType )\nTrue\n</code></pre>\n" }, { "answer_id": 75507, "author": "Matthieu", "author_id": 9310, "author_profile": "https://Stackoverflow.com/users/9310", "pm_score": 5, "selected": true, "text": "<p>The inspect module has exactly what you want:</p>\n\n<pre><code>inspect.isroutine( obj )\n</code></pre>\n\n<p>FYI, the code is:</p>\n\n<pre><code>def isroutine(object):\n \"\"\"Return true if the object is any kind of function or method.\"\"\"\n return (isbuiltin(object)\n or isfunction(object)\n or ismethod(object)\n or ismethoddescriptor(object))\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/74092", "https://Stackoverflow.com", "https://Stackoverflow.com/users/156/" ]
I have a function in Python which is iterating over the attributes returned from `dir(obj)`, and I want to check to see if any of the objects contained within is a function, method, built-in function, etc. Normally you could use `callable()` for this, but I don't want to include classes. The best I've come up with so far is: ``` isinstance(obj, (types.BuiltinFunctionType, types.FunctionType, types.MethodType)) ``` Is there a more future-proof way to do this check? **Edit:** I misspoke before when I said: "Normally you could use `callable()` for this, but I don't want to disqualify classes." I actually *do* want to disqualify classes. I want to match *only* functions, not classes.
The inspect module has exactly what you want: ``` inspect.isroutine( obj ) ``` FYI, the code is: ``` def isroutine(object): """Return true if the object is any kind of function or method.""" return (isbuiltin(object) or isfunction(object) or ismethod(object) or ismethoddescriptor(object)) ```
74,113
<p>It seems obvious that some people have been able to figure out how to access the iPhone camera through the SDK (Spore Origins, for example). How can this be done?</p>
[ { "answer_id": 74255, "author": "wxs", "author_id": 12981, "author_profile": "https://Stackoverflow.com/users/12981", "pm_score": 7, "selected": true, "text": "<p>You need to use the <code>UIImagePickerController</code> class, basically:</p>\n\n<pre><code>UIImagePickerController *picker = [[UIImagePickerController alloc] init];\npicker.delegate = pickerDelegate\npicker.sourceType = UIImagePickerControllerSourceTypeCamera\n</code></pre>\n\n<p>The <code>pickerDelegate</code> object above needs to implement the following method:</p>\n\n<pre><code>- (void)imagePickerController:(UIImagePickerController *)picker\n didFinishPickingMediaWithInfo:(NSDictionary *)info\n</code></pre>\n\n<p>The dictionary <code>info</code> will contain entries for the original, and the edited image, keyed with <code>UIImagePickerControllerOriginalImage</code> and <code>UIImagePickerControllerEditedImage</code> respectively. (see <a href=\"https://developer.apple.com/documentation/uikit/uiimagepickercontrollerdelegate\" rel=\"nofollow noreferrer\">https://developer.apple.com/documentation/uikit/uiimagepickercontrollerdelegate</a> and <a href=\"https://developer.apple.com/documentation/uikit/uiimagepickercontrollerinfokey\" rel=\"nofollow noreferrer\">https://developer.apple.com/documentation/uikit/uiimagepickercontrollerinfokey</a> for more details)</p>\n" }, { "answer_id": 3211440, "author": "binshi", "author_id": 356250, "author_profile": "https://Stackoverflow.com/users/356250", "pm_score": 3, "selected": false, "text": "<p>Hmmmm.....Ever tried using an OverlayView? With this the camera might look customized but in actuality its just a view above it.</p>\n\n<p>If the private API's are directly accessed it might result in the app being rejected by Apple.\nSee if the below link helps.</p>\n\n<p><a href=\"http://www.articlesbase.com/programming-articles/custom-camera-applications-development-using-iphone-sdk-766832.html\" rel=\"noreferrer\">link text</a></p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/74113", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5338/" ]
It seems obvious that some people have been able to figure out how to access the iPhone camera through the SDK (Spore Origins, for example). How can this be done?
You need to use the `UIImagePickerController` class, basically: ``` UIImagePickerController *picker = [[UIImagePickerController alloc] init]; picker.delegate = pickerDelegate picker.sourceType = UIImagePickerControllerSourceTypeCamera ``` The `pickerDelegate` object above needs to implement the following method: ``` - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info ``` The dictionary `info` will contain entries for the original, and the edited image, keyed with `UIImagePickerControllerOriginalImage` and `UIImagePickerControllerEditedImage` respectively. (see <https://developer.apple.com/documentation/uikit/uiimagepickercontrollerdelegate> and <https://developer.apple.com/documentation/uikit/uiimagepickercontrollerinfokey> for more details)
74,148
<p>How do you convert between hexadecimal numbers and decimal numbers in C#?</p>
[ { "answer_id": 74183, "author": "Sklivvz", "author_id": 7028, "author_profile": "https://Stackoverflow.com/users/7028", "pm_score": 2, "selected": false, "text": "<pre><code>String stringrep = myintvar.ToString(\"X\");\n\nint num = int.Parse(\"FF\", System.Globalization.NumberStyles.HexNumber);\n</code></pre>\n" }, { "answer_id": 74185, "author": "Jesper Blad Jensen", "author_id": 11559, "author_profile": "https://Stackoverflow.com/users/11559", "pm_score": 5, "selected": false, "text": "<p>It looks like you can say</p>\n\n<pre><code>Convert.ToInt64(value, 16)\n</code></pre>\n\n<p>to get the decimal from hexdecimal.</p>\n\n<p>The other way around is:</p>\n\n<pre><code>otherVar.ToString(\"X\");\n</code></pre>\n" }, { "answer_id": 74191, "author": "Rob", "author_id": 12413, "author_profile": "https://Stackoverflow.com/users/12413", "pm_score": 4, "selected": false, "text": "<p><a href=\"https://web.archive.org/web/20081231062758/http://www.geekpedia.com/KB8_How-do-I-convert-from-decimal-to-hex-and-hex-to-decimal.html\" rel=\"noreferrer\">From Geekpedia</a>:</p>\n\n<pre><code>// Store integer 182\nint decValue = 182;\n\n// Convert integer 182 as a hex in a string variable\nstring hexValue = decValue.ToString(\"X\");\n\n// Convert the hex string back to the number\nint decAgain = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);\n</code></pre>\n" }, { "answer_id": 74198, "author": "Jonathan Rupp", "author_id": 12502, "author_profile": "https://Stackoverflow.com/users/12502", "pm_score": 6, "selected": false, "text": "<p>Hex -&gt; decimal:</p>\n<pre><code>Convert.ToInt64(hexString, 16);\n</code></pre>\n<p>Decimal -&gt; Hex</p>\n<pre><code>string.Format(&quot;{0:x}&quot;, intValue);\n</code></pre>\n" }, { "answer_id": 74223, "author": "Andy McCluggage", "author_id": 3362, "author_profile": "https://Stackoverflow.com/users/3362", "pm_score": 9, "selected": true, "text": "<p>To convert from decimal to hex do...</p>\n\n<pre><code>string hexValue = decValue.ToString(\"X\");\n</code></pre>\n\n<p>To convert from hex to decimal do either...</p>\n\n<pre><code>int decValue = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);\n</code></pre>\n\n<p>or </p>\n\n<pre><code>int decValue = Convert.ToInt32(hexValue, 16);\n</code></pre>\n" }, { "answer_id": 2484244, "author": "Ecstatic Coder", "author_id": 298120, "author_profile": "https://Stackoverflow.com/users/298120", "pm_score": 1, "selected": false, "text": "<pre><code> static string chex(byte e) // Convert a byte to a string representing that byte in hexadecimal\n {\n string r = \"\";\n string chars = \"0123456789ABCDEF\";\n r += chars[e &gt;&gt; 4];\n return r += chars[e &amp;= 0x0F];\n } // Easy enough...\n\n static byte CRAZY_BYTE(string t, int i) // Take a byte, if zero return zero, else throw exception (i=0 means false, i&gt;0 means true)\n {\n if (i == 0) return 0;\n throw new Exception(t);\n }\n\n static byte hbyte(string e) // Take 2 characters: these are hex chars, convert it to a byte\n { // WARNING: This code will make small children cry. Rated R.\n e = e.ToUpper(); // \n string msg = \"INVALID CHARS\"; // The message that will be thrown if the hex str is invalid\n\n byte[] t = new byte[] // Gets the 2 characters and puts them in seperate entries in a byte array.\n { // This will throw an exception if (e.Length != 2).\n (byte)e[CRAZY_BYTE(\"INVALID LENGTH\", e.Length ^ 0x02)], \n (byte)e[0x01] \n };\n\n for (byte i = 0x00; i &lt; 0x02; i++) // Convert those [ascii] characters to [hexadecimal] characters. Error out if either character is invalid.\n {\n t[i] -= (byte)((t[i] &gt;= 0x30) ? 0x30 : CRAZY_BYTE(msg, 0x01)); // Check for 0-9\n t[i] -= (byte)((!(t[i] &lt; 0x0A)) ? (t[i] &gt;= 0x11 ? 0x07 : CRAZY_BYTE(msg, 0x01)) : 0x00); // Check for A-F\n } \n\n return t[0x01] |= t[0x00] &lt;&lt;= 0x04; // The moment of truth.\n }\n</code></pre>\n" }, { "answer_id": 4474966, "author": "Omair", "author_id": 546562, "author_profile": "https://Stackoverflow.com/users/546562", "pm_score": 1, "selected": false, "text": "<p>This is not really easiest way but this source code enable you to right any types of octal number i.e 23.214, 23 and 0.512 and so on. Hope this will help you..</p>\n\n<pre><code> public string octal_to_decimal(string m_value)\n {\n double i, j, x = 0;\n Int64 main_value;\n int k = 0;\n bool pw = true, ch;\n int position_pt = m_value.IndexOf(\".\");\n if (position_pt == -1)\n {\n main_value = Convert.ToInt64(m_value);\n ch = false;\n }\n else\n {\n main_value = Convert.ToInt64(m_value.Remove(position_pt, m_value.Length - position_pt));\n ch = true;\n }\n\n while (k &lt;= 1)\n {\n do\n {\n i = main_value % 10; // Return Remainder\n i = i * Convert.ToDouble(Math.Pow(8, x)); // calculate power\n if (pw)\n x++;\n else\n x--;\n o_to_d = o_to_d + i; // Saving Required calculated value in main variable\n main_value = main_value / 10; // Dividing the main value \n }\n while (main_value &gt;= 1);\n if (ch)\n {\n k++;\n main_value = Convert.ToInt64(Reversestring(m_value.Remove(0, position_pt + 1)));\n }\n else\n k = 2;\n pw = false;\n x = -1;\n }\n return (Convert.ToString(o_to_d));\n } \n</code></pre>\n" }, { "answer_id": 6205484, "author": "msanjay", "author_id": 392985, "author_profile": "https://Stackoverflow.com/users/392985", "pm_score": 2, "selected": false, "text": "<p>If it's a really big hex string beyond the capacity of the normal integer:</p>\n\n<p>For .NET 3.5, we can use BouncyCastle's BigInteger class:</p>\n\n<pre><code>String hex = \"68c7b05d0000000002f8\";\n// results in \"494809724602834812404472\"\nString decimal = new Org.BouncyCastle.Math.BigInteger(hex, 16).ToString();\n</code></pre>\n\n<p>.NET 4.0 has the <a href=\"http://msdn.microsoft.com/en-us/library/system.numerics.biginteger.aspx\" rel=\"nofollow\">BigInteger</a> class.</p>\n" }, { "answer_id": 6666767, "author": "Luke Puplett", "author_id": 107783, "author_profile": "https://Stackoverflow.com/users/107783", "pm_score": -1, "selected": false, "text": "<p>An extension method for converting a byte array into a hex representation. This pads each byte with leading zeros.</p>\n\n<pre><code> /// &lt;summary&gt;\n /// Turns the byte array into its Hex representation.\n /// &lt;/summary&gt;\n public static string ToHex(this byte[] y)\n {\n StringBuilder sb = new StringBuilder();\n foreach (byte b in y)\n {\n sb.Append(b.ToString(\"X\").PadLeft(2, \"0\"[0]));\n }\n return sb.ToString();\n }\n</code></pre>\n" }, { "answer_id": 9126750, "author": "Vadym Stetsiak", "author_id": 6952, "author_profile": "https://Stackoverflow.com/users/6952", "pm_score": 4, "selected": false, "text": "<p>If you want maximum performance when doing conversion from hex to decimal number, you can use the approach with pre-populated table of hex-to-decimal values.</p>\n\n<p>Here is the code that illustrates that idea. My <a href=\"http://vadmyst.blogspot.com/2012/02/fast-convertion-of-hex-string-into.html\" rel=\"noreferrer\">performance tests</a> showed that it can be 20%-40% faster than Convert.ToInt32(...):</p>\n\n<pre><code>class TableConvert\n {\n static sbyte[] unhex_table =\n { -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1\n ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1\n ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1\n , 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,-1,-1,-1,-1,-1,-1\n ,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1\n ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1\n ,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1\n ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1\n };\n\n public static int Convert(string hexNumber)\n {\n int decValue = unhex_table[(byte)hexNumber[0]];\n for (int i = 1; i &lt; hexNumber.Length; i++)\n {\n decValue *= 16;\n decValue += unhex_table[(byte)hexNumber[i]];\n }\n return decValue;\n }\n }\n</code></pre>\n" }, { "answer_id": 21079586, "author": "Chris Panayotoff", "author_id": 1584898, "author_profile": "https://Stackoverflow.com/users/1584898", "pm_score": -1, "selected": false, "text": "<p>Here is my function:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nclass HexadecimalToDecimal\n{\n static Dictionary&lt;char, int&gt; hexdecval = new Dictionary&lt;char, int&gt;{\n {'0', 0},\n {'1', 1},\n {'2', 2},\n {'3', 3},\n {'4', 4},\n {'5', 5},\n {'6', 6},\n {'7', 7},\n {'8', 8},\n {'9', 9},\n {'a', 10},\n {'b', 11},\n {'c', 12},\n {'d', 13},\n {'e', 14},\n {'f', 15},\n };\n\n static decimal HexToDec(string hex)\n {\n decimal result = 0;\n hex = hex.ToLower();\n\n for (int i = 0; i &lt; hex.Length; i++)\n {\n char valAt = hex[hex.Length - 1 - i];\n result += hexdecval[valAt] * (int)Math.Pow(16, i);\n }\n\n return result;\n }\n\n static void Main()\n {\n\n Console.WriteLine(\"Enter Hexadecimal value\");\n string hex = Console.ReadLine().Trim();\n\n //string hex = \"29A\";\n Console.WriteLine(\"Hex {0} is dec {1}\", hex, HexToDec(hex));\n\n Console.ReadKey();\n }\n}\n</code></pre>\n" }, { "answer_id": 28408141, "author": "Mihók Balázs", "author_id": 4545945, "author_profile": "https://Stackoverflow.com/users/4545945", "pm_score": 0, "selected": false, "text": "<p>My version is I think a little more understandable because my C# knowledge is not so high.\nI'm using this algorithm: <a href=\"http://easyguyevo.hubpages.com/hub/Convert-Hex-to-Decimal\" rel=\"nofollow\">http://easyguyevo.hubpages.com/hub/Convert-Hex-to-Decimal</a> (The Example 2)</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\n\nstatic class Tool\n{\n public static string DecToHex(int x)\n {\n string result = \"\";\n\n while (x != 0)\n {\n if ((x % 16) &lt; 10)\n result = x % 16 + result;\n else\n {\n string temp = \"\";\n\n switch (x % 16)\n {\n case 10: temp = \"A\"; break;\n case 11: temp = \"B\"; break;\n case 12: temp = \"C\"; break;\n case 13: temp = \"D\"; break;\n case 14: temp = \"E\"; break;\n case 15: temp = \"F\"; break;\n }\n\n result = temp + result;\n }\n\n x /= 16;\n }\n\n return result;\n }\n\n public static int HexToDec(string x)\n {\n int result = 0;\n int count = x.Length - 1;\n for (int i = 0; i &lt; x.Length; i++)\n {\n int temp = 0;\n switch (x[i])\n {\n case 'A': temp = 10; break;\n case 'B': temp = 11; break;\n case 'C': temp = 12; break;\n case 'D': temp = 13; break;\n case 'E': temp = 14; break;\n case 'F': temp = 15; break;\n default: temp = -48 + (int)x[i]; break; // -48 because of ASCII\n }\n\n result += temp * (int)(Math.Pow(16, count));\n count--;\n }\n\n return result;\n }\n}\n\nclass Program\n{\n static void Main(string[] args)\n {\n Console.Write(\"Enter Decimal value: \");\n int decNum = int.Parse(Console.ReadLine());\n\n Console.WriteLine(\"Dec {0} is hex {1}\", decNum, Tool.DecToHex(decNum));\n\n Console.Write(\"\\nEnter Hexadecimal value: \");\n string hexNum = Console.ReadLine().ToUpper();\n\n Console.WriteLine(\"Hex {0} is dec {1}\", hexNum, Tool.HexToDec(hexNum));\n\n Console.ReadKey();\n }\n}\n</code></pre>\n" }, { "answer_id": 29939746, "author": "Jewel", "author_id": 4845704, "author_profile": "https://Stackoverflow.com/users/4845704", "pm_score": 0, "selected": false, "text": "<p>Convert binary to Hex</p>\n\n<pre><code>Convert.ToString(Convert.ToUInt32(binary1, 2), 16).ToUpper()\n</code></pre>\n" }, { "answer_id": 44120599, "author": "user7925882", "author_id": 7925882, "author_profile": "https://Stackoverflow.com/users/7925882", "pm_score": 2, "selected": false, "text": "<p>Hex to Decimal Conversion</p>\n\n<pre><code>Convert.ToInt32(number, 16);\n</code></pre>\n\n<p>Decimal to Hex Conversion</p>\n\n<pre><code>int.Parse(number, System.Globalization.NumberStyles.HexNumber)\n</code></pre>\n\n<p><a href=\"http://kodecenter.com/article?id=f3ed25f1-2563-4323-9f43-c4fbbc9c372f\" rel=\"nofollow noreferrer\">For more details Check this article</a></p>\n" }, { "answer_id": 49569835, "author": "Aravin", "author_id": 3058254, "author_profile": "https://Stackoverflow.com/users/3058254", "pm_score": 2, "selected": false, "text": "<p>Try using BigNumber in C# - Represents an arbitrarily large signed integer.</p>\n\n<h3>Program</h3>\n\n<pre><code>using System.Numerics;\n...\nvar bigNumber = BigInteger.Parse(\"837593454735734579347547357233757342857087879423437472347757234945743\");\nConsole.WriteLine(bigNumber.ToString(\"X\"));\n</code></pre>\n\n<h3>Output</h3>\n\n<pre><code>4F30DC39A5B10A824134D5B18EEA3707AC854EE565414ED2E498DCFDE1A15DA5FEB6074AE248458435BD417F06F674EB29A2CFECF\n</code></pre>\n\n<h3>Possible Exceptions,</h3>\n\n<p>ArgumentNullException - value is null.</p>\n\n<p>FormatException - value is not in the correct format.</p>\n\n<h3>Conclusion</h3>\n\n<p>You can convert string and store a value in BigNumber without constraints about the size of the number unless the string is empty and non-analphabets</p>\n" }, { "answer_id": 54082994, "author": "Krisztián Molnár", "author_id": 10881471, "author_profile": "https://Stackoverflow.com/users/10881471", "pm_score": -1, "selected": false, "text": "<p>My solution is a bit like back to basics, but it works without using any built-in functions to convert between number systems.</p>\n\n<pre><code> public static string DecToHex(long a)\n {\n int n = 1;\n long b = a;\n while (b &gt; 15)\n {\n b /= 16;\n n++;\n }\n string[] t = new string[n];\n int i = 0, j = n - 1;\n do\n {\n if (a % 16 == 10) t[i] = \"A\";\n else if (a % 16 == 11) t[i] = \"B\";\n else if (a % 16 == 12) t[i] = \"C\";\n else if (a % 16 == 13) t[i] = \"D\";\n else if (a % 16 == 14) t[i] = \"E\";\n else if (a % 16 == 15) t[i] = \"F\";\n else t[i] = (a % 16).ToString();\n a /= 16;\n i++;\n }\n while ((a * 16) &gt; 15);\n string[] r = new string[n];\n for (i = 0; i &lt; n; i++)\n {\n r[i] = t[j];\n j--;\n }\n string res = string.Concat(r);\n return res;\n }\n</code></pre>\n" }, { "answer_id": 67015650, "author": "MohsenB", "author_id": 1358148, "author_profile": "https://Stackoverflow.com/users/1358148", "pm_score": 0, "selected": false, "text": "<p>You can use this code and possible set Hex length and part's:<br></p>\n<pre><code>const int decimal_places = 4;\nconst int int_places = 4;\nstatic readonly string decimal_places_format = $&quot;X{decimal_places}&quot;;\nstatic readonly string int_places_format = $&quot;X{int_places}&quot;;\n\npublic static string DecimaltoHex(decimal number)\n{\n var n = (int)Math.Truncate(number);\n var f = (int)Math.Truncate((number - n) * ((decimal)Math.Pow(10, decimal_places)));\n return $&quot;{string.Format($&quot;{{0:{int_places_format}}}&quot;, n)}{string.Format($&quot;{{0:{decimal_places_format}}}&quot;, f)}&quot;;\n}\n\npublic static decimal HextoDecimal(string number)\n{\n var n = number.Substring(0, number.Length - decimal_places);\n var f = number.Substring(number.Length - decimal_places);\n return decimal.Parse($&quot;{int.Parse(n, System.Globalization.NumberStyles.HexNumber)}.{int.Parse(f, System.Globalization.NumberStyles.HexNumber)}&quot;);\n}\n</code></pre>\n" }, { "answer_id": 67652913, "author": "Dejan Dozet", "author_id": 4541566, "author_profile": "https://Stackoverflow.com/users/4541566", "pm_score": 1, "selected": false, "text": "<p>This one worked for me:</p>\n<pre><code>public static decimal HexToDec(string hex)\n{\n if (hex.Length % 2 == 1)\n hex = &quot;0&quot; + hex;\n byte[] raw = new byte[hex.Length / 2];\n decimal d = 0;\n for (int i = 0; i &lt; raw.Length; i++)\n {\n raw[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);\n d += Math.Pow(256, (raw.Length - 1 - i)) * raw[i];\n }\n return d.ToString();\n return d;\n}\n</code></pre>\n" }, { "answer_id": 68256392, "author": "Rakibul", "author_id": 12944359, "author_profile": "https://Stackoverflow.com/users/12944359", "pm_score": 1, "selected": false, "text": "<p>Decimal - Hexa</p>\n<pre><code> var decValue = int.Parse(Console.ReadLine());\n string hex = string.Format(&quot;{0:x}&quot;, decValue);\n Console.WriteLine(hex);\n</code></pre>\n<p>Hexa - Decimal (use namespace: using System.Globalization;)</p>\n<pre><code> var hexval = Console.ReadLine();\n int decValue = int.Parse(hexval, NumberStyles.HexNumber);\n Console.WriteLine(decValue);\n</code></pre>\n" }, { "answer_id": 71229254, "author": "Marco Antonio", "author_id": 6907130, "author_profile": "https://Stackoverflow.com/users/6907130", "pm_score": 1, "selected": false, "text": "<p><strong>FOUR C# native ways to convert Hex to Dec and back:</strong></p>\n<pre><code>using System;\n\nnamespace Hexadecimal_and_Decimal\n{\n internal class Program\n {\n private static void Main(string[] args)\n {\n string hex = &quot;4DEAD&quot;;\n int dec;\n\n // hex to dec:\n dec = int.Parse(hex, System.Globalization.NumberStyles.HexNumber);\n // or:\n dec = Convert.ToInt32(hex, 16);\n\n // dec to hex:\n hex = dec.ToString(&quot;X&quot;); // lowcase: x, uppercase: X\n // or:\n hex = string.Format(&quot;{0:X}&quot;, dec); // lowcase: x, uppercase: X\n\n Console.WriteLine(&quot;Hexadecimal number: &quot; + hex);\n Console.WriteLine(&quot;Decimal number: &quot; + dec);\n }\n }\n}\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/74148", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3362/" ]
How do you convert between hexadecimal numbers and decimal numbers in C#?
To convert from decimal to hex do... ``` string hexValue = decValue.ToString("X"); ``` To convert from hex to decimal do either... ``` int decValue = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber); ``` or ``` int decValue = Convert.ToInt32(hexValue, 16); ```
74,162
<p>I'm trying to write a query that extracts and transforms data from a table and then insert those data into another table. Yes, this is a data warehousing query and I'm doing it in MS Access. So basically I want some query like this:</p> <pre><code>INSERT INTO Table2(LongIntColumn2, CurrencyColumn2) VALUES (SELECT LongIntColumn1, Avg(CurrencyColumn) as CurrencyColumn1 FROM Table1 GROUP BY LongIntColumn1); </code></pre> <p>I tried but get a syntax error message.</p> <p>What would you do if you want to do this?</p>
[ { "answer_id": 74196, "author": "Forgotten Semicolon", "author_id": 1960, "author_profile": "https://Stackoverflow.com/users/1960", "pm_score": 3, "selected": false, "text": "<p>Remove <code>VALUES</code> from your SQL.</p>\n" }, { "answer_id": 74204, "author": "pilsetnieks", "author_id": 6615, "author_profile": "https://Stackoverflow.com/users/6615", "pm_score": 9, "selected": true, "text": "<p>No \"VALUES\", no parenthesis:</p>\n\n<pre><code>INSERT INTO Table2(LongIntColumn2, CurrencyColumn2)\nSELECT LongIntColumn1, Avg(CurrencyColumn) as CurrencyColumn1 FROM Table1 GROUP BY LongIntColumn1;\n</code></pre>\n" }, { "answer_id": 74214, "author": "GSerg", "author_id": 11683, "author_profile": "https://Stackoverflow.com/users/11683", "pm_score": 5, "selected": false, "text": "<p>Remove both VALUES and the parenthesis.</p>\n\n<pre><code>INSERT INTO Table2 (LongIntColumn2, CurrencyColumn2)\nSELECT LongIntColumn1, Avg(CurrencyColumn) FROM Table1 GROUP BY LongIntColumn1\n</code></pre>\n" }, { "answer_id": 74222, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 5, "selected": false, "text": "<p>You have two syntax options:</p>\n\n<p><strong>Option 1</strong></p>\n\n<pre><code>CREATE TABLE Table1 (\n id int identity(1, 1) not null,\n LongIntColumn1 int,\n CurrencyColumn money\n)\n\nCREATE TABLE Table2 (\n id int identity(1, 1) not null,\n LongIntColumn2 int,\n CurrencyColumn2 money\n)\n\nINSERT INTO Table1 VALUES(12, 12.00)\nINSERT INTO Table1 VALUES(11, 13.00)\n\nINSERT INTO Table2\nSELECT LongIntColumn1, Avg(CurrencyColumn) as CurrencyColumn1 FROM Table1 GROUP BY LongIntColumn1\n</code></pre>\n\n<p><strong>Option 2</strong></p>\n\n<pre><code>CREATE TABLE Table1 (\n id int identity(1, 1) not null,\n LongIntColumn1 int,\n CurrencyColumn money\n)\n\nINSERT INTO Table1 VALUES(12, 12.00)\nINSERT INTO Table1 VALUES(11, 13.00)\n\n\nSELECT LongIntColumn1, Avg(CurrencyColumn) as CurrencyColumn1\nINTO Table2\nFROM Table1\nGROUP BY LongIntColumn1\n</code></pre>\n\n<p>Bear in mind that Option 2 will create a table with only the columns on the projection (those on the SELECT).</p>\n" }, { "answer_id": 74231, "author": "Philippe Grondier", "author_id": 11436, "author_profile": "https://Stackoverflow.com/users/11436", "pm_score": 2, "selected": false, "text": "<p>Well I think the best way would be (will be?) to define 2 recordsets and use them as an intermediate between the 2 tables. </p>\n\n<ol>\n<li>Open both recordsets</li>\n<li>Extract the data from the first table (SELECT blablabla) </li>\n<li>Update 2nd recordset with data available in the first recordset (either by adding new records or updating existing records</li>\n<li>Close both recordsets</li>\n</ol>\n\n<p>This method is particularly interesting if you plan to update tables from different databases (ie each recordset can have its own connection ...)</p>\n" }, { "answer_id": 74239, "author": "Sean", "author_id": 8334, "author_profile": "https://Stackoverflow.com/users/8334", "pm_score": 4, "selected": false, "text": "<p>I believe your problem in this instance is the \"values\" keyword. You use the \"values\" keyword when you are inserting only one row of data. For inserting the results of a select, you don't need it. </p>\n\n<p>Also, you really don't need the parentheses around the select statement. </p>\n\n<p>From <a href=\"http://msdn.microsoft.com/en-us/library/bb208861.aspx\" rel=\"noreferrer\">msdn</a>:</p>\n\n<p>Multiple-record append query:</p>\n\n<pre><code>INSERT INTO target [(field1[, field2[, …]])] [IN externaldatabase]\nSELECT [source.]field1[, field2[, …]\nFROM tableexpression\n</code></pre>\n\n<p>Single-record append query:</p>\n\n<pre><code>INSERT INTO target [(field1[, field2[, …]])] \nVALUES (value1[, value2[, …])\n</code></pre>\n" }, { "answer_id": 74285, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Do you want to insert extraction in an existing table? </p>\n\n<p>If it does not matter then you can try the below query:</p>\n\n<pre><code>SELECT LongIntColumn1, Avg(CurrencyColumn) as CurrencyColumn1 INTO T1 FROM Table1 \nGROUP BY LongIntColumn1);\n</code></pre>\n\n<p>It will create a new table -> T1 with the extracted information</p>\n" }, { "answer_id": 74347, "author": "Chris OC", "author_id": 11041, "author_profile": "https://Stackoverflow.com/users/11041", "pm_score": 2, "selected": false, "text": "<p>Remove \"values\" when you're appending a group of rows, and remove the extra parentheses. You can avoid the circular reference by using an alias for avg(CurrencyColumn) (as you did in your example) or by not using an alias at all.</p>\n\n<p>If the column names are the same in both tables, your query would be like this:</p>\n\n<pre><code>INSERT INTO Table2 (LongIntColumn, Junk)\nSELECT LongIntColumn, avg(CurrencyColumn) as CurrencyColumn1\nFROM Table1\nGROUP BY LongIntColumn;\n</code></pre>\n\n<p>And it would work without an alias:</p>\n\n<pre><code>INSERT INTO Table2 (LongIntColumn, Junk)\nSELECT LongIntColumn, avg(CurrencyColumn)\nFROM Table1\nGROUP BY LongIntColumn;\n</code></pre>\n" }, { "answer_id": 348981, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>inserting data form one table to another table in different DATABASE</p>\n\n<pre><code>insert into DocTypeGroup \n Select DocGrp_Id,DocGrp_SubId,DocGrp_GroupName,DocGrp_PM,DocGrp_DocType \n from Opendatasource( 'SQLOLEDB','Data Source=10.132.20.19;UserID=sa;Password=gchaturthi').dbIPFMCI.dbo.DocTypeGroup\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/74162", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8203/" ]
I'm trying to write a query that extracts and transforms data from a table and then insert those data into another table. Yes, this is a data warehousing query and I'm doing it in MS Access. So basically I want some query like this: ``` INSERT INTO Table2(LongIntColumn2, CurrencyColumn2) VALUES (SELECT LongIntColumn1, Avg(CurrencyColumn) as CurrencyColumn1 FROM Table1 GROUP BY LongIntColumn1); ``` I tried but get a syntax error message. What would you do if you want to do this?
No "VALUES", no parenthesis: ``` INSERT INTO Table2(LongIntColumn2, CurrencyColumn2) SELECT LongIntColumn1, Avg(CurrencyColumn) as CurrencyColumn1 FROM Table1 GROUP BY LongIntColumn1; ```
74,171
<p>I maintain a Java Swing application.</p> <p>For backwards compatibility with java 5 (for Apple machines), we maintain two codebases, 1 using features from Java 6, another without those features.</p> <p>The code is largely the same, except for 3-4 classes that uses Java 6 features.</p> <p>I wish to just maintain 1 codebase. Is there a way during compilation, to get the Java 5 compiler to 'ignore' some parts of my code?</p> <p>I do not wish to simply comment/uncomment parts of my code, depending on the version of my java compiler.</p>
[ { "answer_id": 74202, "author": "chessguy", "author_id": 1908025, "author_profile": "https://Stackoverflow.com/users/1908025", "pm_score": 2, "selected": false, "text": "<p>I think the best approach here is probably to use build scripts. You can have all your code in one location, and by choosing which files to include, and which not to include, you can choose what version of your code to compile. Note that this may not help if you need finer-grained control than per file.</p>\n" }, { "answer_id": 74229, "author": "Nikki9696", "author_id": 456669, "author_profile": "https://Stackoverflow.com/users/456669", "pm_score": 1, "selected": false, "text": "<p>Not really, but there are workarounds. See\n<a href=\"http://forums.sun.com/thread.jspa?threadID=154106&amp;messageID=447625\" rel=\"nofollow noreferrer\">http://forums.sun.com/thread.jspa?threadID=154106&amp;messageID=447625</a></p>\n\n<p>That said, you should stick with at least having one file version for Java 5 and one for Java 6, and include them via a build or make as appropriate. Sticking it all in one big file and trying to get the compiler for 5 to ignore stuff it doesn't understand isn't a good solution.</p>\n\n<p>HTH</p>\n\n<p>-- nikki --</p>\n" }, { "answer_id": 74259, "author": "DarenW", "author_id": 10468, "author_profile": "https://Stackoverflow.com/users/10468", "pm_score": 1, "selected": false, "text": "<p>This will make all the Java purists cringe (which is fun, heh heh) but i would use the C preprocessor, put #ifdefs in my source. A makefile, rakefile, or whatever controls your build, would have to run cpp to make a temporary files to feed the compiler. I have no idea if ant could be made to do this. </p>\n\n<p>While stackoverflow looks like it'll be <em>the</em> place for all answers, you could wehn no one's looking mosey on over to <a href=\"http://www.javaranch.com\" rel=\"nofollow noreferrer\">http://www.javaranch.com</a> for Java wisdom. I imagine this question has been dealt with there, prolly a long time ago.</p>\n" }, { "answer_id": 74268, "author": "Burkhard", "author_id": 12860, "author_profile": "https://Stackoverflow.com/users/12860", "pm_score": 0, "selected": false, "text": "<p>There is no pre-compiler in Java. Thus, no way to do a #ifdef like in C.\nBuild scripts would be the best way.</p>\n" }, { "answer_id": 74292, "author": "freespace", "author_id": 8297, "author_profile": "https://Stackoverflow.com/users/8297", "pm_score": 0, "selected": false, "text": "<p>You can get conditional compile, but not very nicely - javac will ignore unreachable code. Thus if you structured your code properly, you can get the compiler to ignore parts of your code. To use this properly, you would also need to pass the correct arguments to javac so it doesn't report unreachable code as errors, and refuse to compile :-)</p>\n" }, { "answer_id": 74319, "author": "Jesse Glick", "author_id": 12916, "author_profile": "https://Stackoverflow.com/users/12916", "pm_score": 2, "selected": false, "text": "<p>Keep one \"master\" source root that builds under JDK 5. Add a second parallel source root that has to build under JDK 6 or higher. (There should be no overlap, i.e. no classes present in both.) Use an interface to define the entry point between the two, and a tiny bit of reflection.</p>\n\n<p>For example:</p>\n\n<pre><code>---%&lt;--- main/RandomClass.java\n// ...\nif (...is JDK 6+...) {\n try {\n JDK6Interface i = (JDK6Interface)\n Class.forName(\"JDK6Impl\").newInstance();\n i.browseDesktop(...);\n } catch (Exception x) {\n // fall back...\n }\n}\n---%&lt;--- main/JDK6Interface.java\npublic interface JDK6Interface {\n void browseDesktop(URI uri);\n}\n---%&lt;--- jdk6/JDK6Impl.java\npublic class JDK6Impl implements JDK6Interface {\n public void browseDesktop(URI uri) {\n java.awt.Desktop.getDesktop().browse(uri);\n }\n}\n---%&lt;---\n</code></pre>\n\n<p>You could configure these as separate projects in an IDE using different JDKs, etc. The point is that the main root can be compiled independently and it is very clear what you can use in which root, whereas if you try to compile different parts of a single root separately it is too easy to accidentally \"leak\" usage of JDK 6 into the wrong files.</p>\n\n<p>Rather than using Class.forName like this, you can also use some kind of service registration system - java.util.ServiceLoader (if main could use JDK 6 and you wanted optional support for JDK 7!), NetBeans Lookup, Spring, etc. etc.</p>\n\n<p>The same technique can be used to create support for an optional library rather than a newer JDK.</p>\n" }, { "answer_id": 74366, "author": "Steve g", "author_id": 12092, "author_profile": "https://Stackoverflow.com/users/12092", "pm_score": 2, "selected": false, "text": "<p>You can probably refactor your code so that conditional compile really isn't needed, just conditional classloading. Something like this:</p>\n\n<pre><code>public interface Opener{\n\npublic void open(File f);\n\n public static class Util{\n public Opener getOpener(){\n if(System.getProperty(\"java.version\").beginsWith(\"1.5\")){\n return new Java5Opener();\n }\n try{ \n return new Java6Opener();\n }catch(Throwable t){\n return new Java5Opener();\n }\n }\n }\n\n}\n</code></pre>\n\n<p>This could be a lot of effort depending on how many version-specific pieces of code you have.</p>\n" }, { "answer_id": 74555, "author": "18Rabbit", "author_id": 12662, "author_profile": "https://Stackoverflow.com/users/12662", "pm_score": 3, "selected": true, "text": "<p>Assuming that the classes have similar functionality with 1.5 vs. 6.0 differences in implementation you could merge them into one class. Then, without editing the source to comment/uncomment, you can rely on the optimization that the compiler always do. If an if expression is always false, the code in the if statement will not be included in the compilation.</p>\n\n<p>You can make a static variable in one of your classes to determine which version you want to run:</p>\n\n<pre><code>public static final boolean COMPILED_IN_JAVA_6 = false;\n</code></pre>\n\n<p>And then have the affected classes check that static variable and put the different sections of code in a simple if statement</p>\n\n<pre><code>if (VersionUtil.COMPILED_IN_JAVA_6) {\n // Java 6 stuff goes here\n} else {\n // Java 1.5 stuff goes here\n}\n</code></pre>\n\n<p>Then when you want to compile the other version you just have to change that one variable and recompile. It might make the java file larger but it will consolidate your code and eliminate any code duplication that you have. Your editor may complain about unreachable code or whatever but the compiler should blissfully ignore it.</p>\n" }, { "answer_id": 74603, "author": "Bill K", "author_id": 12943, "author_profile": "https://Stackoverflow.com/users/12943", "pm_score": 0, "selected": false, "text": "<p>The public static final solution mentioned above has one additional benefit the author didn't mention--as I understand it, the compiler will recognize it at compile time and compile out any code that is within an if statement that refers to that final variable.</p>\n\n<p>So I think that's the exact solution you were looking for.</p>\n" }, { "answer_id": 74617, "author": "Garth Gilmour", "author_id": 2635682, "author_profile": "https://Stackoverflow.com/users/2635682", "pm_score": 0, "selected": false, "text": "<p>A simple solution could be:</p>\n\n<ul>\n<li>Place the divergent classes outside of your normal classpath.</li>\n<li>Write a simple custom classloader and install it in main as your default.</li>\n<li>For all classes apart from the 5/6 ones the cassloader can defer to its parent (the normal system classloader)</li>\n<li>For the 5/6 ones (which should be the only ones that cannot be found by the parent) it can decide which to use via the 'os.name' property or one of your own.</li>\n</ul>\n" }, { "answer_id": 76114, "author": "Michael Myers", "author_id": 13531, "author_profile": "https://Stackoverflow.com/users/13531", "pm_score": 1, "selected": false, "text": "<p>It depends on what Java 6 features you want to use. For a simple thing like adding row sorters to JTables, you can actually test at runtime:</p>\n\n<pre><code>private static final double javaVersion =\n Double.parseDouble(System.getProperty(\"java.version\").substring(0, 3));\nprivate static final boolean supportsRowSorter =\n (javaVersion &gt;= 1.6);\n\n//...\n\nif (supportsRowSorter) {\n myTable.setAutoCreateRowSorter(true);\n} else {\n // not supported\n}\n</code></pre>\n\n<p>This code must be compiled with Java 6, but can be run with any version (no new classes are referenced).</p>\n\n<p>EDIT: to be more correct, it will work with any version since 1.3 (according to <a href=\"http://java.sun.com/j2se/versioning_naming.html\" rel=\"nofollow noreferrer\" title=\"J2SE SDK/JRE Version String Naming Convention\">this page</a>).</p>\n" }, { "answer_id": 76276, "author": "Ian", "author_id": 4396, "author_profile": "https://Stackoverflow.com/users/4396", "pm_score": 3, "selected": false, "text": "<p>The suggestions about using custom class loaders and dynamically commented code are a bit incredulous when it comes to maintenance and the preservation of the sanity of whichever poor soul picks up the project after you shuffle to pastures new.</p>\n\n<p>The solution is easy. Pull the affected classes out into two separate, independent projects - make sure the package names are the same, and just compile into jars that you can then consume in your main project. If you keep the package names the same, and the method signatures the same, no problems - just drop whichever version of the jar you need into your deployment script. I would assume you run separate build scripts or have separate targets in the same script - ant and maven can both easily handle conditionally grabbing files and copying them.</p>\n" }, { "answer_id": 76951, "author": "shadit", "author_id": 9925, "author_profile": "https://Stackoverflow.com/users/9925", "pm_score": 1, "selected": false, "text": "<p>You can do all of your compiling exclusively on Java6 and then use System.getProperty(\"java.version\") to conditionally run either the Java5 or the Java6 code path.</p>\n\n<p>You can have Java6-only code in a class and the class will run fine on Java5 as long as the Java6-only code path is not executed.</p>\n\n<p>This is a trick that is used to write applets that will run on the ancient MSJVM all the way up to brand-new Java Plug-in JVMs.</p>\n" }, { "answer_id": 146035, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>You can use reflection API. put all your 1.5 code in one class and 1.6 api in another. In your ant script create two targets one for 1.5 that won't compile the 1.6 class and one for 1.6 that won't compile the class for 1.5. in your code check your java version and load the appropriate class using reflection that way javac won't complain about missing functions. This is how i can compile my MRJ(Mac Runtime for Java) applications on windows.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/74171", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12944/" ]
I maintain a Java Swing application. For backwards compatibility with java 5 (for Apple machines), we maintain two codebases, 1 using features from Java 6, another without those features. The code is largely the same, except for 3-4 classes that uses Java 6 features. I wish to just maintain 1 codebase. Is there a way during compilation, to get the Java 5 compiler to 'ignore' some parts of my code? I do not wish to simply comment/uncomment parts of my code, depending on the version of my java compiler.
Assuming that the classes have similar functionality with 1.5 vs. 6.0 differences in implementation you could merge them into one class. Then, without editing the source to comment/uncomment, you can rely on the optimization that the compiler always do. If an if expression is always false, the code in the if statement will not be included in the compilation. You can make a static variable in one of your classes to determine which version you want to run: ``` public static final boolean COMPILED_IN_JAVA_6 = false; ``` And then have the affected classes check that static variable and put the different sections of code in a simple if statement ``` if (VersionUtil.COMPILED_IN_JAVA_6) { // Java 6 stuff goes here } else { // Java 1.5 stuff goes here } ``` Then when you want to compile the other version you just have to change that one variable and recompile. It might make the java file larger but it will consolidate your code and eliminate any code duplication that you have. Your editor may complain about unreachable code or whatever but the compiler should blissfully ignore it.
74,188
<p>I've created a ListBox to display items in groups, where the groups are wrapped right to left when they can no longer fit within the height of the ListBox's panel. So, the groups would appear similar to this in the listbox, where each group's height is arbitrary (group 1, for instance, is twice as tall as group 2):</p> <pre><code>[ 1 ][ 3 ][ 5 ] [ ][ 4 ][ 6 ] [ 2 ][ ] </code></pre> <p>The following XAML works correctly in that it performs the wrapping, and allows the horizontal scroll bar to appear when the items run off the right side of the ListBox.</p> <pre><code>&lt;ListBox&gt; &lt;ListBox.ItemsPanel&gt; &lt;ItemsPanelTemplate&gt; &lt;StackPanel Orientation="Vertical"/&gt; &lt;/ItemsPanelTemplate&gt; &lt;/ListBox.ItemsPanel&gt; &lt;ListBox.GroupStyle&gt; &lt;ItemsPanelTemplate&gt; &lt;WrapPanel Orientation="Vertical" Height="{Binding Path=ActualHeight, RelativeSource={RelativeSource FindAncestor, AncestorLevel=1, AncestorType={x:Type ScrollContentPresenter}}}"/&gt; &lt;/ItemsPanelTemplate&gt; &lt;/ListBox.GroupStyle&gt; &lt;/ListBox&gt; </code></pre> <p>The problem occurs when a group of items is longer than the height of the WrapPanel. Instead of allowing the vertical scroll bar to appear to view the cutoff item group, the items in that group are simply clipped. I'm assuming that this is a side effect of the Height binding in the WrapPanel - the scrollbar thinks it does not have to enabled.</p> <p>Is there any way to enable the scrollbar, or another way around this issue that I'm not seeing?</p>
[ { "answer_id": 74235, "author": "dcstraw", "author_id": 10391, "author_profile": "https://Stackoverflow.com/users/10391", "pm_score": 0, "selected": false, "text": "<p>I would think that you are correct that it has to do with the binding. What happens when you remove the binding? With the binding are you trying to fill up at least the entire height of the list box? If so, consider binding to MinHeight instead, or try using the <code>VerticalAlignment</code> property.</p>\n" }, { "answer_id": 74306, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Thanks for answering, David.</p>\n\n<p>When the binding is <code>removed</code>, no wrapping occurs. The <strong>WrapPanel</strong> puts every group into a single vertical column.</p>\n\n<p>The binding is meant to force the WrapPanel to actually wrap. If no binding is set, the WrapPanel assumes the height is infinite and never wraps.</p>\n\n<p>Binding to <code>MinHeight</code> results in an empty listbox. I can see how the <code>VerticalAlignment</code> property could seem to be a solution, but alignment itself prevents any wrapping from occurring. When binding and alignment are used together, the alignment has no effect on the problem.</p>\n" }, { "answer_id": 74565, "author": "Abe Heidebrecht", "author_id": 9268, "author_profile": "https://Stackoverflow.com/users/9268", "pm_score": 2, "selected": false, "text": "<p>By setting the Height property on the WrapPanel to the height of the ScrollContentPresenter, it will never scroll vertically. However, if you remove that Binding, it will never wrap, since in the layout pass, it has infinite height to layout in. </p>\n\n<p>I would suggest creating your own panel class to get the behavior you want. Have a separate dependency property that you can bind the desired height to, so you can use that to calculate the target height in the measure and arrange steps. If any one child is taller than the desired height, use that child's height as the target height to calculate the wrapping.</p>\n\n<p>Here is an example panel to do this:</p>\n\n<pre><code>public class SmartWrapPanel : WrapPanel\n{\n /// &lt;summary&gt;\n /// Identifies the DesiredHeight dependency property\n /// &lt;/summary&gt;\n public static readonly DependencyProperty DesiredHeightProperty = DependencyProperty.Register(\n \"DesiredHeight\",\n typeof(double),\n typeof(SmartWrapPanel),\n new FrameworkPropertyMetadata(Double.NaN, \n FrameworkPropertyMetadataOptions.AffectsArrange |\n FrameworkPropertyMetadataOptions.AffectsMeasure));\n\n /// &lt;summary&gt;\n /// Gets or sets the height to attempt to be. If any child is taller than this, will use the child's height.\n /// &lt;/summary&gt;\n public double DesiredHeight\n {\n get { return (double)GetValue(DesiredHeightProperty); }\n set { SetValue(DesiredHeightProperty, value); }\n }\n\n protected override Size MeasureOverride(Size constraint)\n {\n Size ret = base.MeasureOverride(constraint);\n double h = ret.Height;\n\n if (!Double.IsNaN(DesiredHeight))\n {\n h = DesiredHeight;\n foreach (UIElement child in Children)\n {\n if (child.DesiredSize.Height &gt; h)\n h = child.DesiredSize.Height;\n }\n }\n\n return new Size(ret.Width, h);\n }\n\n protected override System.Windows.Size ArrangeOverride(Size finalSize)\n {\n double h = finalSize.Height;\n\n if (!Double.IsNaN(DesiredHeight))\n {\n h = DesiredHeight;\n foreach (UIElement child in Children)\n {\n if (child.DesiredSize.Height &gt; h)\n h = child.DesiredSize.Height;\n }\n }\n\n return base.ArrangeOverride(new Size(finalSize.Width, h));\n }\n}\n</code></pre>\n" }, { "answer_id": 82798, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Here is the slightly modified code - all credit given to Abe Heidebrecht, who previously posted it - that allows both horizontal and vertical scrolling. The only change is that the return value of MeasureOverride needs to be base.MeasureOverride(new Size(ret.width, h)).</p>\n\n<pre><code>// Original code : Abe Heidebrecht\npublic class SmartWrapPanel : WrapPanel\n{\n /// &lt;summary&gt;\n /// Identifies the DesiredHeight dependency property\n /// &lt;/summary&gt;\n public static readonly DependencyProperty DesiredHeightProperty = DependencyProperty.Register(\n \"DesiredHeight\",\n typeof(double),\n typeof(SmartWrapPanel),\n new FrameworkPropertyMetadata(Double.NaN, \n FrameworkPropertyMetadataOptions.AffectsArrange |\n FrameworkPropertyMetadataOptions.AffectsMeasure));\n\n /// &lt;summary&gt;\n /// Gets or sets the height to attempt to be. If any child is taller than this, will use the child's height.\n /// &lt;/summary&gt;\n public double DesiredHeight\n {\n get { return (double)GetValue(DesiredHeightProperty); }\n set { SetValue(DesiredHeightProperty, value); }\n }\n\n protected override Size MeasureOverride(Size constraint)\n {\n Size ret = base.MeasureOverride(constraint);\n double h = ret.Height;\n\n if (!Double.IsNaN(DesiredHeight))\n {\n h = DesiredHeight;\n foreach (UIElement child in Children)\n {\n if (child.DesiredSize.Height &gt; h)\n h = child.DesiredSize.Height;\n }\n }\n\n return base.MeasureOverride(new Size(ret.Width, h));\n }\n\n protected override System.Windows.Size ArrangeOverride(Size finalSize)\n {\n double h = finalSize.Height;\n\n if (!Double.IsNaN(DesiredHeight))\n {\n h = DesiredHeight;\n foreach (UIElement child in Children)\n {\n if (child.DesiredSize.Height &gt; h)\n h = child.DesiredSize.Height;\n }\n }\n\n return base.ArrangeOverride(new Size(finalSize.Width, h));\n }\n}\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/74188", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I've created a ListBox to display items in groups, where the groups are wrapped right to left when they can no longer fit within the height of the ListBox's panel. So, the groups would appear similar to this in the listbox, where each group's height is arbitrary (group 1, for instance, is twice as tall as group 2): ``` [ 1 ][ 3 ][ 5 ] [ ][ 4 ][ 6 ] [ 2 ][ ] ``` The following XAML works correctly in that it performs the wrapping, and allows the horizontal scroll bar to appear when the items run off the right side of the ListBox. ``` <ListBox> <ListBox.ItemsPanel> <ItemsPanelTemplate> <StackPanel Orientation="Vertical"/> </ItemsPanelTemplate> </ListBox.ItemsPanel> <ListBox.GroupStyle> <ItemsPanelTemplate> <WrapPanel Orientation="Vertical" Height="{Binding Path=ActualHeight, RelativeSource={RelativeSource FindAncestor, AncestorLevel=1, AncestorType={x:Type ScrollContentPresenter}}}"/> </ItemsPanelTemplate> </ListBox.GroupStyle> </ListBox> ``` The problem occurs when a group of items is longer than the height of the WrapPanel. Instead of allowing the vertical scroll bar to appear to view the cutoff item group, the items in that group are simply clipped. I'm assuming that this is a side effect of the Height binding in the WrapPanel - the scrollbar thinks it does not have to enabled. Is there any way to enable the scrollbar, or another way around this issue that I'm not seeing?
By setting the Height property on the WrapPanel to the height of the ScrollContentPresenter, it will never scroll vertically. However, if you remove that Binding, it will never wrap, since in the layout pass, it has infinite height to layout in. I would suggest creating your own panel class to get the behavior you want. Have a separate dependency property that you can bind the desired height to, so you can use that to calculate the target height in the measure and arrange steps. If any one child is taller than the desired height, use that child's height as the target height to calculate the wrapping. Here is an example panel to do this: ``` public class SmartWrapPanel : WrapPanel { /// <summary> /// Identifies the DesiredHeight dependency property /// </summary> public static readonly DependencyProperty DesiredHeightProperty = DependencyProperty.Register( "DesiredHeight", typeof(double), typeof(SmartWrapPanel), new FrameworkPropertyMetadata(Double.NaN, FrameworkPropertyMetadataOptions.AffectsArrange | FrameworkPropertyMetadataOptions.AffectsMeasure)); /// <summary> /// Gets or sets the height to attempt to be. If any child is taller than this, will use the child's height. /// </summary> public double DesiredHeight { get { return (double)GetValue(DesiredHeightProperty); } set { SetValue(DesiredHeightProperty, value); } } protected override Size MeasureOverride(Size constraint) { Size ret = base.MeasureOverride(constraint); double h = ret.Height; if (!Double.IsNaN(DesiredHeight)) { h = DesiredHeight; foreach (UIElement child in Children) { if (child.DesiredSize.Height > h) h = child.DesiredSize.Height; } } return new Size(ret.Width, h); } protected override System.Windows.Size ArrangeOverride(Size finalSize) { double h = finalSize.Height; if (!Double.IsNaN(DesiredHeight)) { h = DesiredHeight; foreach (UIElement child in Children) { if (child.DesiredSize.Height > h) h = child.DesiredSize.Height; } } return base.ArrangeOverride(new Size(finalSize.Width, h)); } } ```
74,206
<p>I have been playing with this for a while, but the closest I have gotten is a button that opens the <code>Paste Special</code> dialog box and requires another couple of mouse clicks to paste the contents of the clipboard as unformatted text. </p> <p>So often I am doing a <code>copy-paste</code> from a web site into a document where I don't want the additional baggage of the HTML formatting, it would be nice to be able to do this with a shortcut key or a toolbar button.</p>
[ { "answer_id": 74237, "author": "GSerg", "author_id": 11683, "author_profile": "https://Stackoverflow.com/users/11683", "pm_score": 4, "selected": true, "text": "<p>Make the button call the macro:</p>\n\n<pre><code>public sub PasteSpecialUnformatted()\n selection.pastespecial datatype:=wdpastetext\nend sub\n</code></pre>\n" }, { "answer_id": 74969, "author": "Mackaaij", "author_id": 13222, "author_profile": "https://Stackoverflow.com/users/13222", "pm_score": 0, "selected": false, "text": "<p>I use <a href=\"http://www.getfingertips.com/\" rel=\"nofollow noreferrer\">FingerTips</a> for this. By default it will make CTRL+W -> Paste Special. Furthermore it supports macro text and a lot of useful start-programs-quick things and some Microsoft Outlook tricks to support Getting Things Done.</p>\n" }, { "answer_id": 85696, "author": "Jon Schneider", "author_id": 12484, "author_profile": "https://Stackoverflow.com/users/12484", "pm_score": 2, "selected": false, "text": "<p>I would suggest using the <a href=\"http://www.stevemiller.net/puretext/\" rel=\"nofollow noreferrer\">PureText</a> lightweight utility application by Steve Miller for this.</p>\n\n<p>PureText runs in your system tray and listens on a global hotkey (which you can define -- I use Win+V) to perform a \"paste text sans formatting\" -- essentially the same operation as opening up an instance of notepad.exe, pasting into that, re-copying the resultant plain text, and then pasting into the actual target application.</p>\n\n<p>The advantage of this approach is that you'll be able to perform a \"paste text sans formatting\" in any of your applications, not just in Word.</p>\n\n<p>I first installed PureText a couple of years ago and have been using it heavily ever since; it has become a \"must-have\" utility application for me. Highly recommended.</p>\n" }, { "answer_id": 14869170, "author": "DaDecoder", "author_id": 2070998, "author_profile": "https://Stackoverflow.com/users/2070998", "pm_score": 0, "selected": false, "text": "<p>You can simply use Quick Access Panel in MS Word 2007 and later versions.</p>\n\n<p>It is very simple to add <a href=\"http://dadecoder.blogspot.in/2013/02/add-shortcut-buttons-in-ms-word-2007.html\" rel=\"nofollow\">Shortcut Buttons in MS Office</a></p>\n\n<p>And saves a lot of time for regular users. </p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/74206", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30018/" ]
I have been playing with this for a while, but the closest I have gotten is a button that opens the `Paste Special` dialog box and requires another couple of mouse clicks to paste the contents of the clipboard as unformatted text. So often I am doing a `copy-paste` from a web site into a document where I don't want the additional baggage of the HTML formatting, it would be nice to be able to do this with a shortcut key or a toolbar button.
Make the button call the macro: ``` public sub PasteSpecialUnformatted() selection.pastespecial datatype:=wdpastetext end sub ```
74,218
<p>Is there a way to restart the Rails app (e.g. when you've changed a plugin/config file) while Mongrel is running. Or alternatively quickly restart Mongrel. Mongrel gives these hints that you can but how do you do it?</p> <p>** Signals ready. TERM => stop. USR2 => restart. INT => stop (no restart).</p> <p>** Rails signals registered. HUP => reload (without restart). It might not work well.</p>
[ { "answer_id": 74241, "author": "Jan Krüger", "author_id": 12471, "author_profile": "https://Stackoverflow.com/users/12471", "pm_score": 2, "selected": false, "text": "<p>For example,</p>\n\n<pre><code>killall -USR2 mongrel_rails\n</code></pre>\n" }, { "answer_id": 74998, "author": "TonyLa", "author_id": 1295, "author_profile": "https://Stackoverflow.com/users/1295", "pm_score": 2, "selected": false, "text": "<p>in your rails home directory </p>\n\n<pre><code>mongrel_rails cluster::restart\n</code></pre>\n" }, { "answer_id": 75028, "author": "Lucas Oman", "author_id": 6726, "author_profile": "https://Stackoverflow.com/users/6726", "pm_score": 3, "selected": false, "text": "<p>You can add the -c option if the config for your app's cluster is elsewhere:</p>\n\n<pre><code>mongrel_rails cluster::restart -c /path/to/config\n</code></pre>\n" }, { "answer_id": 90316, "author": "Mike Berrow", "author_id": 17251, "author_profile": "https://Stackoverflow.com/users/17251", "pm_score": 3, "selected": false, "text": "<p>1st discover the current mongrel pid path with something like:</p>\n\n<blockquote>\n <p>>ps axf | fgrep mongrel</p>\n</blockquote>\n\n<p>you will see a process line like:</p>\n\n<p><strong>ruby /usr/lib64/ruby/gems/1.8/gems/swiftiply-0.6.1.1/bin/mongrel_rails start -p 3000 -a 0.0.0.0 -e development -P /home/xxyyzz/rails/myappname/tmp/pids/mongrel.pid -d</strong></p>\n\n<p>Take the '-P /home/xxyyzz/rails/myappname/tmp/pids/mongrel.pid' part and use it like this:</p>\n\n<blockquote>\n <p>>mongrel_rails restart -P /home/xxyyzz/rails/myappname/tmp/pids/mongrel.pid</p>\n</blockquote>\n\n<p><strong>Sending USR2 to Mongrel at PID 18481...Done.</strong></p>\n\n<p>I use this to recover from the dreaded \"Broken pipe\" to MySQL problem.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/74218", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6432/" ]
Is there a way to restart the Rails app (e.g. when you've changed a plugin/config file) while Mongrel is running. Or alternatively quickly restart Mongrel. Mongrel gives these hints that you can but how do you do it? \*\* Signals ready. TERM => stop. USR2 => restart. INT => stop (no restart). \*\* Rails signals registered. HUP => reload (without restart). It might not work well.
You can add the -c option if the config for your app's cluster is elsewhere: ``` mongrel_rails cluster::restart -c /path/to/config ```
74,248
<p>On a JSTL/JSP page, I have a java.util.Date object from my application. I need to find the day <em>after</em> the day specified by that object. I can use &lt;jsp:scriptlet&gt; to drop into Java and use java.util.Calendar to do the necessary calculations, but this feels clumsy and inelegant to me.</p> <p>Is there some way to use JSP or JSTL tags to achieve this end without having to switch into full-on Java, or is the latter the only way to accomplish this?</p>
[ { "answer_id": 74274, "author": "sirprize", "author_id": 12902, "author_profile": "https://Stackoverflow.com/users/12902", "pm_score": 2, "selected": false, "text": "<p>While this does not answer your initial question, you could perhaps eliminate the hassle of going through java.util.Calendar by doing this:</p>\n\n<pre><code>// Date d given\nd.setTime(d.getTime()+86400000);\n</code></pre>\n" }, { "answer_id": 74582, "author": "jodonnell", "author_id": 4223, "author_profile": "https://Stackoverflow.com/users/4223", "pm_score": 2, "selected": false, "text": "<p>You have to either use a scriptlet or write your own tag. For the record, using Calendar would look like this:</p>\n\n<pre><code>Calendar cal = Calendar.getInstance();\ncal.setTime (date);\ncal.add (Calendar.DATE, 1);\ndate = cal.getTime ();\n</code></pre>\n\n<p>Truly horrible.</p>\n" }, { "answer_id": 74619, "author": "Mark B", "author_id": 13070, "author_profile": "https://Stackoverflow.com/users/13070", "pm_score": 1, "selected": false, "text": "<p>Unfortunately there is no tag in the standard JSP/JSTL libraries that I know of that would allow you to do this date calculation.</p>\n\n<p>The simplest, and most inelegant, solution is to just use some scriptlet code to do the calculation. You've already stated that you think this is a clunky solution, and I agree with you. I would probably write a custom JSP taglib to get this if I were you.</p>\n" }, { "answer_id": 74646, "author": "ScArcher2", "author_id": 1310, "author_profile": "https://Stackoverflow.com/users/1310", "pm_score": 4, "selected": true, "text": "<p>I'm not a fan of putting java code in your jsp.</p>\n\n<p>I'd use a static method and a taglib to accomplish this.</p>\n\n<p>Just my idea though. There are many ways to solve this problem.</p>\n\n<pre><code>public static Date addDay(Date date){\n //TODO you may want to check for a null date and handle it.\n Calendar cal = Calendar.getInstance();\n cal.setTime (date);\n cal.add (Calendar.DATE, 1);\n return cal.getTime();\n}\n</code></pre>\n\n<p>functions.tld</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"UTF-8\" ?&gt;\n&lt;taglib 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 http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd\"\n version=\"2.0\"&gt;\n &lt;description&gt;functions library&lt;/description&gt;\n &lt;display-name&gt;functions&lt;/display-name&gt;\n &lt;tlib-version&gt;1.1&lt;/tlib-version&gt;\n &lt;short-name&gt;xfn&lt;/short-name&gt;\n &lt;uri&gt;http://yourdomain/functions.tld&lt;/uri&gt;\n &lt;function&gt;\n &lt;description&gt;\n Adds 1 day to a date.\n &lt;/description&gt;\n &lt;name&gt;addDay&lt;/name&gt;\n &lt;function-class&gt;Functions&lt;/function-class&gt;\n &lt;function-signature&gt;java.util.Date addDay(java.util.Date)&lt;/function-signature&gt;\n &lt;example&gt;\n ${xfn:addDay(date)}\n &lt;/example&gt;\n &lt;/function&gt;\n&lt;/taglib&gt;\n</code></pre>\n" }, { "answer_id": 76166, "author": "Mwanji Ezana", "author_id": 7288, "author_profile": "https://Stackoverflow.com/users/7288", "pm_score": 1, "selected": false, "text": "<p>In general, I think JSPs should not have data logic. They should get all the data they need to display from the Controller and all their logic should be about HOW the data is displayed, not WHAT is displayed. This is usually a lot simpler and a lot less code/XML than adding a custom tag.</p>\n\n<p>And if there isn't any re-use happening, is a tiny scriptlet really that much worse than the taglib XML?</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/74248", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2041950/" ]
On a JSTL/JSP page, I have a java.util.Date object from my application. I need to find the day *after* the day specified by that object. I can use <jsp:scriptlet> to drop into Java and use java.util.Calendar to do the necessary calculations, but this feels clumsy and inelegant to me. Is there some way to use JSP or JSTL tags to achieve this end without having to switch into full-on Java, or is the latter the only way to accomplish this?
I'm not a fan of putting java code in your jsp. I'd use a static method and a taglib to accomplish this. Just my idea though. There are many ways to solve this problem. ``` public static Date addDay(Date date){ //TODO you may want to check for a null date and handle it. Calendar cal = Calendar.getInstance(); cal.setTime (date); cal.add (Calendar.DATE, 1); return cal.getTime(); } ``` functions.tld ``` <?xml version="1.0" encoding="UTF-8" ?> <taglib xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd" version="2.0"> <description>functions library</description> <display-name>functions</display-name> <tlib-version>1.1</tlib-version> <short-name>xfn</short-name> <uri>http://yourdomain/functions.tld</uri> <function> <description> Adds 1 day to a date. </description> <name>addDay</name> <function-class>Functions</function-class> <function-signature>java.util.Date addDay(java.util.Date)</function-signature> <example> ${xfn:addDay(date)} </example> </function> </taglib> ```
74,266
<p>I have an ext combobox which uses a store to suggest values to a user as they type. </p> <p>An example of which can be found here: <a href="http://extjs.com/deploy/ext/examples/form/combos.html" rel="nofollow noreferrer">combobox example</a></p> <p>Is there a way of making it so the <strong>suggested text list</strong> is rendered to an element in the DOM. Please note I do not mean the "applyTo" config option, as this would render the whole control, including the textbox to the DOM element.</p>
[ { "answer_id": 74680, "author": "noah", "author_id": 12034, "author_profile": "https://Stackoverflow.com/users/12034", "pm_score": 0, "selected": false, "text": "<p>So clarify, you want the selected text to render somewhere besides directly below the text input. Correct?</p>\n\n<p>ComboBox is just a composite of <a href=\"http://extjs.com/deploy/dev/docs/?class=Ext.DataView\" rel=\"nofollow noreferrer\">Ext.DataView</a>, a text input, and an optional trigger button. There isn't an official option for what you want and hacking it to make it do what you want would be really painful. So, the easiest course of action (other than finding and using some other library with a component that does exactly what you want) is to build your own with the components above:</p>\n\n<ol>\n<li>Create a text box. You can use an <a href=\"http://extjs.com/deploy/dev/docs/?class=Ext.form.TextField\" rel=\"nofollow noreferrer\">Ext.form.TextField</a> if you want, and observe the keyup event.</li>\n<li>Create a DataView bound to your store, rendering to whatever DOM element you want. Depending on what you want, listen to the 'selectionchange' event and take whatever action you need to in response to the selection. e.g., setValue on an Ext.form.Hidden (or plain HTML input type=\"hidden\" element).</li>\n<li>In your keyup event listener, call the store's filter method (see <a href=\"http://extjs.com/deploy/dev/docs/?class=Ext.data.Store\" rel=\"nofollow noreferrer\">doc</a>), passing the field name and the value from the text field. e.g., store.filter('name',new RegEx(value+'.*'))</li>\n</ol>\n\n<p>It's a little more work, but it's a lot shorter than writing your own component from scratch or hacking the ComboBox to behave like you want.</p>\n" }, { "answer_id": 75619, "author": "Thevs", "author_id": 8559, "author_profile": "https://Stackoverflow.com/users/8559", "pm_score": 2, "selected": true, "text": "<p>You can use plugin for this, since you can call or even override private methods from within the plugin:</p>\n\n<pre><code>var suggested_text_plugin = {\n\n init: function(o) {\n\n o.onTypeAhead = function() {\n // Original code from the sources goes here:\n\n if(this.store.getCount() &gt; 0){\n var r = this.store.getAt(0);\n var newValue = r.data[this.displayField];\n var len = newValue.length;\n var selStart = this.getRawValue().length;\n if(selStart != len){\n this.setRawValue(newValue);\n this.selectText(selStart, newValue.length);\n }\n }\n\n // Your code to display newValue in DOM\n ......myDom.getEl().update(newValue);\n };\n }\n};\n\n\n// in combobox code:\n\nvar cb = new Ext.form.ComboBox({\n ....\n plugins: suggested_text_plugin,\n ....\n});\n</code></pre>\n\n<p>I think it's even possible to create a whole chain of methods, calling original method before or after yours, but I haven't tried this yet.</p>\n\n<p>Also, please don't push me hard for using non-standard plugin definition and invocation methodics (undocumented). It's just my way of seeing things.</p>\n\n<p>EDIT:</p>\n\n<p>I think the method chain could be implemented something like that (untested):</p>\n\n<pre><code>....\no.origTypeAhead = new Function(this.onTypeAhead.toSource());\n// or just\no.origTypeAhead = this.onTypeAhead;\n....\n\no.onTypeAhead = function() {\n // Call original\n this.origTypeAhead();\n // Display value into your DOM element\n ...myDom....\n};\n</code></pre>\n" }, { "answer_id": 81766, "author": "Chris James", "author_id": 3193, "author_profile": "https://Stackoverflow.com/users/3193", "pm_score": 0, "selected": false, "text": "<p>@Thevs</p>\n\n<p>I think you were on the right track. </p>\n\n<p>What I did was override the initList method of Combobox.</p>\n\n<pre><code> Ext.override(Ext.form.ComboBox, {\n initList : function(){\n</code></pre>\n\n<p>If you look at the code you can see the bit where it renders the list of suggestions to a dataview. So just set the apply to the dom element you want:</p>\n\n<pre><code> this.view = new Ext.DataView({\n //applyTo: this.innerList,\n applyTo: \"contentbox\",\n</code></pre>\n" }, { "answer_id": 83721, "author": "Thevs", "author_id": 8559, "author_profile": "https://Stackoverflow.com/users/8559", "pm_score": 0, "selected": false, "text": "<p>@qui</p>\n\n<p>Ok. I thought you want an extra DOM field (in addition to existing combo field).</p>\n\n<p>But your solution would override a method in the ComboBox class, isn't it? That would lead to all your combo-boxes would render to the same DOM. Using a plugin would override only one particular instance.</p>\n" }, { "answer_id": 85687, "author": "noah", "author_id": 12034, "author_profile": "https://Stackoverflow.com/users/12034", "pm_score": 1, "selected": false, "text": "<p>@qui</p>\n\n<p>Another thing to consider is that initList is not part of the API. That method could disappear or the behavior could change significantly in future releases of Ext. If you never plan on upgrading, then you don't need to worry.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/74266", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3193/" ]
I have an ext combobox which uses a store to suggest values to a user as they type. An example of which can be found here: [combobox example](http://extjs.com/deploy/ext/examples/form/combos.html) Is there a way of making it so the **suggested text list** is rendered to an element in the DOM. Please note I do not mean the "applyTo" config option, as this would render the whole control, including the textbox to the DOM element.
You can use plugin for this, since you can call or even override private methods from within the plugin: ``` var suggested_text_plugin = { init: function(o) { o.onTypeAhead = function() { // Original code from the sources goes here: if(this.store.getCount() > 0){ var r = this.store.getAt(0); var newValue = r.data[this.displayField]; var len = newValue.length; var selStart = this.getRawValue().length; if(selStart != len){ this.setRawValue(newValue); this.selectText(selStart, newValue.length); } } // Your code to display newValue in DOM ......myDom.getEl().update(newValue); }; } }; // in combobox code: var cb = new Ext.form.ComboBox({ .... plugins: suggested_text_plugin, .... }); ``` I think it's even possible to create a whole chain of methods, calling original method before or after yours, but I haven't tried this yet. Also, please don't push me hard for using non-standard plugin definition and invocation methodics (undocumented). It's just my way of seeing things. EDIT: I think the method chain could be implemented something like that (untested): ``` .... o.origTypeAhead = new Function(this.onTypeAhead.toSource()); // or just o.origTypeAhead = this.onTypeAhead; .... o.onTypeAhead = function() { // Call original this.origTypeAhead(); // Display value into your DOM element ...myDom.... }; ```
74,267
<p>I'm trying to script the shutdown of my VM Servers in a .bat. if one of the vmware-cmd commands fails (as the machine is already shutdown say), I'd like it to continue instead of bombing out.</p> <pre><code>c: cd "c:\Program Files\VMWare\VmWare Server" vmware-cmd C:\VMImages\TCVMDEVSQL01\TCVMDEVSQL01.vmx suspend soft -q vmware-cmd C:\VMImages\DevEnv\DevEnv\DevEnv.vmx suspend soft -q vmware-cmd C:\VMImages\DevEnv\TCVMDEV02\TCVMDEV02.vmx suspend soft =q robocopy c:\vmimages\ \\tcedilacie1tb\VMShare\DevEnvironmentBackups\ /mir /z /r:0 /w:0 vmware-cmd C:\VMImages\TCVMDEVSQL01\TCVMDEVSQL01.vmx start vmware-cmd C:\VMImages\DevEnv\DevEnv\DevEnv.vmx start vmware-cmd C:\VMImages\DevEnv\TCVMDEV02\TCVMDEV02.vmx start </code></pre>
[ { "answer_id": 74304, "author": "Jen A", "author_id": 12979, "author_profile": "https://Stackoverflow.com/users/12979", "pm_score": 2, "selected": false, "text": "<p>Have you tried using \"start (cmd)\" for each command you are executing?</p>\n" }, { "answer_id": 74314, "author": "Burkhard", "author_id": 12860, "author_profile": "https://Stackoverflow.com/users/12860", "pm_score": 0, "selected": false, "text": "<p>You could write a little Program that executes the command an returns a value (say -1 for an error). This value can then be used in your Batch-File.</p>\n" }, { "answer_id": 74321, "author": "chakrit", "author_id": 3055, "author_profile": "https://Stackoverflow.com/users/3055", "pm_score": 6, "selected": true, "text": "<p>Run it inside another command instance with <code>CMD /C</code></p>\n\n<pre><code>CMD /C vmware-cmd C:\\...\n</code></pre>\n\n<p>This should keep the original BAT files running.</p>\n" }, { "answer_id": 74376, "author": "bastos.sergio", "author_id": 12772, "author_profile": "https://Stackoverflow.com/users/12772", "pm_score": 0, "selected": false, "text": "<p>A batch file should continue executing, even if the previous command has generated an error. Perhaps, what you are seeying is the batch aborting due to some other error?</p>\n" }, { "answer_id": 74502, "author": "kenny", "author_id": 3225, "author_profile": "https://Stackoverflow.com/users/3225", "pm_score": 3, "selected": false, "text": "<p>If you are calling another batch file, you must use CALL batchfile.cmd</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/74267", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11538/" ]
I'm trying to script the shutdown of my VM Servers in a .bat. if one of the vmware-cmd commands fails (as the machine is already shutdown say), I'd like it to continue instead of bombing out. ``` c: cd "c:\Program Files\VMWare\VmWare Server" vmware-cmd C:\VMImages\TCVMDEVSQL01\TCVMDEVSQL01.vmx suspend soft -q vmware-cmd C:\VMImages\DevEnv\DevEnv\DevEnv.vmx suspend soft -q vmware-cmd C:\VMImages\DevEnv\TCVMDEV02\TCVMDEV02.vmx suspend soft =q robocopy c:\vmimages\ \\tcedilacie1tb\VMShare\DevEnvironmentBackups\ /mir /z /r:0 /w:0 vmware-cmd C:\VMImages\TCVMDEVSQL01\TCVMDEVSQL01.vmx start vmware-cmd C:\VMImages\DevEnv\DevEnv\DevEnv.vmx start vmware-cmd C:\VMImages\DevEnv\TCVMDEV02\TCVMDEV02.vmx start ```
Run it inside another command instance with `CMD /C` ``` CMD /C vmware-cmd C:\... ``` This should keep the original BAT files running.
74,350
<p>I'm trying to implement some drag and drop functionality for a material system being developed at my work. Part of this system includes a 'Material Library' which acts as a repository, divided into groups, of saved materials on the user's hard drive.</p> <p>As part of some UI polish, I was hoping to implement a 'highlight' type feature. When dragging and dropping, windows that you can legally drop a material onto will very subtly change color to improve feedback to the user that this is a valid action.</p> <p>I am changing the bar with 'Basic Materials' (Just a CWnd with a CStatic) from having a medium gray background when unhighlighed to a blue background when hovered over. It all works well, the OnDragEnter and OnDragExit messages seem robust and set a flag indicating the highlight status. Then in OnCtrlColor I do this:</p> <pre><code> if (!m_bHighlighted) { pDC-&gt;FillSolidRect(0, 0, m_SizeX, kGroupHeaderHeight, kBackgroundColour); } else { pDC-&gt;FillSolidRect(0, 0, m_SizeX, kGroupHeaderHeight, kHighlightedBackgroundColour); } </code></pre> <p>However, as you can see in the screenshot, the painting 'glitches' below the dragged object, leaving the original gray in place. It looks really ugly and basically spoils the whole effect.</p> <p>Is there any way I can get around this?</p>
[ { "answer_id": 74501, "author": "Andy", "author_id": 3857, "author_profile": "https://Stackoverflow.com/users/3857", "pm_score": 0, "selected": false, "text": "<p>It almost looks like the CStatic doesn't know that it needs to repaint itself, so the background color of the draggable object is left behind. Maybe try to invalidate the CStatic, and see if that helps at all?</p>\n" }, { "answer_id": 77701, "author": "Aidan Ryan", "author_id": 1042, "author_profile": "https://Stackoverflow.com/users/1042", "pm_score": 1, "selected": false, "text": "<p>Remote debugging is a godsend for debugging visual issues. It's a pain to set up, but having a VM ready for remote debugging will pay off for sure.</p>\n\n<p>What I like to do is set a ton of breakpoints in my paint handling, as well as in the framework paint code itself. This allows you to effectively \"freeze frame\" the painting without borking it up by flipping into devenv. This way you can get the true picture of who's painting in what order, and where you've got the chance to break in a fill that rect the way you need to.</p>\n" }, { "answer_id": 81662, "author": "Ali Parr", "author_id": 1169, "author_profile": "https://Stackoverflow.com/users/1169", "pm_score": 1, "selected": true, "text": "<p>Thanks for the answers guys, ajryan, you seem to always come up with help for my questions so extra thanks.</p>\n\n<p>Thankfully this time the answer was fairly straightforward....</p>\n\n<pre><code>ImageList_DragShowNolock(FALSE);\nm_pDragDropTargetWnd-&gt;SendMessage(WM_USER_DRAG_DROP_OBJECT_DRAG_ENTER, (WPARAM)pDragDropObject, (LPARAM)(&amp;dragDropPoint));\nImageList_DragShowNolock(TRUE);\n</code></pre>\n\n<p>This turns off the drawing of the dragged image, then sends a message to the window being entered to repaint in a highlighted state, then finally redraws the drag image over the top. Seems to have done the trick.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/74350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1169/" ]
I'm trying to implement some drag and drop functionality for a material system being developed at my work. Part of this system includes a 'Material Library' which acts as a repository, divided into groups, of saved materials on the user's hard drive. As part of some UI polish, I was hoping to implement a 'highlight' type feature. When dragging and dropping, windows that you can legally drop a material onto will very subtly change color to improve feedback to the user that this is a valid action. I am changing the bar with 'Basic Materials' (Just a CWnd with a CStatic) from having a medium gray background when unhighlighed to a blue background when hovered over. It all works well, the OnDragEnter and OnDragExit messages seem robust and set a flag indicating the highlight status. Then in OnCtrlColor I do this: ``` if (!m_bHighlighted) { pDC->FillSolidRect(0, 0, m_SizeX, kGroupHeaderHeight, kBackgroundColour); } else { pDC->FillSolidRect(0, 0, m_SizeX, kGroupHeaderHeight, kHighlightedBackgroundColour); } ``` However, as you can see in the screenshot, the painting 'glitches' below the dragged object, leaving the original gray in place. It looks really ugly and basically spoils the whole effect. Is there any way I can get around this?
Thanks for the answers guys, ajryan, you seem to always come up with help for my questions so extra thanks. Thankfully this time the answer was fairly straightforward.... ``` ImageList_DragShowNolock(FALSE); m_pDragDropTargetWnd->SendMessage(WM_USER_DRAG_DROP_OBJECT_DRAG_ENTER, (WPARAM)pDragDropObject, (LPARAM)(&dragDropPoint)); ImageList_DragShowNolock(TRUE); ``` This turns off the drawing of the dragged image, then sends a message to the window being entered to repaint in a highlighted state, then finally redraws the drag image over the top. Seems to have done the trick.
74,372
<p>I am involved in the process of porting a system containing several hundreds of ksh scripts from AIX, Solaris and HPUX to Linux. I have come across the following difference in the way ksh behaves on the two systems:</p> <pre><code>#!/bin/ksh flag=false echo "a\nb" | while read x do flag=true done echo "flag = ${flag}" exit 0 </code></pre> <p>On AIX, Solaris and HPUX the output is "flag = true" on Linux the output is "flag = false".</p> <p>My questions are:</p> <ul> <li>Is there an environment variable that I can set to get Linux's ksh to behave like the other Os's'? Failing that:</li> <li>Is there an option on Linux's ksh to get the required behavior? Failing that:</li> <li>Is there a ksh implementation available for Linux with the desired behavior?</li> </ul> <p>Other notes:</p> <ul> <li>On AIX, Solaris and HPUX ksh is a variant of ksh88.</li> <li>On Linux, ksh is the public domain ksh (pdksh)</li> <li>On AIX, Solaris and HPUX dtksh and ksh93 (where I have them installed) are consistent with ksh</li> <li>The Windows NT systems I have access to: Cygwin and MKS NT, are consistent with Linux.</li> <li>On AIX, Solaris and Linux, bash is consistent, giving the incorrect (from my perspective) result of "flag = false".</li> </ul> <p>The following table summarizes the systems the problem:</p> <pre><code>uname -s uname -r which ksh ksh version flag = ======== ======== ========= =========== ====== Linux 2.6.9-55.0.0.0.2.ELsmp /bin/ksh PD KSH v5.2.14 99/07/13.2 false AIX 3 /bin/ksh Version M-11/16/88f true // AIX 5.3 /bin/ksh93 Version M-12/28/93e true SunOS 5.8, 5.9 and 5.10 /bin/ksh Version M-11/16/88i true /usr/dt/bin/dtksh Version M-12/28/93d true HP-UX B.11.11 and B.11.23 /bin/ksh Version 11/16/88 true /usr/dt/bin/dtksh Version M-12/28/93d true CYGWIN_NT-5.1 1.5.25(0.156/4/2) /bin/ksh PD KSH v5.2.14 99/07/13.2 false Windows_NT 5 .../mksnt/ksh.exe Version 8.7.0 build 1859... false // MKS </code></pre> <h1>Update</h1> <p>After some advice from people in my company we decided to make the following modification to the code. This gives us the same result whether using the "real" ksh's (ksh88, ksh93) or any of the ksh clones (pdksh, MSK ksh). This also works correctly with bash.</p> <pre><code>#!/bin/ksh echo "a\nb" &gt; junk flag=false while read x do flag=true done &lt; junk echo "flag = ${flag}" exit 0 </code></pre> <p>Thanks to jj33 for the previously accepted answer.</p>
[ { "answer_id": 74421, "author": "zigdon", "author_id": 4913, "author_profile": "https://Stackoverflow.com/users/4913", "pm_score": 0, "selected": false, "text": "<p>I don't know of any particular option to force ksh to be compatible with a particular older version. That said, perhaps you could install a very old version of ksh on your linux box, and have it behave in a compatible manner?</p>\n\n<p>It might be easier to install a more modern version of amy shell on the AIX/HP-UX boxes, and just migrate your scripts to use sh. I know there are versions of bash available for all platforms.</p>\n" }, { "answer_id": 74446, "author": "jj33", "author_id": 430, "author_profile": "https://Stackoverflow.com/users/430", "pm_score": 3, "selected": false, "text": "<p>Instead of using pdksh on linux, use the \"real\" ksh from kornshell.org. pdksh is a blind re-implementation of ksh. kornshell.org is the original korn shell dating back 25 years or so (the one written by David Korn). AIX and Solaris use versions of the original ksh, so the kornshell.org version is usually feature- and bug- complete. Having cut my teeth with SunOS/Solaris, installing kornshell.org ksh is usually one of the first things I do on a new Linux box...</p>\n" }, { "answer_id": 74580, "author": "Alex M", "author_id": 9652, "author_profile": "https://Stackoverflow.com/users/9652", "pm_score": 0, "selected": false, "text": "<p>Your script gives the correct (true) output when <code>zsh</code> is used with the <code>emulate -L ksh</code> option. If all else fails you may wish to try using <code>zsh</code> on Linux.</p>\n" }, { "answer_id": 74787, "author": "jtimberman", "author_id": 7672, "author_profile": "https://Stackoverflow.com/users/7672", "pm_score": 1, "selected": false, "text": "<p>I installed 'ksh' and 'pdksh' on my local Ubuntu Hardy system. </p>\n\n<pre><code>ii ksh 93s+20071105-1 The real, AT&amp;T version of the Korn shell\nii pdksh 5.2.14-21ubunt A public domain version of the Korn shell\n</code></pre>\n\n<p>ksh has the \"correct\" behavior that you're expecting while pdksh does not. You might check your local Linux distribution's software repository for a \"real\" ksh, instead of using pdksh. The \"Real Unix\" OS's are going to install the AT&amp;T version of Korn shell, rather than pdksh, by default, what with them being based off AT&amp;T Unix (System V) :-).</p>\n" }, { "answer_id": 76858, "author": "szabgab", "author_id": 11827, "author_profile": "https://Stackoverflow.com/users/11827", "pm_score": 1, "selected": false, "text": "<p>Do you have to stay within ksh?</p>\n\n<p>Even if you use the same ksh you'll still call all kinds of external commands (grep, ps, cat, etc...) part of them will have different parameters and different output from system to system. Either you'll have to take in account those differences or use the GNU version of each one of them to make things the same.</p>\n\n<p>The <a href=\"http://www.perl.org/\" rel=\"nofollow noreferrer\">Perl</a> programming language originally was designed exactly to overcome this problem.\nIt includes all the features a unix shell programmer would want from he shell program but\nit is the same on every Unix system. You might not have the latest version on all those\nsystems, but if you need to install something, maybe it is better to install perl.</p>\n" }, { "answer_id": 95267, "author": "Andrew Stein", "author_id": 13029, "author_profile": "https://Stackoverflow.com/users/13029", "pm_score": 3, "selected": true, "text": "<p>After some advice from people in my company we decided to make the following modification to the code. This gives us the same result whether using the \"real\" ksh's (ksh88, ksh93) or any of the ksh clones (pdksh, MSK ksh). This also works correctly with bash.</p>\n\n<pre><code>#!/bin/ksh\necho \"a\\nb\" &gt; junk\nflag=false\nwhile read x\ndo\n flag=true\ndone &lt; junk\necho \"flag = ${flag}\"\nexit 0\n</code></pre>\n\n<p>Thanks to jj33 for the previous accepted answer.</p>\n" }, { "answer_id": 255217, "author": "mpez0", "author_id": 27898, "author_profile": "https://Stackoverflow.com/users/27898", "pm_score": 1, "selected": false, "text": "<p>The reason for the differences is whether the inside block is executed in the original shell context or in a subshell. You may be able to control this with the () and {} grouping commands. Using a temporary file, as you do in your update, will work most of the time but will run into problems if the script is run twice rapidly, or if it executes without clearing the file, etc.</p>\n\n<pre><code>#!/bin/ksh\nflag=false\necho \"a\\nb\" | { while read x\ndo \n flag=true\ndone }\necho \"flag = ${flag}\"\nexit 0\n</code></pre>\n\n<p>That may help with the problem you were getting on the Linux ksh. If you use parentheses instead of braces, you'll get the Linux behavior on the other ksh implementations.</p>\n" }, { "answer_id": 22537900, "author": "venkat", "author_id": 3442785, "author_profile": "https://Stackoverflow.com/users/3442785", "pm_score": 1, "selected": false, "text": "<p>Here is the another solution for echo \"\\n\" issue</p>\n\n<p><strong>Steps:</strong></p>\n\n<ol>\n<li>Find ksh package name</li>\n</ol>\n\n<p><code>$ rpm -qa --queryformat \"%{NAME}-%{VERSION}-%{RELEASE}(%{ARCH})\\n\" | grep \"ksh\"\nksh-20100621-19.el6_4.3(x86_64)</code></p>\n\n<ol>\n<li><p>uninstall ksh\n<code>$ sudo yum remove ksh-20100621-19.el6_4.3.x86_64</code></p></li>\n<li><p>down load pdksh-5.2.14-37.el5_8.1.x86_64.rpm (Please check OS for 32-bit or 64-bit and choose correct pkg)</p></li>\n<li><p>Install pdksh-5.2.14-37.el5_8.1.x86_64.rpm</p></li>\n</ol>\n\n<p><code>$ sudo yum -y install /SCRIPT_PATH/pdksh-5.2.14-37.el5_8.1.x86_64.rpm</code></p>\n\n<p><strong>Output before PDKSH install</strong></p>\n\n<pre><code>$ ora_db_start_stop.sh\n\\n==============\nUsage: START\n==============\\n\\n\n./ora_db_start_stop.sh START ALL \\n\nOR \\n\n./ora_db_start_stop.sh START ONE_OR_MORE \\n\n\\n==============\nUsage: STOP\n==============\\n\\n\n./ora_db_start_stop.sh STOP ALL \\n\nOR \\n\n./ora_db_start_stop.sh STOP ONE_OR_MORE \\n\\n\n</code></pre>\n\n<p><strong>After PDKSH install</strong></p>\n\n<p>==============</p>\n\n<h1>Usage: START</h1>\n\n<p><code>./ora_db_start_stop.sh START ALL</code></p>\n\n<p>OR</p>\n\n<p><code>./ora_db_start_stop.sh START ONE_OR_MORE</code></p>\n\n<p>==============</p>\n\n<h1>Usage: STOP</h1>\n\n<p><code>./ora_db_start_stop.sh STOP ALL</code></p>\n\n<p>OR</p>\n\n<p><code>./ora_db_start_stop.sh STOP ONE_OR_MORE</code></p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/74372", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13029/" ]
I am involved in the process of porting a system containing several hundreds of ksh scripts from AIX, Solaris and HPUX to Linux. I have come across the following difference in the way ksh behaves on the two systems: ``` #!/bin/ksh flag=false echo "a\nb" | while read x do flag=true done echo "flag = ${flag}" exit 0 ``` On AIX, Solaris and HPUX the output is "flag = true" on Linux the output is "flag = false". My questions are: * Is there an environment variable that I can set to get Linux's ksh to behave like the other Os's'? Failing that: * Is there an option on Linux's ksh to get the required behavior? Failing that: * Is there a ksh implementation available for Linux with the desired behavior? Other notes: * On AIX, Solaris and HPUX ksh is a variant of ksh88. * On Linux, ksh is the public domain ksh (pdksh) * On AIX, Solaris and HPUX dtksh and ksh93 (where I have them installed) are consistent with ksh * The Windows NT systems I have access to: Cygwin and MKS NT, are consistent with Linux. * On AIX, Solaris and Linux, bash is consistent, giving the incorrect (from my perspective) result of "flag = false". The following table summarizes the systems the problem: ``` uname -s uname -r which ksh ksh version flag = ======== ======== ========= =========== ====== Linux 2.6.9-55.0.0.0.2.ELsmp /bin/ksh PD KSH v5.2.14 99/07/13.2 false AIX 3 /bin/ksh Version M-11/16/88f true // AIX 5.3 /bin/ksh93 Version M-12/28/93e true SunOS 5.8, 5.9 and 5.10 /bin/ksh Version M-11/16/88i true /usr/dt/bin/dtksh Version M-12/28/93d true HP-UX B.11.11 and B.11.23 /bin/ksh Version 11/16/88 true /usr/dt/bin/dtksh Version M-12/28/93d true CYGWIN_NT-5.1 1.5.25(0.156/4/2) /bin/ksh PD KSH v5.2.14 99/07/13.2 false Windows_NT 5 .../mksnt/ksh.exe Version 8.7.0 build 1859... false // MKS ``` Update ====== After some advice from people in my company we decided to make the following modification to the code. This gives us the same result whether using the "real" ksh's (ksh88, ksh93) or any of the ksh clones (pdksh, MSK ksh). This also works correctly with bash. ``` #!/bin/ksh echo "a\nb" > junk flag=false while read x do flag=true done < junk echo "flag = ${flag}" exit 0 ``` Thanks to jj33 for the previously accepted answer.
After some advice from people in my company we decided to make the following modification to the code. This gives us the same result whether using the "real" ksh's (ksh88, ksh93) or any of the ksh clones (pdksh, MSK ksh). This also works correctly with bash. ``` #!/bin/ksh echo "a\nb" > junk flag=false while read x do flag=true done < junk echo "flag = ${flag}" exit 0 ``` Thanks to jj33 for the previous accepted answer.
74,385
<p>I need to convert a value which is in a <code>DateTime</code> variable into a <code>varchar</code> variable formatted as <code>yyyy-mm-dd</code> format (without time part).</p> <p>How do I do that?</p>
[ { "answer_id": 74394, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 8, "selected": false, "text": "<p>Try the following:</p>\n\n<pre><code>CONVERT(varchar(10), [MyDateTimecolumn], 20)\n</code></pre>\n\n<p>For a full date time and not just date do: </p>\n\n<pre><code>CONVERT(varchar(23), [MyDateTimecolumn], 121)\n</code></pre>\n\n<p>See this page for convert styles:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms187928.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/ms187928.aspx</a><br>\nOR<br>\n<a href=\"http://www.w3schools.com/sql/func_convert.asp\" rel=\"noreferrer\">SQL Server CONVERT() Function</a></p>\n" }, { "answer_id": 74404, "author": "Per Hornshøj-Schierbeck", "author_id": 11619, "author_profile": "https://Stackoverflow.com/users/11619", "pm_score": 3, "selected": false, "text": "<p>Either <code>Cast</code> or <code>Convert</code>:</p>\n\n<p>Syntax for <code>CAST</code>:</p>\n\n<pre><code>CAST ( expression AS data_type [ (length ) ])\n</code></pre>\n\n<p>Syntax for <code>CONVERT</code>:</p>\n\n<pre><code>CONVERT ( data_type [ ( length ) ] , expression [ , style ] )\n</code></pre>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms187928.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/ms187928.aspx</a></p>\n\n<p>Actually since you asked for a specific format:</p>\n\n<pre><code>REPLACE(CONVERT(varchar(10), Date, 102), '.', '-')\n</code></pre>\n" }, { "answer_id": 74431, "author": "Allan Wind", "author_id": 9706, "author_profile": "https://Stackoverflow.com/users/9706", "pm_score": 1, "selected": false, "text": "<p>You did not say which database, but with mysql here is an easy way to get a date from a timestamp (and the varchar type conversion should happen automatically):</p>\n\n<pre><code>mysql&gt; select date(now());\n+-------------+\n| date(now()) |\n+-------------+\n| 2008-09-16 | \n+-------------+\n1 row in set (0.00 sec)\n</code></pre>\n" }, { "answer_id": 74438, "author": "Amy Patterson", "author_id": 300930, "author_profile": "https://Stackoverflow.com/users/300930", "pm_score": 2, "selected": false, "text": "<p>Try the following:</p>\n\n<pre><code>CONVERT(VARCHAR(10),GetDate(),102)\n</code></pre>\n\n<p>Then you would need to replace the \".\" with \"-\".</p>\n\n<p>Here is a site that helps\n<a href=\"http://www.mssqltips.com/tip.asp?tip=1145\" rel=\"nofollow noreferrer\">http://www.mssqltips.com/tip.asp?tip=1145</a></p>\n" }, { "answer_id": 74469, "author": "TonyOssa", "author_id": 3276, "author_profile": "https://Stackoverflow.com/users/3276", "pm_score": 9, "selected": true, "text": "<p>With Microsoft Sql Server:</p>\n\n<pre><code>--\n-- Create test case\n--\nDECLARE @myDateTime DATETIME\nSET @myDateTime = '2008-05-03'\n\n--\n-- Convert string\n--\nSELECT LEFT(CONVERT(VARCHAR, @myDateTime, 120), 10)\n</code></pre>\n" }, { "answer_id": 74473, "author": "Johnny Bravado", "author_id": 12222, "author_profile": "https://Stackoverflow.com/users/12222", "pm_score": -1, "selected": false, "text": "<p>You don't say what language but I am assuming <code>C#/.NET</code> because it has a native <code>DateTime</code> data type. In that case just convert it using the <code>ToString</code> method and use a format specifier such as:</p>\n\n<pre><code>DateTime d = DateTime.Today;\nstring result = d.ToString(\"yyyy-MM-dd\");\n</code></pre>\n\n<p>However, I would caution against using this in a database query or concatenated into a SQL statement. Databases require a specific formatting string to be used. You are better off zeroing out the time part and using the DateTime as a SQL parameter if that is what you are trying to accomplish.</p>\n" }, { "answer_id": 138476, "author": "Andy Jones", "author_id": 5096, "author_profile": "https://Stackoverflow.com/users/5096", "pm_score": 2, "selected": false, "text": "<pre><code>declare @dt datetime\n\nset @dt = getdate()\n\nselect convert(char(10),@dt,120) \n</code></pre>\n\n<p>I have fixed data length of <code>char(10)</code> as you want a specific string format.</p>\n" }, { "answer_id": 6254392, "author": "Arek Bee", "author_id": 664252, "author_profile": "https://Stackoverflow.com/users/664252", "pm_score": 2, "selected": false, "text": "<p>Try:</p>\n\n<pre><code>select replace(convert(varchar, getdate(), 111),'/','-');\n</code></pre>\n\n<p>More on <a href=\"http://www.mssqltips.com/tip.asp?tip=1145\" rel=\"nofollow\">ms sql tips</a></p>\n" }, { "answer_id": 6430393, "author": "P's-SQL", "author_id": 809074, "author_profile": "https://Stackoverflow.com/users/809074", "pm_score": 3, "selected": false, "text": "<p>-- This gives you the time as 0 in format 'yyyy-mm-dd 00:00:00.000'</p>\n\n<pre><code>\nSELECT CAST( CONVERT(VARCHAR, GETDATE(), 101) AS DATETIME) ; \n</code></pre>\n" }, { "answer_id": 7040880, "author": "OldBuildingAndLoan", "author_id": 70870, "author_profile": "https://Stackoverflow.com/users/70870", "pm_score": 2, "selected": false, "text": "<p>The OP mentioned <strong>datetime</strong> format. For me, the time part gets in the way.<br>\nI think it's a bit cleaner to remove the time portion (by casting datetime to date) before formatting.</p>\n\n<pre><code>convert( varchar(10), convert( date, @yourDate ) , 111 )\n</code></pre>\n" }, { "answer_id": 10819689, "author": "dmunozpa", "author_id": 1017892, "author_profile": "https://Stackoverflow.com/users/1017892", "pm_score": 3, "selected": false, "text": "<p>With Microsoft SQL Server:</p>\n\n<p>Use Syntax for CONVERT:</p>\n\n<pre><code>CONVERT ( data_type [ ( length ) ] , expression [ , style ] )\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>SELECT CONVERT(varchar,d.dateValue,1-9)\n</code></pre>\n\n<p>For the style you can find more info here: <a href=\"http://msdn.microsoft.com/en-us/library/ms187928.aspx\" rel=\"noreferrer\">MSDN - Cast and Convert (Transact-SQL)</a>.</p>\n" }, { "answer_id": 11587309, "author": "FCKOE", "author_id": 1541843, "author_profile": "https://Stackoverflow.com/users/1541843", "pm_score": 3, "selected": false, "text": "<p>You can use <code>DATEPART(DATEPART, VARIABLE)</code>. For example:</p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>DECLARE @DAY INT \nDECLARE @MONTH INT\nDECLARE @YEAR INT\nDECLARE @DATE DATETIME\n@DATE = GETDATE()\nSELECT @DAY = DATEPART(DAY,@DATE)\nSELECT @MONTH = DATEPART(MONTH,@DATE)\nSELECT @YEAR = DATEPART(YEAR,@DATE)\n</code></pre>\n" }, { "answer_id": 15621120, "author": "IvanSnek", "author_id": 1899696, "author_profile": "https://Stackoverflow.com/users/1899696", "pm_score": 2, "selected": false, "text": "<p>This is how I do it: <code>CONVERT(NVARCHAR(10), DATE1, 103) )</code></p>\n" }, { "answer_id": 17713768, "author": "Zar Shardan", "author_id": 913845, "author_profile": "https://Stackoverflow.com/users/913845", "pm_score": 5, "selected": false, "text": "<p>SQL Server 2012 has a new function , FORMAT: \n<a href=\"http://msdn.microsoft.com/en-us/library/ee634924.aspx\">http://msdn.microsoft.com/en-us/library/ee634924.aspx</a></p>\n\n<p>and you can use custom date time format strings: <a href=\"http://msdn.microsoft.com/en-us/library/ee634398.aspx\">http://msdn.microsoft.com/en-us/library/ee634398.aspx</a></p>\n\n<p>These pages imply it is also available on SQL2008R2, but I don't have one handy to test if that's the case.</p>\n\n<p>Example usage (Australian datetime): </p>\n\n<pre><code>FORMAT(VALUE,'dd/MM/yyyy h:mm:ss tt')\n</code></pre>\n" }, { "answer_id": 19537658, "author": "Colin", "author_id": 150342, "author_profile": "https://Stackoverflow.com/users/150342", "pm_score": 9, "selected": false, "text": "<p>Here's some test sql for all the styles.</p>\n\n<pre><code>DECLARE @now datetime\nSET @now = GETDATE()\nselect convert(nvarchar(MAX), @now, 0) as output, 0 as style \nunion select convert(nvarchar(MAX), @now, 1), 1\nunion select convert(nvarchar(MAX), @now, 2), 2\nunion select convert(nvarchar(MAX), @now, 3), 3\nunion select convert(nvarchar(MAX), @now, 4), 4\nunion select convert(nvarchar(MAX), @now, 5), 5\nunion select convert(nvarchar(MAX), @now, 6), 6\nunion select convert(nvarchar(MAX), @now, 7), 7\nunion select convert(nvarchar(MAX), @now, 8), 8\nunion select convert(nvarchar(MAX), @now, 9), 9\nunion select convert(nvarchar(MAX), @now, 10), 10\nunion select convert(nvarchar(MAX), @now, 11), 11\nunion select convert(nvarchar(MAX), @now, 12), 12\nunion select convert(nvarchar(MAX), @now, 13), 13\nunion select convert(nvarchar(MAX), @now, 14), 14\n--15 to 19 not valid\nunion select convert(nvarchar(MAX), @now, 20), 20\nunion select convert(nvarchar(MAX), @now, 21), 21\nunion select convert(nvarchar(MAX), @now, 22), 22\nunion select convert(nvarchar(MAX), @now, 23), 23\nunion select convert(nvarchar(MAX), @now, 24), 24\nunion select convert(nvarchar(MAX), @now, 25), 25\n--26 to 99 not valid\nunion select convert(nvarchar(MAX), @now, 100), 100\nunion select convert(nvarchar(MAX), @now, 101), 101\nunion select convert(nvarchar(MAX), @now, 102), 102\nunion select convert(nvarchar(MAX), @now, 103), 103\nunion select convert(nvarchar(MAX), @now, 104), 104\nunion select convert(nvarchar(MAX), @now, 105), 105\nunion select convert(nvarchar(MAX), @now, 106), 106\nunion select convert(nvarchar(MAX), @now, 107), 107\nunion select convert(nvarchar(MAX), @now, 108), 108\nunion select convert(nvarchar(MAX), @now, 109), 109\nunion select convert(nvarchar(MAX), @now, 110), 110\nunion select convert(nvarchar(MAX), @now, 111), 111\nunion select convert(nvarchar(MAX), @now, 112), 112\nunion select convert(nvarchar(MAX), @now, 113), 113\nunion select convert(nvarchar(MAX), @now, 114), 114\nunion select convert(nvarchar(MAX), @now, 120), 120\nunion select convert(nvarchar(MAX), @now, 121), 121\n--122 to 125 not valid\nunion select convert(nvarchar(MAX), @now, 126), 126\nunion select convert(nvarchar(MAX), @now, 127), 127\n--128, 129 not valid\nunion select convert(nvarchar(MAX), @now, 130), 130\nunion select convert(nvarchar(MAX), @now, 131), 131\n--132 not valid\norder BY style\n</code></pre>\n\n<p>Here's the result</p>\n\n<pre><code>output style\nApr 28 2014 9:31AM 0\n04/28/14 1\n14.04.28 2\n28/04/14 3\n28.04.14 4\n28-04-14 5\n28 Apr 14 6\nApr 28, 14 7\n09:31:28 8\nApr 28 2014 9:31:28:580AM 9\n04-28-14 10\n14/04/28 11\n140428 12\n28 Apr 2014 09:31:28:580 13\n09:31:28:580 14\n2014-04-28 09:31:28 20\n2014-04-28 09:31:28.580 21\n04/28/14 9:31:28 AM 22\n2014-04-28 23\n09:31:28 24\n2014-04-28 09:31:28.580 25\nApr 28 2014 9:31AM 100\n04/28/2014 101\n2014.04.28 102\n28/04/2014 103\n28.04.2014 104\n28-04-2014 105\n28 Apr 2014 106\nApr 28, 2014 107\n09:31:28 108\nApr 28 2014 9:31:28:580AM 109\n04-28-2014 110\n2014/04/28 111\n20140428 112\n28 Apr 2014 09:31:28:580 113\n09:31:28:580 114\n2014-04-28 09:31:28 120\n2014-04-28 09:31:28.580 121\n2014-04-28T09:31:28.580 126\n2014-04-28T09:31:28.580 127\n28 جمادى الثانية 1435 9:31:28:580AM 130\n28/06/1435 9:31:28:580AM 131\n</code></pre>\n\n<p>Make <code>nvarchar(max)</code> shorter to trim the time. For example:</p>\n\n<pre><code>select convert(nvarchar(11), GETDATE(), 0)\nunion select convert(nvarchar(max), GETDATE(), 0)\n</code></pre>\n\n<p>outputs:</p>\n\n<pre><code>May 18 2018\nMay 18 2018 9:57AM\n</code></pre>\n" }, { "answer_id": 23369972, "author": "Gabriel", "author_id": 3112707, "author_profile": "https://Stackoverflow.com/users/3112707", "pm_score": 1, "selected": false, "text": "<pre><code>CONVERT(VARCHAR, GETDATE(), 23)\n</code></pre>\n" }, { "answer_id": 27231940, "author": "Konstantin", "author_id": 1665649, "author_profile": "https://Stackoverflow.com/users/1665649", "pm_score": 2, "selected": false, "text": "<p>The shortest and the simplest way is :</p>\n\n<pre><code>DECLARE @now AS DATETIME = GETDATE()\n\nSELECT CONVERT(VARCHAR, @now, 23)\n</code></pre>\n" }, { "answer_id": 41594909, "author": "Ema.H", "author_id": 2630447, "author_profile": "https://Stackoverflow.com/users/2630447", "pm_score": 2, "selected": false, "text": "<p>You can convert your date in many formats, the syntaxe is simple to use :</p>\n\n<pre><code>CONVERT('TheTypeYouWant', 'TheDateToConvert', 'TheCodeForFormating' * )\nCONVERT(NVARCHAR(10), DATE_OF_DAY, 103) =&gt; 15/09/2016\n</code></pre>\n\n<ul>\n<li>The code is an integer, here 3 is the third formating without century, if you want the century just change the code to 103.</li>\n</ul>\n\n<p><strong>In your case</strong>, i've just converted and restrict size by nvarchar(10) like this :</p>\n\n<pre><code>CONVERT(NVARCHAR(10), MY_DATE_TIME, 120) =&gt; 2016-09-15\n</code></pre>\n\n<p>See more at : <a href=\"http://www.w3schools.com/sql/func_convert.asp\" rel=\"nofollow noreferrer\">http://www.w3schools.com/sql/func_convert.asp</a></p>\n\n<p><strong>Another solution</strong> (if your date is a Datetime) is a simple <strong>CAST</strong> :</p>\n\n<pre><code>CAST(MY_DATE_TIME as DATE) =&gt; 2016-09-15\n</code></pre>\n" }, { "answer_id": 45005103, "author": "Dilkhush", "author_id": 7384154, "author_profile": "https://Stackoverflow.com/users/7384154", "pm_score": 2, "selected": false, "text": "<p>Try this SQL:</p>\n\n<pre><code>select REPLACE(CONVERT(VARCHAR(24),GETDATE(),103),'/','_') + '_'+ \n REPLACE(CONVERT(VARCHAR(24),GETDATE(),114),':','_')\n</code></pre>\n" }, { "answer_id": 53440678, "author": "Dilkhush", "author_id": 7384154, "author_profile": "https://Stackoverflow.com/users/7384154", "pm_score": 1, "selected": false, "text": "<pre><code>DECLARE @DateTime DATETIME\nSET @DateTime = '2018-11-23 10:03:23'\nSELECT CONVERT(VARCHAR(100),@DateTime,121 )\n</code></pre>\n" }, { "answer_id": 53486217, "author": "Peter Majko", "author_id": 4528229, "author_profile": "https://Stackoverflow.com/users/4528229", "pm_score": 2, "selected": false, "text": "<p>For SQL Server 2008+ You can use CONVERT and FORMAT together.</p>\n\n<p>For example, for European style (e.g. Germany) timestamp:</p>\n\n<pre><code>CONVERT(VARCHAR, FORMAT(GETDATE(), 'dd.MM.yyyy HH:mm:ss', 'de-DE'))\n</code></pre>\n" }, { "answer_id": 57322855, "author": "Beyhan", "author_id": 2599859, "author_profile": "https://Stackoverflow.com/users/2599859", "pm_score": 0, "selected": false, "text": "<p>Write a function</p>\n\n<pre><code>CREATE FUNCTION dbo.TO_SAP_DATETIME(@input datetime)\nRETURNS VARCHAR(14)\nAS BEGIN\n DECLARE @ret VARCHAR(14)\n SET @ret = COALESCE(SUBSTRING(REPLACE(REPLACE(REPLACE(CONVERT(VARCHAR(26), @input, 25),'-',''),' ',''),':',''),1,14),'00000000000000');\n RETURN @ret\nEND\n</code></pre>\n" }, { "answer_id": 61617060, "author": "Andres Galindo", "author_id": 13475919, "author_profile": "https://Stackoverflow.com/users/13475919", "pm_score": 1, "selected": false, "text": "<pre><code>select REPLACE(CONVERT(VARCHAR, FORMAT(GETDATE(), N'dd/MM/yyyy hh:mm:ss tt')),'.', '/')\n</code></pre>\n\n<p>will give <code>05/05/2020 10:41:05 AM</code> as a result</p>\n" }, { "answer_id": 67225951, "author": "Zain", "author_id": 4281423, "author_profile": "https://Stackoverflow.com/users/4281423", "pm_score": 0, "selected": false, "text": "<p>Simple use &quot;Convert&quot; and then use &quot;Format&quot; to get your desire date format</p>\n<pre><code>DECLARE @myDateTime DATETIME\nSET @myDateTime = '2008-05-03'\n\nSELECT FORMAT(CONVERT(date, @myDateTime ),'yyyy-MM-dd')\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/74385", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7604/" ]
I need to convert a value which is in a `DateTime` variable into a `varchar` variable formatted as `yyyy-mm-dd` format (without time part). How do I do that?
With Microsoft Sql Server: ``` -- -- Create test case -- DECLARE @myDateTime DATETIME SET @myDateTime = '2008-05-03' -- -- Convert string -- SELECT LEFT(CONVERT(VARCHAR, @myDateTime, 120), 10) ```
74,430
<p>I am trying to use the <code>import random</code> statement in python, but it doesn't appear to have any methods in it to use.</p> <p>Am I missing something?</p>
[ { "answer_id": 74445, "author": "jamuraa", "author_id": 9805, "author_profile": "https://Stackoverflow.com/users/9805", "pm_score": 2, "selected": false, "text": "<p>I think you need to give some more information. It's not really possible to answer why it's not working based on the information in the question. The basic documentation for random is at: \n<a href=\"https://docs.python.org/library/random.html\" rel=\"nofollow noreferrer\">https://docs.python.org/library/random.html</a></p>\n\n<p>You might check there. </p>\n" }, { "answer_id": 74459, "author": "Chris AtLee", "author_id": 4558, "author_profile": "https://Stackoverflow.com/users/4558", "pm_score": 0, "selected": false, "text": "<p>Can you post an example of what you're trying to do? It's not clear from your question what the actual problem is.</p>\n\n<p>Here's an example of how to use the random module:</p>\n\n<pre><code>import random\nprint random.randint(0,10)\n</code></pre>\n" }, { "answer_id": 74476, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 1, "selected": false, "text": "<pre><code>Python 2.5.2 (r252:60911, Jun 16 2008, 18:27:58)\n[GCC 3.3.4 (pre 3.3.5 20040809)] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n&gt;&gt;&gt; import random\n&gt;&gt;&gt; random.seed()\n&gt;&gt;&gt; dir(random)\n['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random', 'SG_MAGICCONST', 'SystemRandom', 'TWOPI', 'WichmannHill', '_BuiltinMethodType', '_MethodType', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '_acos', '_ceil', '_cos', '_e', '_exp', '_hexlify', '_inst', '_log', '_pi', '_random', '_sin', '_sqrt', '_test', '_test_generator', '_urandom', '_warn', 'betavariate', 'choice', 'expovariate', 'gammavariate', 'gauss', 'getrandbits', 'getstate', 'jumpahead', 'lognormvariate', 'normalvariate', 'paretovariate', 'randint', 'random', 'randrange', 'sample', 'seed', 'setstate', 'shuffle', 'uniform', 'vonmisesvariate', 'weibullvariate']\n&gt;&gt;&gt; random.randint(0,3)\n3\n&gt;&gt;&gt; random.randint(0,3)\n1\n&gt;&gt;&gt; \n</code></pre>\n" }, { "answer_id": 74485, "author": "Chris Bunch", "author_id": 422, "author_profile": "https://Stackoverflow.com/users/422", "pm_score": 0, "selected": false, "text": "<p>Seems to work fine for me. Check out the methods in the <a href=\"http://docs.python.org/lib/module-random.html\" rel=\"nofollow noreferrer\">official python documentation</a> for random:</p>\n\n<pre><code>&gt;&gt;&gt; import random\n&gt;&gt;&gt; random.random()\n0.69130806168332215\n&gt;&gt;&gt; random.uniform(1, 10)\n8.8384170917436293\n&gt;&gt;&gt; random.randint(1, 10)\n4\n</code></pre>\n" }, { "answer_id": 75360, "author": "Thomas Vander Stichele", "author_id": 2900, "author_profile": "https://Stackoverflow.com/users/2900", "pm_score": 0, "selected": false, "text": "<p>Works for me:</p>\n\n<pre><code>Python 2.5.1 (r251:54863, Jun 15 2008, 18:24:51) \n[GCC 4.3.0 20080428 (Red Hat 4.3.0-8)] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n&gt;&gt;&gt; import random\n&gt;&gt;&gt; brothers = ['larry', 'curly', 'moe']\n&gt;&gt;&gt; random.choice(brothers)\n'moe'\n&gt;&gt;&gt; random.choice(brothers)\n'curly'\n</code></pre>\n" }, { "answer_id": 75427, "author": "Jerry Hill", "author_id": 12773, "author_profile": "https://Stackoverflow.com/users/12773", "pm_score": 6, "selected": true, "text": "<p>You probably have a file named random.py or random.pyc in your working directory. That's shadowing the built-in random module. You need to rename random.py to something like my_random.py and/or remove the random.pyc file.</p>\n\n<p>To tell for sure what's going on, do this:</p>\n\n<pre><code>&gt;&gt;&gt; import random\n&gt;&gt;&gt; print random.__file__\n</code></pre>\n\n<p>That will show you exactly which file is being imported.</p>\n" }, { "answer_id": 76404, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 1, "selected": false, "text": "<p>If the script you are trying to run is itself called random.py, then you would have a naming conflict. Choose a different name for your script.</p>\n" }, { "answer_id": 78304, "author": "Johan Dahlin", "author_id": 14337, "author_profile": "https://Stackoverflow.com/users/14337", "pm_score": 2, "selected": false, "text": "<p>This is happening because you have a random.py file in the python search path, most likely the current directory.</p>\n\n<p>Python is searching for modules using sys.path, which normally includes the current directory before the standard site-packages, which contains the expected random.py.</p>\n\n<p>This is expected to be fixed in Python 3.0, so that you can't import modules from the current directory without using a special import syntax.</p>\n\n<p>Just remove the random.py + random.pyc in the directory you're running python from and it'll work fine.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/74430", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13050/" ]
I am trying to use the `import random` statement in python, but it doesn't appear to have any methods in it to use. Am I missing something?
You probably have a file named random.py or random.pyc in your working directory. That's shadowing the built-in random module. You need to rename random.py to something like my\_random.py and/or remove the random.pyc file. To tell for sure what's going on, do this: ``` >>> import random >>> print random.__file__ ``` That will show you exactly which file is being imported.
74,451
<p>Windows file system is case insensitive. How, given a file/folder name (e.g. "somefile"), I get the <em>actual</em> name of that file/folder (e.g. it should return "SomeFile" if Explorer displays it so)?</p> <p>Some ways I know, all of which seem quite backwards:</p> <ol> <li>Given the full path, search for each folder on the path (via FindFirstFile). This gives proper cased results of each folder. At the last step, search for the file itself.</li> <li>Get filename from handle (as in <a href="http://msdn.microsoft.com/en-us/library/aa366789(VS.85).aspx" rel="noreferrer">MSDN example</a>). This requires opening a file, creating file mapping, getting it's name, parsing device names etc. Pretty convoluted. And it does not work for folders or zero-size files.</li> </ol> <p>Am I missing some obvious WinAPI call? The simplest ones, like GetActualPathName() or GetFullPathName() return the name using casing that was passed in (e.g. returns "program files" if that was passed in, even if it should be "Program Files").</p> <p>I'm looking for a native solution (not .NET one).</p>
[ { "answer_id": 74563, "author": "bugmagnet", "author_id": 426, "author_profile": "https://Stackoverflow.com/users/426", "pm_score": 2, "selected": false, "text": "<p>Okay, this is VBScript, but even so I'd suggest using the Scripting.FileSystemObject object</p>\n\n<pre><code>Dim fso\nSet fso = CreateObject(\"Scripting.FileSystemObject\")\nDim f\nSet f = fso.GetFile(\"C:\\testfile.dat\") 'actually named \"testFILE.dAt\"\nwscript.echo f.Name\n</code></pre>\n\n<p>The response I get is from this snippet is </p>\n\n<pre><code>testFILE.dAt\n</code></pre>\n\n<p>Hope that at least points you in the right direction.</p>\n" }, { "answer_id": 74588, "author": "cspirz", "author_id": 8352, "author_profile": "https://Stackoverflow.com/users/8352", "pm_score": 2, "selected": false, "text": "<p>Have you tried using <a href=\"http://msdn.microsoft.com/en-us/library/bb762179(VS.85).aspx\" rel=\"nofollow noreferrer\">SHGetFileInfo?</a></p>\n" }, { "answer_id": 74589, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": -1, "selected": false, "text": "<p>After a quick test, <a href=\"http://msdn.microsoft.com/en-us/library/aa364980(VS.85).aspx\" rel=\"nofollow noreferrer\">GetLongPathName()</a> does what you want.</p>\n" }, { "answer_id": 81493, "author": "NeARAZ", "author_id": 6799, "author_profile": "https://Stackoverflow.com/users/6799", "pm_score": 4, "selected": true, "text": "<p>And hereby I answer my own question, based on <a href=\"https://stackoverflow.com/questions/74451/getting-actual-file-name-with-proper-casing-on-windows#74588\">original answer from <em>cspirz</em></a>.</p>\n\n<p>Here's a function that given absolute, relative or network path, will return the path with upper/lower case as it would be displayed on Windows. If some component of the path does not exist, it will return the passed in path from that point.</p>\n\n<p>It is quite involved because it tries to handle network paths and other edge cases. It operates on wide character strings and uses std::wstring. Yes, in theory Unicode TCHAR could be not the same as wchar_t; that is an exercise for the reader :)</p>\n\n<pre><code>std::wstring GetActualPathName( const wchar_t* path )\n{\n // This is quite involved, but the meat is SHGetFileInfo\n\n const wchar_t kSeparator = L'\\\\';\n\n // copy input string because we'll be temporary modifying it in place\n size_t length = wcslen(path);\n wchar_t buffer[MAX_PATH];\n memcpy( buffer, path, (length+1) * sizeof(path[0]) );\n\n size_t i = 0;\n\n std::wstring result;\n\n // for network paths (\\\\server\\share\\RestOfPath), getting the display\n // name mangles it into unusable form (e.g. \"\\\\server\\share\" turns\n // into \"share on server (server)\"). So detect this case and just skip\n // up to two path components\n if( length &gt;= 2 &amp;&amp; buffer[0] == kSeparator &amp;&amp; buffer[1] == kSeparator )\n {\n int skippedCount = 0;\n i = 2; // start after '\\\\'\n while( i &lt; length &amp;&amp; skippedCount &lt; 2 )\n {\n if( buffer[i] == kSeparator )\n ++skippedCount;\n ++i;\n }\n\n result.append( buffer, i );\n }\n // for drive names, just add it uppercased\n else if( length &gt;= 2 &amp;&amp; buffer[1] == L':' )\n {\n result += towupper(buffer[0]);\n result += L':';\n if( length &gt;= 3 &amp;&amp; buffer[2] == kSeparator )\n {\n result += kSeparator;\n i = 3; // start after drive, colon and separator\n }\n else\n {\n i = 2; // start after drive and colon\n }\n }\n\n size_t lastComponentStart = i;\n bool addSeparator = false;\n\n while( i &lt; length )\n {\n // skip until path separator\n while( i &lt; length &amp;&amp; buffer[i] != kSeparator )\n ++i;\n\n if( addSeparator )\n result += kSeparator;\n\n // if we found path separator, get real filename of this\n // last path name component\n bool foundSeparator = (i &lt; length);\n buffer[i] = 0;\n SHFILEINFOW info;\n\n // nuke the path separator so that we get real name of current path component\n info.szDisplayName[0] = 0;\n if( SHGetFileInfoW( buffer, 0, &amp;info, sizeof(info), SHGFI_DISPLAYNAME ) )\n {\n result += info.szDisplayName;\n }\n else\n {\n // most likely file does not exist.\n // So just append original path name component.\n result.append( buffer + lastComponentStart, i - lastComponentStart );\n }\n\n // restore path separator that we might have nuked before\n if( foundSeparator )\n buffer[i] = kSeparator;\n\n ++i;\n lastComponentStart = i;\n addSeparator = true;\n }\n\n return result;\n}\n</code></pre>\n\n<p>Again, thanks to cspirz for pointing me to SHGetFileInfo.</p>\n" }, { "answer_id": 5452625, "author": "sergioko", "author_id": 679366, "author_profile": "https://Stackoverflow.com/users/679366", "pm_score": 2, "selected": false, "text": "<p>There is another solution. First call GetShortPathName() and then GetLongPathName(). Guess what character case will be used then? ;-)</p>\n" }, { "answer_id": 32892823, "author": "Doub", "author_id": 67432, "author_profile": "https://Stackoverflow.com/users/67432", "pm_score": 0, "selected": false, "text": "<p><a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/aa364421(v=vs.85).aspx\" rel=\"nofollow\">FindFirstFileNameW</a> will work with a few drawbacks:</p>\n\n<ul>\n<li>it doesn't work on UNC paths</li>\n<li>it strips the drive letter so you need to add it back</li>\n<li>if there are more than one hard link to your file you need to identify the right one</li>\n</ul>\n" }, { "answer_id": 47353320, "author": "raymai97", "author_id": 1261956, "author_profile": "https://Stackoverflow.com/users/1261956", "pm_score": 1, "selected": false, "text": "<p>Just found that the <code>Scripting.FileSystemObject</code> suggested by @bugmagnet 10 years ago is a treasure. Unlike my old method, it works on Absolute Path, Relative Path, UNC Path and Very Long Path (path longer than <code>MAX_PATH</code>). Shame on me for not testing his method earlier.</p>\n\n<p>For future reference, I would like to present this code which can be compiled in both C and C++ mode. In C++ mode, the code will use STL and ATL. In C mode, you can clearly see how everything is working behind the scene.</p>\n\n<pre><code>#include &lt;Windows.h&gt;\n#include &lt;objbase.h&gt;\n#include &lt;conio.h&gt; // for _getch()\n\n#ifndef __cplusplus\n# include &lt;stdio.h&gt;\n\n#define SafeFree(p, fn) \\\n if (p) { fn(p); (p) = NULL; }\n\n#define SafeFreeCOM(p) \\\n if (p) { (p)-&gt;lpVtbl-&gt;Release(p); (p) = NULL; }\n\n\nstatic HRESULT CorrectPathCasing2(\n LPCWSTR const pszSrc, LPWSTR *ppszDst)\n{\n DWORD const clsCtx = CLSCTX_INPROC_SERVER;\n LCID const lcid = LOCALE_USER_DEFAULT;\n LPCWSTR const pszProgId = L\"Scripting.FileSystemObject\";\n LPCWSTR const pszMethod = L\"GetAbsolutePathName\";\n HRESULT hr = 0;\n CLSID clsid = { 0 };\n IDispatch *pDisp = NULL;\n DISPID dispid = 0;\n VARIANT vtSrc = { VT_BSTR };\n VARIANT vtDst = { VT_BSTR };\n DISPPARAMS params = { 0 };\n SIZE_T cbDst = 0;\n LPWSTR pszDst = NULL;\n\n // CoCreateInstance&lt;IDispatch&gt;(pszProgId, &amp;pDisp)\n\n hr = CLSIDFromProgID(pszProgId, &amp;clsid);\n if (FAILED(hr)) goto eof;\n\n hr = CoCreateInstance(&amp;clsid, NULL, clsCtx,\n &amp;IID_IDispatch, (void**)&amp;pDisp);\n if (FAILED(hr)) goto eof;\n if (!pDisp) {\n hr = E_UNEXPECTED; goto eof;\n }\n\n // Variant&lt;BSTR&gt; vtSrc(pszSrc), vtDst;\n // vtDst = pDisp-&gt;InvokeMethod( pDisp-&gt;GetIDOfName(pszMethod), vtSrc );\n\n hr = pDisp-&gt;lpVtbl-&gt;GetIDsOfNames(pDisp, NULL,\n (LPOLESTR*)&amp;pszMethod, 1, lcid, &amp;dispid);\n if (FAILED(hr)) goto eof;\n\n vtSrc.bstrVal = SysAllocString(pszSrc);\n if (!vtSrc.bstrVal) {\n hr = E_OUTOFMEMORY; goto eof;\n }\n params.rgvarg = &amp;vtSrc;\n params.cArgs = 1;\n hr = pDisp-&gt;lpVtbl-&gt;Invoke(pDisp, dispid, NULL, lcid,\n DISPATCH_METHOD, &amp;params, &amp;vtDst, NULL, NULL);\n if (FAILED(hr)) goto eof;\n if (!vtDst.bstrVal) {\n hr = E_UNEXPECTED; goto eof;\n }\n\n // *ppszDst = AllocWStrCopyBStrFrom(vtDst.bstrVal);\n\n cbDst = SysStringByteLen(vtDst.bstrVal);\n pszDst = HeapAlloc(GetProcessHeap(),\n HEAP_ZERO_MEMORY, cbDst + sizeof(WCHAR));\n if (!pszDst) {\n hr = E_OUTOFMEMORY; goto eof;\n }\n CopyMemory(pszDst, vtDst.bstrVal, cbDst);\n *ppszDst = pszDst;\n\neof:\n SafeFree(vtDst.bstrVal, SysFreeString);\n SafeFree(vtSrc.bstrVal, SysFreeString);\n SafeFreeCOM(pDisp);\n return hr;\n}\n\nstatic void Cout(char const *psz)\n{\n printf(\"%s\", psz);\n}\n\nstatic void CoutErr(HRESULT hr)\n{\n printf(\"Error HRESULT 0x%.8X!\\n\", hr);\n}\n\nstatic void Test(LPCWSTR pszPath)\n{\n LPWSTR pszRet = NULL;\n HRESULT hr = CorrectPathCasing2(pszPath, &amp;pszRet);\n if (FAILED(hr)) {\n wprintf(L\"Input: &lt;%s&gt;\\n\", pszPath);\n CoutErr(hr);\n }\n else {\n wprintf(L\"Was: &lt;%s&gt;\\nNow: &lt;%s&gt;\\n\", pszPath, pszRet);\n HeapFree(GetProcessHeap(), 0, pszRet);\n }\n}\n\n\n#else // Use C++ STL and ATL\n# include &lt;iostream&gt;\n# include &lt;iomanip&gt;\n# include &lt;string&gt;\n# include &lt;atlbase.h&gt;\n\nstatic HRESULT CorrectPathCasing2(\n std::wstring const &amp;srcPath,\n std::wstring &amp;dstPath)\n{\n HRESULT hr = 0;\n CComPtr&lt;IDispatch&gt; disp;\n hr = disp.CoCreateInstance(L\"Scripting.FileSystemObject\");\n if (FAILED(hr)) return hr;\n\n CComVariant src(srcPath.c_str()), dst;\n hr = disp.Invoke1(L\"GetAbsolutePathName\", &amp;src, &amp;dst);\n if (FAILED(hr)) return hr;\n\n SIZE_T cch = SysStringLen(dst.bstrVal);\n dstPath = std::wstring(dst.bstrVal, cch);\n return hr;\n}\n\nstatic void Cout(char const *psz)\n{\n std::cout &lt;&lt; psz;\n}\n\nstatic void CoutErr(HRESULT hr)\n{\n std::wcout\n &lt;&lt; std::hex &lt;&lt; std::setfill(L'0') &lt;&lt; std::setw(8)\n &lt;&lt; \"Error HRESULT 0x\" &lt;&lt; hr &lt;&lt; \"\\n\";\n}\n\nstatic void Test(std::wstring const &amp;path)\n{\n std::wstring output;\n HRESULT hr = CorrectPathCasing2(path, output);\n if (FAILED(hr)) {\n std::wcout &lt;&lt; L\"Input: &lt;\" &lt;&lt; path &lt;&lt; \"&gt;\\n\";\n CoutErr(hr);\n }\n else {\n std::wcout &lt;&lt; L\"Was: &lt;\" &lt;&lt; path &lt;&lt; \"&gt;\\n\"\n &lt;&lt; \"Now: &lt;\" &lt;&lt; output &lt;&lt; \"&gt;\\n\";\n }\n}\n\n#endif\n\n\nstatic void TestRoutine(void)\n{\n HRESULT hr = CoInitialize(NULL);\n\n if (FAILED(hr)) {\n Cout(\"CoInitialize failed!\\n\");\n CoutErr(hr);\n return;\n }\n\n Cout(\"\\n[ Absolute Path ]\\n\");\n Test(L\"c:\\\\uSers\\\\RayMai\\\\docuMENTs\");\n Test(L\"C:\\\\WINDOWS\\\\SYSTEM32\");\n\n Cout(\"\\n[ Relative Path ]\\n\");\n Test(L\".\");\n Test(L\"..\");\n Test(L\"\\\\\");\n\n Cout(\"\\n[ UNC Path ]\\n\");\n Test(L\"\\\\\\\\VMWARE-HOST\\\\SHARED FOLDERS\\\\D\\\\PROGRAMS INSTALLER\");\n\n Cout(\"\\n[ Very Long Path ]\\n\");\n Test(L\"\\\\\\\\?\\\\C:\\\\VERYVERYVERYLOOOOOOOONGFOLDERNAME\\\\\"\n L\"VERYVERYVERYLOOOOOOOONGFOLDERNAME\\\\\"\n L\"VERYVERYVERYLOOOOOOOONGFOLDERNAME\\\\\"\n L\"VERYVERYVERYLOOOOOOOONGFOLDERNAME\\\\\"\n L\"VERYVERYVERYLOOOOOOOONGFOLDERNAME\\\\\"\n L\"VERYVERYVERYLOOOOOOOONGFOLDERNAME\\\\\"\n L\"VERYVERYVERYLOOOOOOOONGFOLDERNAME\\\\\"\n L\"VERYVERYVERYLOOOOOOOONGFOLDERNAME\\\\\"\n L\"VERYVERYVERYLOOOOOOOONGFOLDERNAME\");\n\n Cout(\"\\n!! Worth Nothing Behavior !!\\n\");\n Test(L\"\");\n Test(L\"1234notexist\");\n Test(L\"C:\\\\bad\\\\PATH\");\n\n CoUninitialize();\n}\n\nint main(void)\n{\n TestRoutine();\n _getch();\n return 0;\n}\n</code></pre>\n\n<p>Screenshot:</p>\n\n<p><a href=\"https://i.stack.imgur.com/goDre.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/goDre.png\" alt=\"screenshot2\"></a></p>\n\n<hr>\n\n<p>Old Answer:</p>\n\n<p>I found that <code>FindFirstFile()</code> will return the proper casing file name (last part of path) in <code>fd.cFileName</code>. If we pass <code>c:\\winDOWs\\exPLORER.exe</code> as first parameter to <code>FindFirstFile()</code>, the <code>fd.cFileName</code> would be <code>explorer.exe</code> like this:</p>\n\n<p><a href=\"https://i.stack.imgur.com/3ihE5.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/3ihE5.png\" alt=\"prove\"></a></p>\n\n<p>If we replace the last part of path with <code>fd.cFileName</code>, we will get the last part right; the path would become <code>c:\\winDOWs\\explorer.exe</code>.</p>\n\n<p>Assuming the path is always absolute path (no change in text length), we can just apply this 'algorithm' to every part of path (except the drive letter part). </p>\n\n<p>Talk is cheap, here is the code:</p>\n\n<pre><code>#include &lt;windows.h&gt;\n#include &lt;stdio.h&gt;\n\n/*\n c:\\windows\\windowsupdate.log --&gt; c:\\windows\\WindowsUpdate.log\n*/\nstatic HRESULT MyProcessLastPart(LPTSTR szPath)\n{\n HRESULT hr = 0;\n HANDLE hFind = NULL;\n WIN32_FIND_DATA fd = {0};\n TCHAR *p = NULL, *q = NULL;\n /* thePart = GetCorrectCasingFileName(thePath); */\n hFind = FindFirstFile(szPath, &amp;fd);\n if (hFind == INVALID_HANDLE_VALUE) {\n hr = HRESULT_FROM_WIN32(GetLastError());\n hFind = NULL; goto eof;\n }\n /* thePath = thePath.ReplaceLast(thePart); */\n for (p = szPath; *p; ++p);\n for (q = fd.cFileName; *q; ++q, --p);\n for (q = fd.cFileName; *p = *q; ++p, ++q);\neof:\n if (hFind) { FindClose(hFind); }\n return hr;\n}\n\n/*\n Important! 'szPath' should be absolute path only.\n MUST NOT SPECIFY relative path or UNC or short file name.\n*/\nEXTERN_C\nHRESULT __stdcall\nCorrectPathCasing(\n LPTSTR szPath)\n{\n HRESULT hr = 0;\n TCHAR *p = NULL;\n if (GetFileAttributes(szPath) == -1) {\n hr = HRESULT_FROM_WIN32(GetLastError()); goto eof;\n }\n for (p = szPath; *p; ++p)\n {\n if (*p == '\\\\' || *p == '/')\n {\n TCHAR slashChar = *p;\n if (p[-1] == ':') /* p[-2] is drive letter */\n {\n p[-2] = toupper(p[-2]);\n continue;\n }\n *p = '\\0';\n hr = MyProcessLastPart(szPath);\n *p = slashChar;\n if (FAILED(hr)) goto eof;\n }\n }\n hr = MyProcessLastPart(szPath);\neof:\n return hr;\n}\n\nint main()\n{\n TCHAR szPath[] = TEXT(\"c:\\\\windows\\\\EXPLORER.exe\");\n HRESULT hr = CorrectPathCasing(szPath);\n if (SUCCEEDED(hr))\n {\n MessageBox(NULL, szPath, TEXT(\"Test\"), MB_ICONINFORMATION);\n }\n return 0;\n}\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/vYAcH.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/vYAcH.png\" alt=\"prove 2\"></a></p>\n\n<p>Advantages:</p>\n\n<ul>\n<li>The code works on every version of Windows since Windows 95.</li>\n<li>Basic error-handling.</li>\n<li>Highest performance possible. <code>FindFirstFile()</code> is very fast, direct buffer manipulation makes it even faster.</li>\n<li>Just C and pure WinAPI. Small executable size.</li>\n</ul>\n\n<p>Disadvantages:</p>\n\n<ul>\n<li>Only absolute path is supported, other are undefined behavior.</li>\n<li>Not sure if it is relying on undocumented behavior.</li>\n<li>The code might be too raw too much DIY for some people. Might get you flamed.</li>\n</ul>\n\n<p>Reason behind the code style:</p>\n\n<p>I use <code>goto</code> for error-handling because I was used to it (<code>goto</code> is very handy for error-handling in C). I use <code>for</code> loop to perform functions like <code>strcpy</code> and <code>strchr</code> on-the-fly because I want to be certain what was actually executed.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/74451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6799/" ]
Windows file system is case insensitive. How, given a file/folder name (e.g. "somefile"), I get the *actual* name of that file/folder (e.g. it should return "SomeFile" if Explorer displays it so)? Some ways I know, all of which seem quite backwards: 1. Given the full path, search for each folder on the path (via FindFirstFile). This gives proper cased results of each folder. At the last step, search for the file itself. 2. Get filename from handle (as in [MSDN example](http://msdn.microsoft.com/en-us/library/aa366789(VS.85).aspx)). This requires opening a file, creating file mapping, getting it's name, parsing device names etc. Pretty convoluted. And it does not work for folders or zero-size files. Am I missing some obvious WinAPI call? The simplest ones, like GetActualPathName() or GetFullPathName() return the name using casing that was passed in (e.g. returns "program files" if that was passed in, even if it should be "Program Files"). I'm looking for a native solution (not .NET one).
And hereby I answer my own question, based on [original answer from *cspirz*](https://stackoverflow.com/questions/74451/getting-actual-file-name-with-proper-casing-on-windows#74588). Here's a function that given absolute, relative or network path, will return the path with upper/lower case as it would be displayed on Windows. If some component of the path does not exist, it will return the passed in path from that point. It is quite involved because it tries to handle network paths and other edge cases. It operates on wide character strings and uses std::wstring. Yes, in theory Unicode TCHAR could be not the same as wchar\_t; that is an exercise for the reader :) ``` std::wstring GetActualPathName( const wchar_t* path ) { // This is quite involved, but the meat is SHGetFileInfo const wchar_t kSeparator = L'\\'; // copy input string because we'll be temporary modifying it in place size_t length = wcslen(path); wchar_t buffer[MAX_PATH]; memcpy( buffer, path, (length+1) * sizeof(path[0]) ); size_t i = 0; std::wstring result; // for network paths (\\server\share\RestOfPath), getting the display // name mangles it into unusable form (e.g. "\\server\share" turns // into "share on server (server)"). So detect this case and just skip // up to two path components if( length >= 2 && buffer[0] == kSeparator && buffer[1] == kSeparator ) { int skippedCount = 0; i = 2; // start after '\\' while( i < length && skippedCount < 2 ) { if( buffer[i] == kSeparator ) ++skippedCount; ++i; } result.append( buffer, i ); } // for drive names, just add it uppercased else if( length >= 2 && buffer[1] == L':' ) { result += towupper(buffer[0]); result += L':'; if( length >= 3 && buffer[2] == kSeparator ) { result += kSeparator; i = 3; // start after drive, colon and separator } else { i = 2; // start after drive and colon } } size_t lastComponentStart = i; bool addSeparator = false; while( i < length ) { // skip until path separator while( i < length && buffer[i] != kSeparator ) ++i; if( addSeparator ) result += kSeparator; // if we found path separator, get real filename of this // last path name component bool foundSeparator = (i < length); buffer[i] = 0; SHFILEINFOW info; // nuke the path separator so that we get real name of current path component info.szDisplayName[0] = 0; if( SHGetFileInfoW( buffer, 0, &info, sizeof(info), SHGFI_DISPLAYNAME ) ) { result += info.szDisplayName; } else { // most likely file does not exist. // So just append original path name component. result.append( buffer + lastComponentStart, i - lastComponentStart ); } // restore path separator that we might have nuked before if( foundSeparator ) buffer[i] = kSeparator; ++i; lastComponentStart = i; addSeparator = true; } return result; } ``` Again, thanks to cspirz for pointing me to SHGetFileInfo.
74,461
<p>I'm currently playing with the Silverlight(Beta 2) Datagrid control. Before I wired up the SelectionChanged event, the grid would sort perfectly by clicking on the header. Now, when the grid is clicked, it will fire the SelectionChanged event when I click the header to sort. Is there any way around this?</p> <p>In a semi-related topic, I'd like to have the SelectionChanged event fire when I click on an already selected item (so that I can have a pop-up occur to allow the user to edit the selected value). Right now, you have to click on a different value and then back to the value you wanted in order for it to pop up. Is there another way? </p> <p>Included is my code. </p> <p>The Page:</p> <pre><code>&lt;UserControl x:Class="WebServicesApp.Page" xmlns="http://schemas.microsoft.com/client/2007" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data" Width="1280" Height="1024" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d"&gt; &lt;Grid x:Name="LayoutRoot" Background="White"&gt; &lt;Grid.RowDefinitions&gt; &lt;RowDefinition /&gt; &lt;RowDefinition /&gt; &lt;/Grid.RowDefinitions&gt; &lt;StackPanel Grid.Row="0" x:Name="OurStack" Orientation="Vertical" Margin="5,5,5,5"&gt; &lt;ContentControl VerticalAlignment="Center" HorizontalAlignment="Center"&gt; &lt;StackPanel x:Name="SearchStackPanel" Orientation="Horizontal" Margin="5,5,5,5"&gt; &lt;TextBlock x:Name="SearchEmail" HorizontalAlignment="Stretch" VerticalAlignment="Center" Text="Email Address:" Margin="5,5,5,5" /&gt; &lt;TextBox x:Name="InputText" HorizontalAlignment="Stretch" VerticalAlignment="Center" Width="150" Height="Auto" Margin="5,5,5,5"/&gt; &lt;Button x:Name="SearchButton" Content="Search" Click="CallServiceButton_Click" HorizontalAlignment="Center" VerticalAlignment="Center" Width="75" Height="Auto" Background="#FFAFAFAF" Margin="5,5,5,5"/&gt; &lt;/StackPanel&gt; &lt;/ContentControl&gt; &lt;Grid x:Name="DisplayRoot" Background="White" ShowGridLines="True" HorizontalAlignment="Center" VerticalAlignment="Center" MaxHeight="300" MinHeight="100" MaxWidth="800" MinWidth="200" ScrollViewer.HorizontalScrollBarVisibility="Visible" ScrollViewer.VerticalScrollBarVisibility="Visible"&gt; &lt;data:DataGrid ItemsSource="{Binding ''}" CanUserReorderColumns="False" CanUserResizeColumns="False" AutoGenerateColumns="False" AlternatingRowBackground="#FFAFAFAF" SelectionMode="Single" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="5,5,5,5" x:Name="IncidentGrid" SelectionChanged="IncidentGrid_SelectionChanged"&gt; &lt;data:DataGrid.Columns&gt; &lt;data:DataGridTextColumn DisplayMemberBinding="{Binding Address}" Header="Email Address" IsReadOnly="True" /&gt; &lt;!--Width="150"--&gt; &lt;data:DataGridTextColumn DisplayMemberBinding="{Binding whereClause}" Header="Where Clause" IsReadOnly="True" /&gt; &lt;!--Width="500"--&gt; &lt;data:DataGridTextColumn DisplayMemberBinding="{Binding Enabled}" Header="Enabled" IsReadOnly="True" /&gt; &lt;/data:DataGrid.Columns&gt; &lt;/data:DataGrid&gt; &lt;/Grid&gt; &lt;/StackPanel&gt; &lt;Grid x:Name="EditPersonPopupGrid" Visibility="Collapsed"&gt; &lt;Rectangle HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Opacity="0.765" Fill="#FF8A8A8A" /&gt; &lt;Border CornerRadius="30" Background="#FF2D1DCC" Width="700" Height="400" HorizontalAlignment="Center" VerticalAlignment="Center" BorderThickness="1,1,1,1" BorderBrush="#FF000000"&gt; &lt;StackPanel x:Name="EditPersonStackPanel" Orientation="Vertical" Background="White" HorizontalAlignment="Center" VerticalAlignment="Center" Width="650" &gt; &lt;ContentControl&gt; &lt;StackPanel x:Name="EmailEditStackPanel" Orientation="Horizontal"&gt; &lt;TextBlock Text="Email Address:" Width="200" Margin="5,0,5,0" /&gt; &lt;TextBox x:Name="EmailPopupTextBox" Width="200" /&gt; &lt;/StackPanel&gt; &lt;/ContentControl&gt; &lt;ContentControl&gt; &lt;StackPanel x:Name="AppliesToDropdownStackPanel" Orientation="Horizontal" Margin="2,2,2,0"&gt; &lt;TextBlock Text="Don't send when update was done by:" /&gt; &lt;StackPanel Orientation="Vertical" MaxHeight="275" MaxWidth="350" &gt; &lt;TextBlock x:Name="SelectedItemTextBlock" TextAlignment="Right" Width="200" Margin="5,0,5,0" /&gt; &lt;Grid x:Name="UserDropDownGrid" MaxHeight="75" MaxWidth="200" Visibility="Collapsed" ScrollViewer.VerticalScrollBarVisibility="Visible" ScrollViewer.HorizontalScrollBarVisibility="Hidden" &gt; &lt;Rectangle Fill="White" /&gt; &lt;Border Background="White"&gt; &lt;ListBox x:Name="UsersListBox" SelectionChanged="UsersListBox_SelectionChanged" ItemsSource="{Binding UserID}" /&gt; &lt;/Border&gt; &lt;/Grid&gt; &lt;/StackPanel&gt; &lt;Button x:Name="DropDownButton" Click="DropDownButton_Click" VerticalAlignment="Top" Width="25" Height="25"&gt; &lt;Path Height="10" Width="10" Fill="#FF000000" Stretch="Fill" Stroke="#FF000000" Data="M514.66669,354 L542.16669,354 L527.74988,368.41684 z" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="1,1,1,1"/&gt; &lt;/Button&gt; &lt;/StackPanel&gt; &lt;/ContentControl&gt; &lt;TextBlock Text="Where Clause Condition:" /&gt; &lt;TextBox x:Name="WhereClauseTextBox" Height="200" Width="800" AcceptsReturn="True" TextWrapping="Wrap" /&gt; &lt;ContentControl&gt; &lt;StackPanel Orientation="Vertical"&gt; &lt;StackPanel Orientation="Horizontal"&gt; &lt;Button x:Name="TestConditionButton" Content="Test Condition" Margin="5,5,5,5" Click="TestConditionButton_Click" /&gt; &lt;Button x:Name="Save" Content="Save" HorizontalAlignment="Right" Margin="5,5,5,5" Click="Save_Click" /&gt; &lt;Button x:Name="Cancel" Content="Cancel" HorizontalAlignment="Right" Margin="5,5,5,5" Click="Cancel_Click" /&gt; &lt;/StackPanel&gt; &lt;TextBlock x:Name="TestContitionResults" Visibility="Collapsed" /&gt; &lt;/StackPanel&gt; &lt;/ContentControl&gt; &lt;/StackPanel&gt; &lt;/Border&gt; &lt;/Grid&gt; &lt;/Grid&gt; </code></pre> <p></p> <p>And the call that occurs when the grid's selection is changed:</p> <pre><code>Private Sub IncidentGrid_SelectionChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) If mFirstTime Then mFirstTime = False Else Dim data As SimpleASMX.EMailMonitor = CType(IncidentGrid.SelectedItem, SimpleASMX.EMailMonitor) Dim selectedGridItem As SimpleASMX.EMailMonitor = Nothing If IncidentGrid.SelectedItem IsNot Nothing Then selectedGridItem = CType(IncidentGrid.SelectedItem, SimpleASMX.EMailMonitor) EmailPopupTextBox.Text = selectedGridItem.Address SelectedItemTextBlock.Text = selectedGridItem.AppliesToUserID WhereClauseTextBox.Text = selectedGridItem.whereClause IncidentGrid.SelectedIndex = mEmailMonitorData.IndexOf(selectedGridItem) End If If IncidentGrid.SelectedIndex &gt; -1 Then EditPersonPopupGrid.Visibility = Windows.Visibility.Visible Else EditPersonPopupGrid.Visibility = Windows.Visibility.Collapsed End If End If End Sub </code></pre> <p>Sorry if my code is atrocious, I'm still learning Silverlight.</p>
[ { "answer_id": 74877, "author": "Senkwe", "author_id": 6419, "author_profile": "https://Stackoverflow.com/users/6419", "pm_score": 3, "selected": true, "text": "<p>That looks like a Silverlight bug to me. I've just tried it and what's happening on my end is that the <strong>SelectionChanged</strong> event fires twice when you click the column header and to make matters worse, the index of the selected item doesn't stay synched with the currently selected item.</p>\n\n<p>I'd suggest you work your way around it by using the knowledge that the first time SelectionChanged fires, the value of the datagrid's <strong>SelectedItem</strong> property will be <strong>null</strong></p>\n\n<p>Here's some sample code that at least lives with the issue. Your <strong>SelectionChanged</strong> logic can go in the <strong>if</strong> clause.</p>\n\n<pre><code>public partial class Page : UserControl\n{\n private Person _currentSelectedPerson;\n\n public Page()\n {\n InitializeComponent();\n\n List&lt;Person&gt; persons = new List&lt;Person&gt;();\n persons.Add(new Person() { Age = 5, Name = \"Tom\" });\n persons.Add(new Person() { Age = 3, Name = \"Lisa\" });\n persons.Add(new Person() { Age = 4, Name = \"Sam\" });\n\n dg.ItemsSource = persons;\n } \n\n private void SelectionChanged(object sender, EventArgs e)\n {\n DataGrid grid = sender as DataGrid;\n if (grid.SelectedItem != null)\n {\n _currentSelectedPerson = grid.SelectedItem as Person;\n }\n else\n {\n grid.SelectedItem = _currentSelectedPerson;\n }\n }\n }\n\npublic class Person\n{\n public string Name { get; set; }\n public int Age { get; set; }\n}\n</code></pre>\n" }, { "answer_id": 76586, "author": "Rob", "author_id": 12413, "author_profile": "https://Stackoverflow.com/users/12413", "pm_score": 0, "selected": false, "text": "<p>This worked, but now if I sort twice, on the first one it sorts, and then does the popup as the first selected item of the grid . If I close the popup grid, and then try to sort a second time, it stack overflows, and crashes firefox out.</p>\n\n<p>I'm thinking I may need to rethink working in silverlight until the system gets a bit more stable.</p>\n\n<p>Thanks for the answer Hovito!</p>\n" }, { "answer_id": 498801, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Frozen Columns in Silverlight DataGrid..</p>\n\n<p><a href=\"http://dotnetdreamer.wordpress.com/2009/01/31/silverlight-2-datagrid-frozen-columns/\" rel=\"nofollow noreferrer\">http://dotnetdreamer.wordpress.com/2009/01/31/silverlight-2-datagrid-frozen-columns/</a></p>\n" }, { "answer_id": 592048, "author": "Matthew Timbs", "author_id": 21343, "author_profile": "https://Stackoverflow.com/users/21343", "pm_score": 1, "selected": false, "text": "<p>There's a bugfix for the first issue you mentioned (selection changed event getting fired on resort).</p>\n\n<p>See the following URL for Microsoft's patch:</p>\n\n<p><a href=\"http://www.microsoft.com/downloads/details.aspx?familyid=084A1BB2-0078-4009-94EE-E659C6409DB0&amp;displaylang=en\" rel=\"nofollow noreferrer\">http://www.microsoft.com/downloads/details.aspx?familyid=084A1BB2-0078-4009-94EE-E659C6409DB0&amp;displaylang=en</a></p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/74461", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12413/" ]
I'm currently playing with the Silverlight(Beta 2) Datagrid control. Before I wired up the SelectionChanged event, the grid would sort perfectly by clicking on the header. Now, when the grid is clicked, it will fire the SelectionChanged event when I click the header to sort. Is there any way around this? In a semi-related topic, I'd like to have the SelectionChanged event fire when I click on an already selected item (so that I can have a pop-up occur to allow the user to edit the selected value). Right now, you have to click on a different value and then back to the value you wanted in order for it to pop up. Is there another way? Included is my code. The Page: ``` <UserControl x:Class="WebServicesApp.Page" xmlns="http://schemas.microsoft.com/client/2007" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data" Width="1280" Height="1024" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d"> <Grid x:Name="LayoutRoot" Background="White"> <Grid.RowDefinitions> <RowDefinition /> <RowDefinition /> </Grid.RowDefinitions> <StackPanel Grid.Row="0" x:Name="OurStack" Orientation="Vertical" Margin="5,5,5,5"> <ContentControl VerticalAlignment="Center" HorizontalAlignment="Center"> <StackPanel x:Name="SearchStackPanel" Orientation="Horizontal" Margin="5,5,5,5"> <TextBlock x:Name="SearchEmail" HorizontalAlignment="Stretch" VerticalAlignment="Center" Text="Email Address:" Margin="5,5,5,5" /> <TextBox x:Name="InputText" HorizontalAlignment="Stretch" VerticalAlignment="Center" Width="150" Height="Auto" Margin="5,5,5,5"/> <Button x:Name="SearchButton" Content="Search" Click="CallServiceButton_Click" HorizontalAlignment="Center" VerticalAlignment="Center" Width="75" Height="Auto" Background="#FFAFAFAF" Margin="5,5,5,5"/> </StackPanel> </ContentControl> <Grid x:Name="DisplayRoot" Background="White" ShowGridLines="True" HorizontalAlignment="Center" VerticalAlignment="Center" MaxHeight="300" MinHeight="100" MaxWidth="800" MinWidth="200" ScrollViewer.HorizontalScrollBarVisibility="Visible" ScrollViewer.VerticalScrollBarVisibility="Visible"> <data:DataGrid ItemsSource="{Binding ''}" CanUserReorderColumns="False" CanUserResizeColumns="False" AutoGenerateColumns="False" AlternatingRowBackground="#FFAFAFAF" SelectionMode="Single" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="5,5,5,5" x:Name="IncidentGrid" SelectionChanged="IncidentGrid_SelectionChanged"> <data:DataGrid.Columns> <data:DataGridTextColumn DisplayMemberBinding="{Binding Address}" Header="Email Address" IsReadOnly="True" /> <!--Width="150"--> <data:DataGridTextColumn DisplayMemberBinding="{Binding whereClause}" Header="Where Clause" IsReadOnly="True" /> <!--Width="500"--> <data:DataGridTextColumn DisplayMemberBinding="{Binding Enabled}" Header="Enabled" IsReadOnly="True" /> </data:DataGrid.Columns> </data:DataGrid> </Grid> </StackPanel> <Grid x:Name="EditPersonPopupGrid" Visibility="Collapsed"> <Rectangle HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Opacity="0.765" Fill="#FF8A8A8A" /> <Border CornerRadius="30" Background="#FF2D1DCC" Width="700" Height="400" HorizontalAlignment="Center" VerticalAlignment="Center" BorderThickness="1,1,1,1" BorderBrush="#FF000000"> <StackPanel x:Name="EditPersonStackPanel" Orientation="Vertical" Background="White" HorizontalAlignment="Center" VerticalAlignment="Center" Width="650" > <ContentControl> <StackPanel x:Name="EmailEditStackPanel" Orientation="Horizontal"> <TextBlock Text="Email Address:" Width="200" Margin="5,0,5,0" /> <TextBox x:Name="EmailPopupTextBox" Width="200" /> </StackPanel> </ContentControl> <ContentControl> <StackPanel x:Name="AppliesToDropdownStackPanel" Orientation="Horizontal" Margin="2,2,2,0"> <TextBlock Text="Don't send when update was done by:" /> <StackPanel Orientation="Vertical" MaxHeight="275" MaxWidth="350" > <TextBlock x:Name="SelectedItemTextBlock" TextAlignment="Right" Width="200" Margin="5,0,5,0" /> <Grid x:Name="UserDropDownGrid" MaxHeight="75" MaxWidth="200" Visibility="Collapsed" ScrollViewer.VerticalScrollBarVisibility="Visible" ScrollViewer.HorizontalScrollBarVisibility="Hidden" > <Rectangle Fill="White" /> <Border Background="White"> <ListBox x:Name="UsersListBox" SelectionChanged="UsersListBox_SelectionChanged" ItemsSource="{Binding UserID}" /> </Border> </Grid> </StackPanel> <Button x:Name="DropDownButton" Click="DropDownButton_Click" VerticalAlignment="Top" Width="25" Height="25"> <Path Height="10" Width="10" Fill="#FF000000" Stretch="Fill" Stroke="#FF000000" Data="M514.66669,354 L542.16669,354 L527.74988,368.41684 z" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="1,1,1,1"/> </Button> </StackPanel> </ContentControl> <TextBlock Text="Where Clause Condition:" /> <TextBox x:Name="WhereClauseTextBox" Height="200" Width="800" AcceptsReturn="True" TextWrapping="Wrap" /> <ContentControl> <StackPanel Orientation="Vertical"> <StackPanel Orientation="Horizontal"> <Button x:Name="TestConditionButton" Content="Test Condition" Margin="5,5,5,5" Click="TestConditionButton_Click" /> <Button x:Name="Save" Content="Save" HorizontalAlignment="Right" Margin="5,5,5,5" Click="Save_Click" /> <Button x:Name="Cancel" Content="Cancel" HorizontalAlignment="Right" Margin="5,5,5,5" Click="Cancel_Click" /> </StackPanel> <TextBlock x:Name="TestContitionResults" Visibility="Collapsed" /> </StackPanel> </ContentControl> </StackPanel> </Border> </Grid> </Grid> ``` And the call that occurs when the grid's selection is changed: ``` Private Sub IncidentGrid_SelectionChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) If mFirstTime Then mFirstTime = False Else Dim data As SimpleASMX.EMailMonitor = CType(IncidentGrid.SelectedItem, SimpleASMX.EMailMonitor) Dim selectedGridItem As SimpleASMX.EMailMonitor = Nothing If IncidentGrid.SelectedItem IsNot Nothing Then selectedGridItem = CType(IncidentGrid.SelectedItem, SimpleASMX.EMailMonitor) EmailPopupTextBox.Text = selectedGridItem.Address SelectedItemTextBlock.Text = selectedGridItem.AppliesToUserID WhereClauseTextBox.Text = selectedGridItem.whereClause IncidentGrid.SelectedIndex = mEmailMonitorData.IndexOf(selectedGridItem) End If If IncidentGrid.SelectedIndex > -1 Then EditPersonPopupGrid.Visibility = Windows.Visibility.Visible Else EditPersonPopupGrid.Visibility = Windows.Visibility.Collapsed End If End If End Sub ``` Sorry if my code is atrocious, I'm still learning Silverlight.
That looks like a Silverlight bug to me. I've just tried it and what's happening on my end is that the **SelectionChanged** event fires twice when you click the column header and to make matters worse, the index of the selected item doesn't stay synched with the currently selected item. I'd suggest you work your way around it by using the knowledge that the first time SelectionChanged fires, the value of the datagrid's **SelectedItem** property will be **null** Here's some sample code that at least lives with the issue. Your **SelectionChanged** logic can go in the **if** clause. ``` public partial class Page : UserControl { private Person _currentSelectedPerson; public Page() { InitializeComponent(); List<Person> persons = new List<Person>(); persons.Add(new Person() { Age = 5, Name = "Tom" }); persons.Add(new Person() { Age = 3, Name = "Lisa" }); persons.Add(new Person() { Age = 4, Name = "Sam" }); dg.ItemsSource = persons; } private void SelectionChanged(object sender, EventArgs e) { DataGrid grid = sender as DataGrid; if (grid.SelectedItem != null) { _currentSelectedPerson = grid.SelectedItem as Person; } else { grid.SelectedItem = _currentSelectedPerson; } } } public class Person { public string Name { get; set; } public int Age { get; set; } } ```
74,466
<p>I have a .ico file that is embedded as a resource (build action set to resource). I am trying to create a NotifyIcon. How can I reference my icon?</p> <pre><code>notifyIcon = new NotifyIcon(); notifyIcon.Icon = ?? // my icon file is called MyIcon.ico and is embedded </code></pre>
[ { "answer_id": 74671, "author": "user13125", "author_id": 13125, "author_profile": "https://Stackoverflow.com/users/13125", "pm_score": 8, "selected": true, "text": "<p>Your icon file should be added to one of your project assemblies and its Build Action should be set to Resource. After adding a reference to the assembly, you can create a NotifyIcon like this:</p>\n\n<pre><code>System.Windows.Forms.NotifyIcon icon = new System.Windows.Forms.NotifyIcon();\nStream iconStream = Application.GetResourceStream( new Uri( \"pack://application:,,,/YourReferencedAssembly;component/YourPossibleSubFolder/YourResourceFile.ico\" )).Stream;\nicon.Icon = new System.Drawing.Icon( iconStream );\n</code></pre>\n" }, { "answer_id": 74679, "author": "Jaykul", "author_id": 8718, "author_profile": "https://Stackoverflow.com/users/8718", "pm_score": 4, "selected": false, "text": "<p>Well, you don't want to use the resx style resources: you just stick the ico file in your project in a folder (lets say \"ArtWork\") and in the properties, set the Build Action to \"Resources\" ...</p>\n\n<p>Then you can reference it in XAML using PACK URIs ... \"pack://application:,,,/Artwork/Notify.ico\"</p>\n\n<p>See here: <a href=\"http://msdn.microsoft.com/en-us/library/aa970069.aspx#Programming_with_Pack_URIs\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/aa970069.aspx</a> and the <a href=\"http://msdn.microsoft.com/en-us/library/aa972152.aspx\" rel=\"noreferrer\">sample</a></p>\n\n<p>If you want to be a little bit more ... WPF-like, you should look into the <a href=\"http://www.codeplex.com/wpfcontrib/Wiki/View.aspx?title=NotifyIcon&amp;referringTitle=Home\" rel=\"noreferrer\">WPF Contrib</a> project on CodePlex which has a NotifyIcon control which you can create in XAML and which uses standard WPF menus (so you can stick \"anything\" in the menu).</p>\n" }, { "answer_id": 75049, "author": "shinybluesphere", "author_id": 10282, "author_profile": "https://Stackoverflow.com/users/10282", "pm_score": 2, "selected": false, "text": "<p>I created a project here and used an embedded resource (build action was set to Embedded Resource, rather than just resource). This solution doesn't work with Resource, but you may be able to manipulate it. I put this on the OnIntialized() but it doesn't have to go there.</p>\n\n<pre><code>//IconTest = namespace; exclamic.ico = resource \nSystem.IO.Stream stream = this.GetType().Assembly.GetManifestResourceStream(\"IconTest.Resources.exclamic.ico\");\n\n if (stream != null)\n {\n //Decode the icon from the stream and set the first frame to the BitmapSource\n BitmapDecoder decoder = IconBitmapDecoder.Create(stream, BitmapCreateOptions.None, BitmapCacheOption.None);\n BitmapSource source = decoder.Frames[0];\n\n //set the source of your image\n image.Source = source;\n }\n</code></pre>\n" }, { "answer_id": 1870823, "author": "Thomas Bratt", "author_id": 15985, "author_profile": "https://Stackoverflow.com/users/15985", "pm_score": 5, "selected": false, "text": "<p>A common usage pattern is to have the notify icon the same as the main window's icon. The icon is defined as a PNG file.</p>\n\n<p>To do this, add the image to the project's resources and then use as follows:</p>\n\n<pre><code>var iconHandle = MyNamespace.Properties.Resources.MyImage.GetHicon();\nthis.notifyIcon.Icon = System.Drawing.Icon.FromHandle(iconHandle);\n</code></pre>\n\n<p>In the window XAML:</p>\n\n<pre><code>&lt;Window x:Class=\"MyNamespace.Window1\"\nxmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\nxmlns:local=\"clr-namespace:Seahorse\"\nxmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\nHeight=\"600\"\nIcon=\"images\\MyImage.png\"&gt;\n</code></pre>\n" }, { "answer_id": 32081321, "author": "Mike Sage", "author_id": 862414, "author_profile": "https://Stackoverflow.com/users/862414", "pm_score": 2, "selected": false, "text": "<p>If you are just looking for the simple answer, I think this is it where MyApp is your application name and where that's the root namespace name for your application. You have to use the pack URI syntax, but it doesn't have to be that complicated to pull an icon out of your embedded resources. </p>\n\n<pre><code> &lt;Window x:Class=\"MyApp.MainWindow\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:d=\"http://schemas.microsoft.com/expression/blend/2008\"\n xmlns:mc=\"http://schemas.openxmlformats.org/markup-compatibility/2006\"\n mc:Ignorable=\"d\"\n Height=\"100\"\n Width=\"200\"\n Icon=\"pack://application:,,,/MyApp;component/Resources/small_icon.ico\"&gt;\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/74466", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3047/" ]
I have a .ico file that is embedded as a resource (build action set to resource). I am trying to create a NotifyIcon. How can I reference my icon? ``` notifyIcon = new NotifyIcon(); notifyIcon.Icon = ?? // my icon file is called MyIcon.ico and is embedded ```
Your icon file should be added to one of your project assemblies and its Build Action should be set to Resource. After adding a reference to the assembly, you can create a NotifyIcon like this: ``` System.Windows.Forms.NotifyIcon icon = new System.Windows.Forms.NotifyIcon(); Stream iconStream = Application.GetResourceStream( new Uri( "pack://application:,,,/YourReferencedAssembly;component/YourPossibleSubFolder/YourResourceFile.ico" )).Stream; icon.Icon = new System.Drawing.Icon( iconStream ); ```
74,471
<p>I have a function that takes, amongst others, a parameter declared as <em>int privateCount</em>. When I want to call ToString() on this param, ReSharper greys it out and marks it as a redundant call. So, curious as I am, I remove the ToString(), and the code still builds!</p> <p>How can a C# compiler allow this, where <em>str</em> is a string?</p> <p><code>str += privateCount +</code> ...</p>
[ { "answer_id": 74495, "author": "Haacked", "author_id": 598, "author_profile": "https://Stackoverflow.com/users/598", "pm_score": 5, "selected": true, "text": "<p>The + operator for string is overloaded to call String.Concat passing in the left and right side of the expression. Thus:</p>\n\n<pre><code>string x = \"123\" + 45;\n</code></pre>\n\n<p>Gets compiled to:</p>\n\n<pre><code>String.Concat(\"123\", 45);\n</code></pre>\n\n<p>Since String.Concat takes in two objects, the right hand side (45) is boxed and then ToString() is called on it.</p>\n\n<p>Note that this \"overloading\" is not via operator overloading in the language (aka it's not a method named op_Addition) but is handled by the compiler.</p>\n" }, { "answer_id": 74546, "author": "Stephen Deken", "author_id": 7154, "author_profile": "https://Stackoverflow.com/users/7154", "pm_score": 2, "selected": false, "text": "<p>C# automatically converts the objects to strings for you. Consider this line of code:</p>\n\n<pre><code>aString = aString + 23;\n</code></pre>\n\n<p>This is valid C#; it compiles down to a call to String.Concat(), which takes two objects as arguments. Those objects are automatically converted to string objects for you.</p>\n\n<p>The same thing occurs when you write:</p>\n\n<pre><code>aString += 23;\n</code></pre>\n\n<p>Again, this compiles down to the same call to String.Concat(); it's just written differently.</p>\n" }, { "answer_id": 74606, "author": "Drejc", "author_id": 6482, "author_profile": "https://Stackoverflow.com/users/6482", "pm_score": 1, "selected": false, "text": "<p>This is a valid bad practice, as you must think twice if the variable is a string or an int. What if the variable would be called myInt?</p>\n\n<pre><code>myInt = myInt + 23;\n</code></pre>\n\n<p>it is more readable and understandable in this form?</p>\n\n<pre><code>myInt = mInt + \"23\";\n</code></pre>\n\n<p>or even:</p>\n\n<pre><code>myInt = string.Format(\"{0}{1}\", myInt, 23);\n</code></pre>\n\n<p>We know from the code that it is a string and not an integer.</p>\n" }, { "answer_id": 75404, "author": "Thomas Danecker", "author_id": 9632, "author_profile": "https://Stackoverflow.com/users/9632", "pm_score": 3, "selected": false, "text": "<p>It is not only bad practice, but also less performant: The integer has to be boxed because String.Concat expectes an object while int.ToString() does not require boxing.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/74471", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8741/" ]
I have a function that takes, amongst others, a parameter declared as *int privateCount*. When I want to call ToString() on this param, ReSharper greys it out and marks it as a redundant call. So, curious as I am, I remove the ToString(), and the code still builds! How can a C# compiler allow this, where *str* is a string? `str += privateCount +` ...
The + operator for string is overloaded to call String.Concat passing in the left and right side of the expression. Thus: ``` string x = "123" + 45; ``` Gets compiled to: ``` String.Concat("123", 45); ``` Since String.Concat takes in two objects, the right hand side (45) is boxed and then ToString() is called on it. Note that this "overloading" is not via operator overloading in the language (aka it's not a method named op\_Addition) but is handled by the compiler.
74,514
<p>Implementing Equals() for reference types is harder than it seems. My current canonical implementation goes like this:</p> <pre><code>public bool Equals( MyClass obj ) { // If both refer to the same reference they are equal. if( ReferenceEquals( obj, this ) ) return true; // If the other object is null they are not equal because in C# this cannot be null. if( ReferenceEquals( obj, null ) ) return false; // Compare data to evaluate equality return _data.Equals( obj._data ); } public override bool Equals( object obj ) { // If both refer to the same reference they are equal. if( ReferenceEquals( obj, this ) ) return true; // If the other object is null or is of a different types the objects are not equal. if( ReferenceEquals( obj, null ) || obj.GetType() != GetType() ) return false; // Use type-safe equality comparison return Equals( (MyClass)obj ); } public override int GetHashCode() { // Use data's hash code as our hashcode return _data.GetHashCode(); } </code></pre> <p>I think that this covers all corner (inheritance and such) cases but I may be wrong. What do you guys think?</p>
[ { "answer_id": 74540, "author": "Peter Ritchie", "author_id": 5620, "author_profile": "https://Stackoverflow.com/users/5620", "pm_score": 0, "selected": false, "text": "<p>It depends on whether you're writing a value type or a reference type. For a sortable value type, I recommend this:\n<a href=\"http://msmvps.com/blogs/peterritchie/archive/2006/03/25/a-code-snippet-for-visual-studio-2005-that-implements-a-skeleton-value-type-adhering-to-framework-design-guidelines.aspx\" rel=\"nofollow noreferrer\">A code snippet for Visual Studio 2005 that implements a skeleton value type adhering to Framework Design Guidelines</a></p>\n" }, { "answer_id": 74559, "author": "chakrit", "author_id": 3055, "author_profile": "https://Stackoverflow.com/users/3055", "pm_score": 0, "selected": false, "text": "<p>Concerning inheritance, I think you should just let the OO paradigm does its magic.</p>\n\n<p>Specifically, the <code>GetType()</code> check should be removed, it might break polymorphism down the line.</p>\n" }, { "answer_id": 74704, "author": "Santiago Palladino", "author_id": 12791, "author_profile": "https://Stackoverflow.com/users/12791", "pm_score": 0, "selected": false, "text": "<p>I agree with chakrit, objects of different types should be allowed to be semantically equal if they have the same data or ID.</p>\n\n<p>Personally, I use the following:</p>\n\n<pre><code> public override bool Equals(object obj)\n {\n var other = obj as MyClass;\n if (other == null) return false;\n\n return this.data.Equals(other.data);\n }\n</code></pre>\n" }, { "answer_id": 74765, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 1, "selected": false, "text": "<p>Better hope that this._data is not null if it's also a reference type.</p>\n\n<pre><code>public bool Equals( MyClass obj )\n{\n if (obj == null) {\n return false;\n }\n else {\n return (this._data != null &amp;&amp; this._data.Equals( obj._data ))\n || obj._data == null;\n }\n}\n\npublic override bool Equals( object obj )\n{\n if (obj == null || !(obj is MyClass)) {\n return false;\n }\n else {\n return this.Equals( (MyClass)obj );\n }\n}\n\npublic override int GetHashCode() {\n return this._data == null ? 0 : this._data.GetHashCode();\n}\n</code></pre>\n" }, { "answer_id": 74802, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": true, "text": "<p>I wrote a fairly comprehensive guide to this a while back. For a start your equals implementations should be shared (i.e. the overload taking an object should pass through to the one taking a strongly typed object). Additionally you need to consider things such as your object should be immutable because of the need to override GetHashCode. More info here:</p>\n\n<p><a href=\"http://gregbeech.com/blog/implementing-object-equality-in-dotnet\" rel=\"nofollow noreferrer\">http://gregbeech.com/blog/implementing-object-equality-in-dotnet</a></p>\n" }, { "answer_id": 69503610, "author": "Manfred", "author_id": 411428, "author_profile": "https://Stackoverflow.com/users/411428", "pm_score": 0, "selected": false, "text": "<p>As the link in the accepted answer by Greg Beech is broken, I hope this answer might be helpful to some.</p>\n<p>Microsoft's documentation provides the following example for a typical implementation of <code>Equals()</code> on reference types (i.e. class):</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public override bool Equals(object obj) =&gt; this.Equals(obj as TwoDPoint);\n\npublic bool Equals(TwoDPoint p)\n{\n if (p is null)\n {\n return false;\n }\n\n // Optimization for a common success case.\n if (Object.ReferenceEquals(this, p))\n {\n return true;\n }\n\n // If run-time types are not exactly the same, return false.\n if (this.GetType() != p.GetType())\n {\n return false;\n }\n\n // Return true if the fields match.\n // Note that the base class is not invoked because it is\n // System.Object, which defines Equals as reference equality.\n return (X == p.X) &amp;&amp; (Y == p.Y);\n}\n</code></pre>\n<p>The complete example with more details including what to do in derived classes or for structs, can be found at <a href=\"https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/how-to-define-value-equality-for-a-type\" rel=\"nofollow noreferrer\">&quot;How to define value equality for a class or struct (C# Programming Guide)&quot;</a></p>\n<p>As an alternative to what is described in Microsoft's doc, the method <code>GetHashCode()</code> can also be implemented as follows:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public override int GetHashCode()\n{\n return HashCode.Combine(X, Y);\n}\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/74514", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12851/" ]
Implementing Equals() for reference types is harder than it seems. My current canonical implementation goes like this: ``` public bool Equals( MyClass obj ) { // If both refer to the same reference they are equal. if( ReferenceEquals( obj, this ) ) return true; // If the other object is null they are not equal because in C# this cannot be null. if( ReferenceEquals( obj, null ) ) return false; // Compare data to evaluate equality return _data.Equals( obj._data ); } public override bool Equals( object obj ) { // If both refer to the same reference they are equal. if( ReferenceEquals( obj, this ) ) return true; // If the other object is null or is of a different types the objects are not equal. if( ReferenceEquals( obj, null ) || obj.GetType() != GetType() ) return false; // Use type-safe equality comparison return Equals( (MyClass)obj ); } public override int GetHashCode() { // Use data's hash code as our hashcode return _data.GetHashCode(); } ``` I think that this covers all corner (inheritance and such) cases but I may be wrong. What do you guys think?
I wrote a fairly comprehensive guide to this a while back. For a start your equals implementations should be shared (i.e. the overload taking an object should pass through to the one taking a strongly typed object). Additionally you need to consider things such as your object should be immutable because of the need to override GetHashCode. More info here: <http://gregbeech.com/blog/implementing-object-equality-in-dotnet>
74,570
<p>I'm maintaining <a href="http://perl-begin.org/" rel="nofollow noreferrer">the Perl Beginners' Site</a> and used a modified template from Open Source Web Designs. Now, the problem is that I still have an undesired artifact: a gray line on the left side of the main frame, to the left of the navigation menu. Here's <a href="http://www.shlomifish.org/Files/files/images/Computer/Screenshots/perl-begin-bad-artif.png" rel="nofollow noreferrer">an image</a> highlighting the undesired effect.</p> <p>How can I fix the CSS to remedy this problem?</p>
[ { "answer_id": 74610, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 4, "selected": true, "text": "<p>It's the <code>background-image</code> on the body showing through. Quick fix (edit style.css or add elsewhere):</p>\n\n<pre><code>#page-container\n{\n background-color: white;\n}\n</code></pre>\n" }, { "answer_id": 74613, "author": "Stephen Wrighton", "author_id": 7516, "author_profile": "https://Stackoverflow.com/users/7516", "pm_score": 1, "selected": false, "text": "<p>That is an image. (see it here: <a href=\"http://perl-begin.org/images/background.gif\" rel=\"nofollow noreferrer\">http://perl-begin.org/images/background.gif</a>) It's set in the BODY class of your stylesheet.</p>\n" }, { "answer_id": 74621, "author": "Jonathan Rupp", "author_id": 12502, "author_profile": "https://Stackoverflow.com/users/12502", "pm_score": 0, "selected": false, "text": "<p>I think it's this:</p>\n\n<pre><code>#page-container {\n border-left: solid 1px rgb(150,150,150); border-right: solid 1px rgb(150,150,150); \n}\n</code></pre>\n\n<p>However, I'm not seeing why the right border isn't showing up....</p>\n" }, { "answer_id": 74663, "author": "Jim", "author_id": 8427, "author_profile": "https://Stackoverflow.com/users/8427", "pm_score": 1, "selected": false, "text": "<p>The grey line is supposed to be there. The reason why it looks odd is because the very top is hidden by the buffer element. Remove the <code>background-color</code> rule from this ruleset:</p>\n\n<pre><code>.buffer {\n float: left; width: 160px; height: 20px; margin: 0px; padding: 0px; background-color: rgb(255,255,255); \n}\n</code></pre>\n" }, { "answer_id": 74774, "author": "user11070", "author_id": 11070, "author_profile": "https://Stackoverflow.com/users/11070", "pm_score": 0, "selected": false, "text": "<p>I would do a quick fix on this to add the style:</p>\n\n<pre><code>border-left:2px solid #BDBDBD;\n</code></pre>\n\n<p>to the .buffer class</p>\n\n<pre><code>.buffer {style.css (line 328)\n background-color:#FFFFFF;\n border-left:2px solid #BDBDBD; /* Grey border */\n float:left;\n height:20px;\n margin:0px;\n padding:0px;\n width:160px;\n}\n</code></pre>\n" }, { "answer_id": 74795, "author": "Buzz", "author_id": 13113, "author_profile": "https://Stackoverflow.com/users/13113", "pm_score": 0, "selected": false, "text": "<p>I found the problem. </p>\n\n<p>The problem is that you need to set a white background on #page-container. As things stand, it has a transparent background, so the 5pt left margin on navbar-sidebanner is revealing the bg of the page_container ... so change that bg and you're cool. </p>\n" }, { "answer_id": 75055, "author": "Shlomi Fish", "author_id": 7709, "author_profile": "https://Stackoverflow.com/users/7709", "pm_score": -1, "selected": false, "text": "<p>Thanks to all the people who answered. The problem was indeed the transparency of the #page-container and the background image of the body. I fixed them both in the stylesheet. </p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/74570", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7709/" ]
I'm maintaining [the Perl Beginners' Site](http://perl-begin.org/) and used a modified template from Open Source Web Designs. Now, the problem is that I still have an undesired artifact: a gray line on the left side of the main frame, to the left of the navigation menu. Here's [an image](http://www.shlomifish.org/Files/files/images/Computer/Screenshots/perl-begin-bad-artif.png) highlighting the undesired effect. How can I fix the CSS to remedy this problem?
It's the `background-image` on the body showing through. Quick fix (edit style.css or add elsewhere): ``` #page-container { background-color: white; } ```
74,612
<p>I have a table inside a div. I want the table to occupy the entire width of the div tag.</p> <p>In the CSS, I've set the <code>width</code> of the table to <code>100%</code>. Unfortunately, when the div has some <code>margin</code> on it, the table ends up wider than the div it's in.</p> <p>I need to support IE6 and IE7 (as this is an internal app), although I'd obviously like a fully cross-browser solution if possible!</p> <p>I'm using the following DOCTYPE...</p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; </code></pre> <hr> <p><strong>Edit</strong>: Unfortunately I can't hard-code the width as I'm dynamically generating the HTML and it includes nesting the divs recursively inside each other (with left margin on each div, this creates a nice 'nested' effect).</p>
[ { "answer_id": 74715, "author": "Nate", "author_id": 12779, "author_profile": "https://Stackoverflow.com/users/12779", "pm_score": 3, "selected": false, "text": "<p>The following works for me in Firefox and IE7... a guideline, though is: if you set width on an element, don't set margin or padding on the same element. This holds true <em>especially</em> if you're mixing units -- say, mixing percents and pixels.</p>\n\n<pre><code>&lt;!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt;\n\n&lt;html&gt;\n &lt;head&gt;\n &lt;title&gt;Test&lt;/title&gt;\n &lt;/head&gt;\n &lt;body&gt;\n &lt;div style=\"width: 500px; background-color:#F33;\"&gt;\n This is the outer div\n &lt;div style=\"background-color: #FAA; padding: 10px; margin:10px;\"&gt;\n This is the inner div\n &lt;table cellpadding=\"0\" cellspacing=\"0\" style=\"width: 100%\"&gt;\n &lt;tr&gt;\n &lt;td style=\"border: 1px solid blue; background-color:#FEE;\"&gt;Here is my td&lt;/td&gt;\n &lt;/tr&gt;\n &lt;/table&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>See <a href=\"http://bl.ocks.org/1752582\" rel=\"nofollow noreferrer\">here</a> for an example.</p>\n" }, { "answer_id": 74799, "author": "Nate", "author_id": 12779, "author_profile": "https://Stackoverflow.com/users/12779", "pm_score": 1, "selected": false, "text": "<p>In the case where you're automatically generating code that may have margins on it, adding a simple, unstyled <code>&lt;div&gt;</code> element wrapping your table might do the trick.</p>\n" }, { "answer_id": 74913, "author": "buti-oxa", "author_id": 2515, "author_profile": "https://Stackoverflow.com/users/2515", "pm_score": 0, "selected": false, "text": "<p>That is the big problem with the way CSS treats width property and the reason Microsoft implemented box model differently at first. Microsoft lost, and now it's either width or margin/padding/border for an element. </p>\n\n<p>Situation may change to better in CSS3 with <a href=\"http://www.css3.info/preview/box-sizing/\" rel=\"nofollow noreferrer\">box-sizing property</a></p>\n" }, { "answer_id": 75100, "author": "Joe Morgan", "author_id": 13244, "author_profile": "https://Stackoverflow.com/users/13244", "pm_score": 1, "selected": false, "text": "<p>I've always used <code>&lt;table width=\"100%\"&gt;</code></p>\n" }, { "answer_id": 75343, "author": "Christian Davén", "author_id": 12534, "author_profile": "https://Stackoverflow.com/users/12534", "pm_score": 0, "selected": false, "text": "<p>Maybe this extensive article about <a href=\"http://www.456bereastreet.com/archive/200612/internet_explorer_and_the_css_box_model/\" rel=\"nofollow noreferrer\">Internet Explorer and the CSS box model</a> will help?</p>\n" }, { "answer_id": 76242, "author": "farzad", "author_id": 9394, "author_profile": "https://Stackoverflow.com/users/9394", "pm_score": 0, "selected": false, "text": "<p>try this:</p>\n\n<pre><code>div {\n padding: 0px;\n}\n\ntable {\n width: 100%;\n margin: 0px;\n}\n</code></pre>\n\n<p>by setting the padding of the div to zero, you will remove the space between the borders of the div and the content of it. by setting the width of the table to 100% and it's margin to zero, you will remove the space between the borders of the table and it's container.</p>\n" }, { "answer_id": 76478, "author": "Eric DeLabar", "author_id": 7556, "author_profile": "https://Stackoverflow.com/users/7556", "pm_score": 2, "selected": false, "text": "<p>Percentage-based widths are relative to the first parent element that has a width specified. If your div does not have a width specified then the width of the table has nothing to do with it. Can you post a simplified version of the markup that shows what your <code>DOM</code> tree looks like? </p>\n\n<p>From another angle, if your parent div DOES have a width set and the margin is still affecting your table then you are probably in quirks mode. You have specified your <code>DOCTYPE</code>, but be aware that the <code>DOCTYPE</code> element MUST be the first line in the file. Something else to note when dealing with <code>IE6</code>, by default, if your content is wider than your parent, the parent will be stretched to accommodate, you can stop this by adding <code>overflow: hidden</code> to your <code>css</code> for the parent element but in the process you might obscure some of the child element's content. </p>\n" }, { "answer_id": 84685, "author": "David Heggie", "author_id": 4309, "author_profile": "https://Stackoverflow.com/users/4309", "pm_score": 2, "selected": false, "text": "<p>Not really sure what the problem is here - this works fine in IE6/7 and FF3. Setting the width of the .container DIV element sets the table's width. Adding margins to the .container div doesn't affect the table. Maybe there's something else in your markup / CSS that's affecting the layout?</p>\n\n<pre><code>&lt;!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt;\n\n&lt;html&gt;\n &lt;head&gt;\n &lt;title&gt;Boxes and Tables&lt;/title&gt;\n &lt;style type=\"text/css\"&gt;\n\n div.container {\n background-color: yellow;\n border: 1px solid #000;\n width: 500px;\n margin: 5px auto;\n }\n\n table.contained {\n width: 100%;\n border-collapse: collapse;\n }\n\n table td {\n border: 2px solid #999;\n }\n\n &lt;/style&gt;\n &lt;/head&gt;\n\n &lt;body&gt;\n &lt;div class=\"container\"&gt;\n &lt;table class=\"contained\"&gt;\n &lt;thead&gt;\n &lt;tr&gt;&lt;th&gt;Column1&lt;/th&gt;&lt;th&gt;Column2&lt;/th&gt;&lt;th&gt;Column3&lt;/th&gt;&lt;/tr&gt;\n &lt;/thead&gt;\n &lt;tbody&gt;\n &lt;tr&gt;&lt;td&gt;Value&lt;/td&gt;&lt;td&gt;Value&lt;/td&gt;&lt;td&gt;Value&lt;/td&gt;&lt;/tr&gt;\n &lt;tr&gt;&lt;td&gt;Value&lt;/td&gt;&lt;td&gt;Value&lt;/td&gt;&lt;td&gt;Value&lt;/td&gt;&lt;/tr&gt;\n &lt;tr&gt;&lt;td&gt;Value&lt;/td&gt;&lt;td&gt;Value&lt;/td&gt;&lt;td&gt;Value&lt;/td&gt;&lt;/tr&gt;\n &lt;tr&gt;&lt;td&gt;Value&lt;/td&gt;&lt;td&gt;Value&lt;/td&gt;&lt;td&gt;Value&lt;/td&gt;&lt;/tr&gt;\n &lt;tr&gt;&lt;td&gt;Value&lt;/td&gt;&lt;td&gt;Value&lt;/td&gt;&lt;td&gt;Value&lt;/td&gt;&lt;/tr&gt;\n &lt;/tbody&gt;\n &lt;/table&gt;\n &lt;/div&gt;\n &lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n" }, { "answer_id": 84714, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 0, "selected": false, "text": "<p>Incidentally, is there a good reason for you not to use the strict doctype? strict should always be the default. transitional is only intended for legacy code.</p>\n" }, { "answer_id": 650759, "author": "Chris", "author_id": 13700, "author_profile": "https://Stackoverflow.com/users/13700", "pm_score": 2, "selected": false, "text": "<p>I figured out the heart of the problem here. It has to do with <code>border-collapse</code>. I've had this same problem for a while now. Since tables often have thin borders the problem is not obvious to most people. If you put a regular table with width set to 100% inside a div, as Nate has, you will be fine.</p>\n\n<p>However, if you specify <code>border-collapse:collapse</code> on the table, the table will break out of the div. This is not obvious to most people because it may only break out by one pixel, or depending on the context it's in and the user agent, perhaps not at all.</p>\n\n<p>To make it clearer what is going on, try this: Put Nate's example next to David Heggie's example in an html file.</p>\n\n<p>It will look like both work fine. But now, change Nate's inline TD style to <code>border: 40px solid blue</code>. Change David's table td style to <code>border: 40px solid #999;</code>. At this point, David's table breaks out of the div by 50% of its border on each side. Nate's still works.\nPut a <code>border-collapse:collapse</code> style on Nate's table and his breaks now too.</p>\n\n<p>It's the <code>border-collapse</code> that is causing it!</p>\n" }, { "answer_id": 3908157, "author": "Nestor", "author_id": 470854, "author_profile": "https://Stackoverflow.com/users/470854", "pm_score": 0, "selected": false, "text": "<p>The following code works on IE6/8, Chrome, Firefox, Safari:</p>\n\n<pre><code>&lt;style type=\"text/css\"&gt;\n div.container \n {\n width: 500px;\n padding: 10px;\n margin: 10px;\n border: 1px solid red;\n }\n table.contained \n {\n width: 100%;\n border: 1px solid blue;\n }\n&lt;/style&gt;\n\n&lt;div class=\"container\"&gt;\n &lt;table class=\"contained\"&gt;\n &lt;tr&gt;\n &lt;td&gt;Hello&lt;/td&gt;&lt;td&gt;World&lt;/td&gt;\n &lt;/tr&gt;\n &lt;/table&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>Try copy and paste and build on it (just move the style part to the header or to a separate .css file), maybe the way you using of putting the CSS inline (using the style tag) has something to do with the problem, or it is some other CSS surrounding the div table blocks? Floating can also give troubles.</p>\n\n<p>P.S. I set red and blue borders to see where the areas expand to for a more visual check.</p>\n" }, { "answer_id": 12907189, "author": "William", "author_id": 1562498, "author_profile": "https://Stackoverflow.com/users/1562498", "pm_score": 0, "selected": false, "text": "<p>overflow: auto; on the outermost div may help if you are seeing weird things - like the outermost div being smaller than you want it or not taking up the entire size of the divs inside of it.</p>\n" }, { "answer_id": 28622543, "author": "Sharad Biradar", "author_id": 2114874, "author_profile": "https://Stackoverflow.com/users/2114874", "pm_score": 5, "selected": false, "text": "<p>Add the below CSS to your <code>&lt;table&gt;</code>:</p>\n\n<pre><code>table-layout: fixed;\nwidth: 100%;\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/74612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/475/" ]
I have a table inside a div. I want the table to occupy the entire width of the div tag. In the CSS, I've set the `width` of the table to `100%`. Unfortunately, when the div has some `margin` on it, the table ends up wider than the div it's in. I need to support IE6 and IE7 (as this is an internal app), although I'd obviously like a fully cross-browser solution if possible! I'm using the following DOCTYPE... ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> ``` --- **Edit**: Unfortunately I can't hard-code the width as I'm dynamically generating the HTML and it includes nesting the divs recursively inside each other (with left margin on each div, this creates a nice 'nested' effect).
Add the below CSS to your `<table>`: ``` table-layout: fixed; width: 100%; ```
74,616
<p>example:</p> <pre><code>public static void DoSomething&lt;K,V&gt;(IDictionary&lt;K,V&gt; items) { items.Keys.Each(key =&gt; { if (items[key] **is IEnumerable&lt;?&gt;**) { /* do something */ } else { /* do something else */ } } </code></pre> <p>Can this be done without using reflection? How do I say IEnumerable in C#? Should I just use IEnumerable since IEnumerable&lt;> implements IEnumerable? </p>
[ { "answer_id": 74648, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 2, "selected": false, "text": "<pre><code>if (typeof(IEnumerable).IsAssignableFrom(typeof(V))) {\n</code></pre>\n" }, { "answer_id": 74772, "author": "Isak Savo", "author_id": 8521, "author_profile": "https://Stackoverflow.com/users/8521", "pm_score": 0, "selected": false, "text": "<p>I'm not sure I understand what you mean here. Do you want to know if the object is of <strong>any generic type</strong> or do you want to test if it is a <strong>specific generic type</strong>? Or do you just want to know if is enumerable?</p>\n\n<p>I don't think the first is possible. The second is definitely possible, just treat it as any other type. For the third, just test it against IEnumerable as you suggested.</p>\n\n<p>Also, you cannot use the 'is' operator on types. </p>\n\n<pre><code>// Not allowed\nif (string is Object)\n Foo();\n// You have to use \nif (typeof(object).IsAssignableFrom(typeof(string))\n Foo();\n</code></pre>\n\n<p>See <a href=\"https://stackoverflow.com/questions/72360/how-to-use-the-is-operator-in-systemtype-variables\">this question about types</a> for more details. Maybe it'll help you.</p>\n" }, { "answer_id": 75266, "author": "Paul van Brenk", "author_id": 1837197, "author_profile": "https://Stackoverflow.com/users/1837197", "pm_score": -1, "selected": false, "text": "<p>You want to check out the <a href=\"http://msdn.microsoft.com/en-us/library/system.type.isinstanceoftype.aspx\" rel=\"nofollow noreferrer\">Type.IsInstanceOfType</a> method</p>\n" }, { "answer_id": 75341, "author": "Thomas Danecker", "author_id": 9632, "author_profile": "https://Stackoverflow.com/users/9632", "pm_score": 1, "selected": false, "text": "<p>I'd use overloading:</p>\n\n<pre><code>public static void DoSomething&lt;K,V&gt;(IDictionary&lt;K,V&gt; items)\n where V : IEnumerable\n{\n items.Keys.Each(key =&gt; { /* do something */ });\n}\n\npublic static void DoSomething&lt;K,V&gt;(IDictionary&lt;K,V&gt; items)\n{\n items.Keys.Each(key =&gt; { /* do something else */ });\n}\n</code></pre>\n" }, { "answer_id": 75502, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 6, "selected": true, "text": "<p><a href=\"https://stackoverflow.com/a/74648/1968\">The previously accepted answer</a> is nice but it is wrong. Thankfully, the error is a small one. Checking for <code>IEnumerable</code> is not enough if you really want to know about the generic version of the interface; there are a lot of classes that implement only the nongeneric interface. I'll give the answer in a minute. First, though, I'd like to point out that the accepted answer is overly complicated, since the following code would achieve the same under the given circumstances:</p>\n\n<pre><code>if (items[key] is IEnumerable)\n</code></pre>\n\n<p>This does even more because it works for each item separately (and not on their common subclass, <code>V</code>).</p>\n\n<p>Now, for the correct solution. This is a bit more complicated because we have to take the generic type <code>IEnumerable`1</code> (that is, the type <code>IEnumerable&lt;&gt;</code> with one type parameter) and inject the right generic argument:</p>\n\n<pre><code>static bool IsGenericEnumerable(Type t) {\n var genArgs = t.GetGenericArguments();\n if (genArgs.Length == 1 &amp;&amp;\n typeof(IEnumerable&lt;&gt;).MakeGenericType(genArgs).IsAssignableFrom(t))\n return true;\n else\n return t.BaseType != null &amp;&amp; IsGenericEnumerable(t.BaseType);\n}\n</code></pre>\n\n<p>You can test the correctness of this code easily:</p>\n\n<pre><code>var xs = new List&lt;string&gt;();\nvar ys = new System.Collections.ArrayList();\nConsole.WriteLine(IsGenericEnumerable(xs.GetType()));\nConsole.WriteLine(IsGenericEnumerable(ys.GetType()));\n</code></pre>\n\n<p>yields:</p>\n\n<pre><code>True\nFalse\n</code></pre>\n\n<p>Don't be overly concerned by the fact that this uses reflection. While it's true that this adds runtime overhead, so does the use of the <code>is</code> operator.</p>\n\n<p>Of course the above code is awfully constrained and could be expanded into a more generally applicable method, <code>IsAssignableToGenericType</code>. The following implementation is slightly incorrect<sup>1</sup> and I’ll leave it here <em>for historic purposes only</em>. <strong>Do not use it</strong>. Instead, <a href=\"https://stackoverflow.com/a/1075059/1968\">James has provided an excellent, correct implementation in his answer.</a></p>\n\n<pre><code>public static bool IsAssignableToGenericType(Type givenType, Type genericType) {\n var interfaceTypes = givenType.GetInterfaces();\n\n foreach (var it in interfaceTypes)\n if (it.IsGenericType)\n if (it.GetGenericTypeDefinition() == genericType) return true;\n\n Type baseType = givenType.BaseType;\n if (baseType == null) return false;\n\n return baseType.IsGenericType &amp;&amp;\n baseType.GetGenericTypeDefinition() == genericType ||\n IsAssignableToGenericType(baseType, genericType);\n}\n</code></pre>\n\n<p><sup>1</sup> It fails when the <code>genericType</code> is the same as <code>givenType</code>; for the same reason, it fails for nullable types, i.e.</p>\n\n<pre><code>IsAssignableToGenericType(typeof(List&lt;int&gt;), typeof(List&lt;&gt;)) == false\nIsAssignableToGenericType(typeof(int?), typeof(Nullable&lt;&gt;)) == false\n</code></pre>\n\n<p>I’ve created a <a href=\"https://gist.github.com/4174727\" rel=\"noreferrer\">gist with a comprehensive suite of test cases</a>.</p>\n" }, { "answer_id": 75600, "author": "Rich Visotcky", "author_id": 400730, "author_profile": "https://Stackoverflow.com/users/400730", "pm_score": 3, "selected": false, "text": "<p>A word of warning about generic types and using IsAssignableFrom()...</p>\n\n<p>Say you have the following:</p>\n\n<pre><code>public class MyListBase&lt;T&gt; : IEnumerable&lt;T&gt; where T : ItemBase\n{\n}\n\npublic class MyItem : ItemBase\n{\n}\n\npublic class MyDerivedList : MyListBase&lt;MyItem&gt;\n{\n}\n</code></pre>\n\n<p>Calling IsAssignableFrom on the base list type or on the derived list type will return false, yet clearly <code>MyDerivedList</code> inherits <code>MyListBase&lt;T&gt;</code>. (A quick note for Jeff, generics absolutely <em>must</em> be wrapped in a code block or tildes to get the <code>&lt;T&gt;</code>, otherwise it's omitted. Is this intended?) The problem stems from the fact that <code>MyListBase&lt;MyItem&gt;</code> is treated as an entirely different type than <code>MyListBase&lt;T&gt;</code>. The following article could explain this a little better. <a href=\"http://mikehadlow.blogspot.com/2006/08/reflecting-generics.html\" rel=\"nofollow noreferrer\">http://mikehadlow.blogspot.com/2006/08/reflecting-generics.html</a></p>\n\n<p>Instead, try the following recursive function:</p>\n\n<pre><code> public static bool IsDerivedFromGenericType(Type givenType, Type genericType)\n {\n Type baseType = givenType.BaseType;\n if (baseType == null) return false;\n if (baseType.IsGenericType)\n {\n if (baseType.GetGenericTypeDefinition() == genericType) return true;\n }\n return IsDerivedFromGenericType(baseType, genericType);\n }\n</code></pre>\n\n<p>/EDIT: Konrad's new post which takes the generic recursion into account as well as interfaces is spot on. Very nice work. :)</p>\n\n<p>/EDIT2: If a check is made on whether genericType is an interface, performance benefits could be realized. The check can be an if block around the current interface code, but if you're interested in using .NET 3.5, a friend of mine offers the following:</p>\n\n<pre><code> public static bool IsAssignableToGenericType(Type givenType, Type genericType)\n {\n var interfaces = givenType.GetInterfaces().Where(it =&gt; it.IsGenericType).Select(it =&gt; it.GetGenericTypeDefinition());\n var foundInterface = interfaces.FirstOrDefault(it =&gt; it == genericType);\n if (foundInterface != null) return true;\n\n Type baseType = givenType.BaseType;\n if (baseType == null) return false;\n\n return baseType.IsGenericType ?\n baseType.GetGenericTypeDefinition() == genericType :\n IsAssignableToGenericType(baseType, genericType);\n }\n</code></pre>\n" }, { "answer_id": 390981, "author": "Hosam Aly", "author_id": 41283, "author_profile": "https://Stackoverflow.com/users/41283", "pm_score": 0, "selected": false, "text": "<p>I used to think such a situation may be solvable in a way similar to @Thomas Danecker's <a href=\"https://stackoverflow.com/questions/74616/how-to-detect-if-type-is-another-generic-type#75341\">solution</a>, but adding another template argument:</p>\n\n<pre><code>public static void DoSomething&lt;K, V, U&gt;(IDictionary&lt;K,V&gt; items)\n where V : IEnumerable&lt;U&gt; { /* do something */ }\npublic static void DoSomething&lt;K, V&gt;(IDictionary&lt;K,V&gt; items)\n { /* do something else */ }\n</code></pre>\n\n<p>But I noticed now that it does't work unless I specify the template arguments of the first method explicitly. This is clearly not customized per each item in the dictionary, but it may be a kind of poor-man's solution.</p>\n\n<p>I would be very thankful if someone could point out anything incorrect I might have done here.</p>\n" }, { "answer_id": 1075059, "author": "James Fraumeni", "author_id": 132345, "author_profile": "https://Stackoverflow.com/users/132345", "pm_score": 7, "selected": false, "text": "<p>Thanks very much for this post. I wanted to provide a version of Konrad Rudolph's solution that has worked better for me. I had minor issues with that version, notably when testing if a Type is a nullable value type:</p>\n\n<pre><code>public static bool IsAssignableToGenericType(Type givenType, Type genericType)\n{\n var interfaceTypes = givenType.GetInterfaces();\n\n foreach (var it in interfaceTypes)\n {\n if (it.IsGenericType &amp;&amp; it.GetGenericTypeDefinition() == genericType)\n return true;\n }\n\n if (givenType.IsGenericType &amp;&amp; givenType.GetGenericTypeDefinition() == genericType)\n return true;\n\n Type baseType = givenType.BaseType;\n if (baseType == null) return false;\n\n return IsAssignableToGenericType(baseType, genericType);\n}\n</code></pre>\n" }, { "answer_id": 8684023, "author": "Matt Johnson-Pint", "author_id": 634824, "author_profile": "https://Stackoverflow.com/users/634824", "pm_score": 2, "selected": false, "text": "<p>Thanks for the great info. For convienience, I've refactored this into an extension method and reduced it to a single statement.</p>\n\n<pre><code>public static bool IsAssignableToGenericType(this Type givenType, Type genericType)\n{\n return givenType.GetInterfaces().Any(t =&gt; t.IsGenericType &amp;&amp; t.GetGenericTypeDefinition() == genericType) ||\n givenType.BaseType != null &amp;&amp; (givenType.BaseType.IsGenericType &amp;&amp; givenType.BaseType.GetGenericTypeDefinition() == genericType ||\n givenType.BaseType.IsAssignableToGenericType(genericType));\n}\n</code></pre>\n\n<p>Now it can be easily called with:</p>\n\n<p>sometype.IsAssignableToGenericType(typeof(MyGenericType&lt;>))</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/74616", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12934/" ]
example: ``` public static void DoSomething<K,V>(IDictionary<K,V> items) { items.Keys.Each(key => { if (items[key] **is IEnumerable<?>**) { /* do something */ } else { /* do something else */ } } ``` Can this be done without using reflection? How do I say IEnumerable in C#? Should I just use IEnumerable since IEnumerable<> implements IEnumerable?
[The previously accepted answer](https://stackoverflow.com/a/74648/1968) is nice but it is wrong. Thankfully, the error is a small one. Checking for `IEnumerable` is not enough if you really want to know about the generic version of the interface; there are a lot of classes that implement only the nongeneric interface. I'll give the answer in a minute. First, though, I'd like to point out that the accepted answer is overly complicated, since the following code would achieve the same under the given circumstances: ``` if (items[key] is IEnumerable) ``` This does even more because it works for each item separately (and not on their common subclass, `V`). Now, for the correct solution. This is a bit more complicated because we have to take the generic type `IEnumerable`1` (that is, the type `IEnumerable<>` with one type parameter) and inject the right generic argument: ``` static bool IsGenericEnumerable(Type t) { var genArgs = t.GetGenericArguments(); if (genArgs.Length == 1 && typeof(IEnumerable<>).MakeGenericType(genArgs).IsAssignableFrom(t)) return true; else return t.BaseType != null && IsGenericEnumerable(t.BaseType); } ``` You can test the correctness of this code easily: ``` var xs = new List<string>(); var ys = new System.Collections.ArrayList(); Console.WriteLine(IsGenericEnumerable(xs.GetType())); Console.WriteLine(IsGenericEnumerable(ys.GetType())); ``` yields: ``` True False ``` Don't be overly concerned by the fact that this uses reflection. While it's true that this adds runtime overhead, so does the use of the `is` operator. Of course the above code is awfully constrained and could be expanded into a more generally applicable method, `IsAssignableToGenericType`. The following implementation is slightly incorrect1 and I’ll leave it here *for historic purposes only*. **Do not use it**. Instead, [James has provided an excellent, correct implementation in his answer.](https://stackoverflow.com/a/1075059/1968) ``` public static bool IsAssignableToGenericType(Type givenType, Type genericType) { var interfaceTypes = givenType.GetInterfaces(); foreach (var it in interfaceTypes) if (it.IsGenericType) if (it.GetGenericTypeDefinition() == genericType) return true; Type baseType = givenType.BaseType; if (baseType == null) return false; return baseType.IsGenericType && baseType.GetGenericTypeDefinition() == genericType || IsAssignableToGenericType(baseType, genericType); } ``` 1 It fails when the `genericType` is the same as `givenType`; for the same reason, it fails for nullable types, i.e. ``` IsAssignableToGenericType(typeof(List<int>), typeof(List<>)) == false IsAssignableToGenericType(typeof(int?), typeof(Nullable<>)) == false ``` I’ve created a [gist with a comprehensive suite of test cases](https://gist.github.com/4174727).
74,620
<p>Can't understand why the following takes place:</p> <pre><code>String date = "06-04-2007 07:05"; SimpleDateFormat fmt = new SimpleDateFormat("MM-dd-yyyy HH:mm"); Date myDate = fmt.parse(date); System.out.println(myDate); //Mon Jun 04 07:05:00 EDT 2007 long timestamp = myDate.getTime(); System.out.println(timestamp); //1180955100000 -- where are the milliseconds? // on the other hand... myDate = new Date(); System.out.println(myDate); //Tue Sep 16 13:02:44 EDT 2008 timestamp = myDate.getTime(); System.out.println(timestamp); //1221584564703 -- why, oh, why? </code></pre>
[ { "answer_id": 74652, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 5, "selected": true, "text": "<p>What milliseconds? You are providing only minutes information in the first example, whereas your second example grabs current date from the system with milliseconds, what is it you're looking for?</p>\n\n<pre><code>String date = \"06-04-2007 07:05:00.999\";\nSimpleDateFormat fmt = new SimpleDateFormat(\"MM-dd-yyyy HH:mm:ss.S\");\nDate myDate = fmt.parse(date);\n\nSystem.out.println(myDate); \nlong timestamp = myDate.getTime();\nSystem.out.println(timestamp);\n</code></pre>\n" }, { "answer_id": 74683, "author": "Mostlyharmless", "author_id": 12881, "author_profile": "https://Stackoverflow.com/users/12881", "pm_score": 2, "selected": false, "text": "<p>Because simple date format you specified discards the milliseconds. So the resulting Date object does not have that info. So when you print it out, its all 0s.</p>\n\n<p>On the other hand, the Date object does retain the milliseconds when you assign it a value with milliseconds (in this case, using new Date()). So when you print them out, it contains the millisecs too.</p>\n" }, { "answer_id": 74685, "author": "ScArcher2", "author_id": 1310, "author_profile": "https://Stackoverflow.com/users/1310", "pm_score": 0, "selected": false, "text": "<p>When you parse a date it only uses the information you provide.\nIn this case it only knows MM-dd-yyyy HH:mm.</p>\n\n<p>Creating a new date object returns the current system date/time (number of milliseconds since the epoch). </p>\n" }, { "answer_id": 74694, "author": "tim_yates", "author_id": 6509, "author_profile": "https://Stackoverflow.com/users/6509", "pm_score": 0, "selected": false, "text": "<p>toString() of a Date object does not show you the milliseconds... But they are there</p>\n\n<p>So new Date() is an object with milisecond resolution, as can be seen by:</p>\n\n<pre><code> System.out.printf( \"ms = %d\\n\", myDate.getTime() % 1000 ) ;\n</code></pre>\n\n<p>However, when you construct your date with SimpleDateFormat, no milliseconds are passed to it</p>\n\n<p>Am I missing the question here?</p>\n\n<p>[edit] Hahaha...way too slow ;)</p>\n" }, { "answer_id": 75140, "author": "laz", "author_id": 8753, "author_profile": "https://Stackoverflow.com/users/8753", "pm_score": 0, "selected": false, "text": "<p>Date.getTime returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by the Date object. So \"06-04-2007 07:05\" - \"01-01-1970 00:00\" is equal to 1180955340000 milliseconds. Since the only concern of your question is about the time portion of the date, a rough way of thinking of this calculation is the number of milliseconds between 07:05 and 00:00 which is 25500000. This is evenly divisible by 1000 since neither time has any milliseconds.</p>\n\n<p>In the second date it uses the current time when that line of code is executed. That will use whatever the current milliseconds past the current second are in the calculation. Therefore, Date.getTime will more than likely return a number that is not evenly divisible by 1000.</p>\n" }, { "answer_id": 76006, "author": "Michael", "author_id": 13379, "author_profile": "https://Stackoverflow.com/users/13379", "pm_score": 0, "selected": false, "text": "<p>The <code>getTime()</code> method of <code>Date</code> returns the number of milliseconds since January 1, 1970 (this date is called the \"epoch\" because all computer dates are based off of this date). It should <strong>not</strong> be used to display a human-readable version of your Date.</p>\n\n<p>Use the <code>SimpleDateFormat.format()</code> method instead. Here is a revised version of part of your code that I think may solve your problem:</p>\n\n<pre><code>String date = \"06-04-2007 07:05:23:123\";\nSimpleDateFormat fmt = new SimpleDateFormat(\"MM-dd-yyyy HH:mm:ss:S\");\nDate myDate = fmt.parse(date); \n\nSystem.out.println(myDate); //Mon Jun 04 07:05:23 EDT 2007\nString formattedDate = fmt.format(myDate);\nSystem.out.println(formattedDate); //06-04-2007 07:05:23:123\n</code></pre>\n" }, { "answer_id": 78965, "author": "Ryan Delucchi", "author_id": 9931, "author_profile": "https://Stackoverflow.com/users/9931", "pm_score": 2, "selected": false, "text": "<p>Instead of using the Sun JDK Time/Date libraries (which leave much to be desired) I recommend taking a look at <a href=\"http://joda-time.sourceforge.net\" rel=\"nofollow noreferrer\">http://joda-time.sourceforge.net</a>.</p>\n\n<p>This is a very mature and active sourceforge project and has a very elegant API.</p>\n" }, { "answer_id": 647220, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<pre><code>import java.util.*;\n\npublic class Time {\n public static void main(String[] args) {\n Long l = 0L;\n Calendar c = Calendar.getInstance();\n //milli sec part of current time\n l = c.getTimeInMillis() % 1000; \n //current time without millisec\n StringBuffer sb = new StringBuffer(c.getTime().toString());\n //millisec in string\n String s = \":\" + l.toString();\n //insert at right place\n sb.insert(19, s);\n //ENJOY\n System.out.println(sb);\n }\n}\n</code></pre>\n" }, { "answer_id": 61567225, "author": "Basil Bourque", "author_id": 642706, "author_profile": "https://Stackoverflow.com/users/642706", "pm_score": 1, "selected": false, "text": "<h1>tl;dr</h1>\n\n<p>The accepted <a href=\"https://stackoverflow.com/a/74652/642706\">Answer by Vinko Vrsalovic</a> is correct. Your input is whole minutes, so the milliseconds for fractional second should indeed be zero.</p>\n\n<p>Use <em>java.time</em>.</p>\n\n<pre><code>LocalDateTime.parse\n( \n \"06-04-2007 07:05\" , \n DateTimeFormatter.ofPattern( \"MM-dd-uuuu HH:mm\" ) \n)\n.atZone\n(\n ZoneId.of( \"Africa/Casablanca\" ) \n)\n.toInstant()\n.getEpochMilli()\n</code></pre>\n\n<h1><em>java.time</em></h1>\n\n<p>The modern approach uses the <em>java.time</em> classes defined in JSR 310 that years ago supplanted the terrible classes you are using.</p>\n\n<p>Define a formatting pattern to match your input. FYI: Learn to use standard ISO 8601 formats for exchanging date-time values as text.</p>\n\n<pre><code>String input = \"06-04-2007 07:05\" ;\nDateTimeFormatter f = DateTimeFormatter.ofPattern( \"MM-dd-uuuu HH:mm\" ) ;\n</code></pre>\n\n<p>Parse your input as a <code>LocalDateTime</code>, as it lacks an indicator of time zone or offset-from-UTC.</p>\n\n<pre><code>LocalDateTime ldt = LocalDateTime.parse( input , f ) ;\n</code></pre>\n\n<p>This represents a date and a time-of-day, but lacks the context of a time zone or offset. So we do not know if you meant 7 AM in Tokyo Japan, 7 AM in Toulouse France, or 7 AM in Toledo Ohio US. This issue of time zone is crucial, because your desired count of milliseconds is a count since the first moment of 1970 as seen in UTC (an offset of zero hours-minutes-seconds), 1970-01-01T00:00Z. </p>\n\n<p>So we must place your input value, the <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/time/LocalDateTime.html\" rel=\"nofollow noreferrer\"><code>LocalDateTime</code></a> object, in the context of a time zone or offset. </p>\n\n<p>If your input was intended to represent a date and time in UTC, use <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/time/OffsetDateTime.html\" rel=\"nofollow noreferrer\"><code>OffsetDateTime</code></a> with <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/time/ZoneOffset.html#UTC\" rel=\"nofollow noreferrer\"><code>ZoneOffset.UTC</code></a>.</p>\n\n<pre><code>OffsetDateTime odt = ldt.atOffset( ZoneOffset.UTC ) ; // Do this if your date and time represent a moment as seen in UTC. \n</code></pre>\n\n<p>If your input was intended to represent a date and time as seen through the wall-clock time used by the people of a particular region, use <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/time/ZonedDateTime.html\" rel=\"nofollow noreferrer\"><code>ZonedDateTime</code></a>. </p>\n\n<pre><code>ZoneId z = ZoneId.of( \"Asia/Tokyo\" ) ;\nZonedDateTime zdt = ldt.atZone( z ) ;\n</code></pre>\n\n<p>Next we want to interrogate for the count of milliseconds since the epoch of first moment of 1970 in UTC. With either a <code>OffsetDateTime</code> or <code>ZonedDateTime</code> object in hand, extract a <code>Instant</code> by calling <code>toInstant</code>. </p>\n\n<pre><code>Instant instant = odt.toInstant() ;\n</code></pre>\n\n<p>…or…</p>\n\n<pre><code>Instant instant = zdt.toInstant() ;\n</code></pre>\n\n<p>Now get count of milliseconds. </p>\n\n<pre><code>long millisecondsSinceEpoch = instant.toEpochMilli() ;\n</code></pre>\n\n<p>By the way, I suggest you not track time by a count of milliseconds. Use ISO 8601 formatted text instead: easy to parse by machine, easy to read by humans across cultures. A count of milliseconds is neither. </p>\n\n<hr>\n\n<p><a href=\"https://i.stack.imgur.com/CNlDF.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/CNlDF.png\" alt=\"Table of date-time types in Java, both modern and legacy\"></a></p>\n\n<hr>\n\n<h1>About <em>java.time</em></h1>\n\n<p>The <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/time/package-summary.html\" rel=\"nofollow noreferrer\"><em>java.time</em></a> framework is built into Java 8 and later. These classes supplant the troublesome old <a href=\"https://en.wikipedia.org/wiki/Legacy_system\" rel=\"nofollow noreferrer\">legacy</a> date-time classes such as <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Date.html\" rel=\"nofollow noreferrer\"><code>java.util.Date</code></a>, <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Calendar.html\" rel=\"nofollow noreferrer\"><code>Calendar</code></a>, &amp; <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/text/SimpleDateFormat.html\" rel=\"nofollow noreferrer\"><code>SimpleDateFormat</code></a>.</p>\n\n<p>To learn more, see the <a href=\"http://docs.oracle.com/javase/tutorial/datetime/TOC.html\" rel=\"nofollow noreferrer\"><em>Oracle Tutorial</em></a>. And search Stack Overflow for many examples and explanations. Specification is <a href=\"https://jcp.org/en/jsr/detail?id=310\" rel=\"nofollow noreferrer\">JSR 310</a>.</p>\n\n<p>The <a href=\"http://www.joda.org/joda-time/\" rel=\"nofollow noreferrer\"><em>Joda-Time</em></a> project, now in <a href=\"https://en.wikipedia.org/wiki/Maintenance_mode\" rel=\"nofollow noreferrer\">maintenance mode</a>, advises migration to the <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/time/package-summary.html\" rel=\"nofollow noreferrer\">java.time</a> classes.</p>\n\n<p>You may exchange <em>java.time</em> objects directly with your database. Use a <a href=\"https://en.wikipedia.org/wiki/JDBC_driver\" rel=\"nofollow noreferrer\">JDBC driver</a> compliant with <a href=\"http://openjdk.java.net/jeps/170\" rel=\"nofollow noreferrer\">JDBC 4.2</a> or later. No need for strings, no need for <code>java.sql.*</code> classes. Hibernate 5 &amp; JPA 2.2 support <em>java.time</em>. </p>\n\n<p>Where to obtain the java.time classes? </p>\n\n<ul>\n<li><a href=\"https://en.wikipedia.org/wiki/Java_version_history#Java_SE_8\" rel=\"nofollow noreferrer\"><strong>Java SE 8</strong></a>, <a href=\"https://en.wikipedia.org/wiki/Java_version_history#Java_SE_9\" rel=\"nofollow noreferrer\"><strong>Java SE 9</strong></a>, <a href=\"https://en.wikipedia.org/wiki/Java_version_history#Java_SE_10\" rel=\"nofollow noreferrer\"><strong>Java SE 10</strong></a>, <a href=\"https://en.wikipedia.org/wiki/Java_version_history#Java_SE_11\" rel=\"nofollow noreferrer\"><strong>Java SE 11</strong></a>, and later - Part of the standard Java API with a bundled implementation.\n\n<ul>\n<li>Java 9 adds some minor features and fixes.</li>\n</ul></li>\n<li><a href=\"https://en.wikipedia.org/wiki/Java_version_history#Java_SE_6\" rel=\"nofollow noreferrer\"><strong>Java SE 6</strong></a> and <a href=\"https://en.wikipedia.org/wiki/Java_version_history#Java_SE_7\" rel=\"nofollow noreferrer\"><strong>Java SE 7</strong></a>\n\n<ul>\n<li>Most of the <em>java.time</em> functionality is back-ported to Java 6 &amp; 7 in <a href=\"http://www.threeten.org/threetenbp/\" rel=\"nofollow noreferrer\"><strong><em>ThreeTen-Backport</em></strong></a>.</li>\n</ul></li>\n<li><a href=\"https://en.wikipedia.org/wiki/Android_(operating_system)\" rel=\"nofollow noreferrer\"><strong>Android</strong></a>\n\n<ul>\n<li>Later versions of Android bundle implementations of the <em>java.time</em> classes.</li>\n<li>For earlier Android (&lt;26), the <a href=\"https://github.com/JakeWharton/ThreeTenABP\" rel=\"nofollow noreferrer\"><strong><em>ThreeTenABP</em></strong></a> project adapts <a href=\"http://www.threeten.org/threetenbp/\" rel=\"nofollow noreferrer\"><strong><em>ThreeTen-Backport</em></strong></a> (mentioned above). See <a href=\"http://stackoverflow.com/q/38922754/642706\"><em>How to use ThreeTenABP…</em></a>.</li>\n</ul></li>\n</ul>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/74620", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10675/" ]
Can't understand why the following takes place: ``` String date = "06-04-2007 07:05"; SimpleDateFormat fmt = new SimpleDateFormat("MM-dd-yyyy HH:mm"); Date myDate = fmt.parse(date); System.out.println(myDate); //Mon Jun 04 07:05:00 EDT 2007 long timestamp = myDate.getTime(); System.out.println(timestamp); //1180955100000 -- where are the milliseconds? // on the other hand... myDate = new Date(); System.out.println(myDate); //Tue Sep 16 13:02:44 EDT 2008 timestamp = myDate.getTime(); System.out.println(timestamp); //1221584564703 -- why, oh, why? ```
What milliseconds? You are providing only minutes information in the first example, whereas your second example grabs current date from the system with milliseconds, what is it you're looking for? ``` String date = "06-04-2007 07:05:00.999"; SimpleDateFormat fmt = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss.S"); Date myDate = fmt.parse(date); System.out.println(myDate); long timestamp = myDate.getTime(); System.out.println(timestamp); ```
74,649
<p>What is the syntax to declare a type for my compare-function generator in code like the following?</p> <pre><code>var colName:String = ""; // actually assigned in a loop gc.sortCompareFunction = function() : ??WHAT_GOES_HERE?? { var tmp:String = colName; return function(a:Object,b:Object):int { return compareGeneral(a,b,tmp); }; }(); </code></pre>
[ { "answer_id": 74743, "author": "Brent", "author_id": 10680, "author_profile": "https://Stackoverflow.com/users/10680", "pm_score": 2, "selected": true, "text": "<p>Isn't \"Function\" a data type?</p>\n" }, { "answer_id": 125763, "author": "Brian Hodge", "author_id": 20628, "author_profile": "https://Stackoverflow.com/users/20628", "pm_score": 0, "selected": false, "text": "<p>In order to understand what the data type is, we must know what the intended outcome of the return is. I need to see the code block for compareGeneral, and I still don't believe this will help. You have two returns withing the same function \"gc.sortCompareFunction\", I believe this is incorrect as return gets a value and then acts as a break command meaning the rest of the anything withing the same function block is ignored. The problem is that I don't know which return is the intended return, and I don't know that flash knows either. You can use * as a data type, but this should only really be used in specific situations. In this situation I believe you need only the one return value that merely returns whatever the value of compareGeneral.</p>\n\n<p>Now if this is a compareGenerator it really should either return a Boolean TRUE or FALSE, or a int 0 or 1, lets use the former. Also I believe we can use one less function. Since I have not seen all of your code and I am not exactly sure what your trying to accomplish, the following is hypothetical.</p>\n\n<blockquote>\n<pre>\nfunction compareGeneral(a:object,b:object):Boolean\n{\n //Check some property associated to each object for likeness.\n if(a.someAssignedPropery == b.someAssignedPropery)\n {\n return true;\n }\n return false;\n}\nvar objA:Object = new Object();\nobjA.someAssignedProperty = \"AS3\";\nobjB.someAssignedProperty = \"AS3\";\n\ncompareGeneral(objA,objB);\n</pre>\n</blockquote>\n\n<p>In this case compareGeneral(objA,objB); returns true, though we haven't done anything useful with it yet. Here is a way you may use it. Remember that it either returns a value of true or false so we can treat it like a variable.</p>\n\n<blockquote>\n<pre>\nif(compareGeneral(objA,objB)) //same as if(compareGeneral(objA,objB)) == true)\n{\n trace(\"You have found a match!\");\n //Here you can call some other function or set a variable or whatever you require functionality wise based on a match being found.\n}\nelse\n{\n trace(\"No match could be found!\");\n}\n</pre>\n</blockquote>\n\n<p>I hope that this is able to help you understand data types and return values. I do not know what you were doing with tmp, but generally functions that return a value deal with that one thing and only that thing, so it is best that the compare function compare one thing against the other and that be the extent of the call. Whatever functionality you require with tmp can go inside its own function or method, and be called when needed.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/74649", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4540/" ]
What is the syntax to declare a type for my compare-function generator in code like the following? ``` var colName:String = ""; // actually assigned in a loop gc.sortCompareFunction = function() : ??WHAT_GOES_HERE?? { var tmp:String = colName; return function(a:Object,b:Object):int { return compareGeneral(a,b,tmp); }; }(); ```
Isn't "Function" a data type?
74,674
<p>I need to check CPU and memory usage for the server in java, anyone know how it could be done?</p>
[ { "answer_id": 74720, "author": "Tim Howland", "author_id": 4276, "author_profile": "https://Stackoverflow.com/users/4276", "pm_score": 1, "selected": false, "text": "<p>If you are using Tomcat, check out <a href=\"https://code.google.com/p/psi-probe/\" rel=\"nofollow noreferrer\">Psi Probe</a>, which lets you monitor internal and external memory consumption as well as a host of other areas.</p>\n" }, { "answer_id": 74724, "author": "moonshadow", "author_id": 11834, "author_profile": "https://Stackoverflow.com/users/11834", "pm_score": 2, "selected": false, "text": "<p>Java's <a href=\"http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Runtime.html\" rel=\"nofollow noreferrer\">Runtime</a> object can report the JVM's memory usage. For CPU consumption you'll have to use an external utility, like Unix's top or Windows Process Manager.</p>\n" }, { "answer_id": 74742, "author": "Rich Adams", "author_id": 10018, "author_profile": "https://Stackoverflow.com/users/10018", "pm_score": 3, "selected": false, "text": "<p>For memory usage, the following will work,</p>\n\n<pre><code>long total = Runtime.getRuntime().totalMemory();\nlong used = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();\n</code></pre>\n\n<p>For CPU usage, you'll need to use an external application to measure it.</p>\n" }, { "answer_id": 74753, "author": "blahspam", "author_id": 8290, "author_profile": "https://Stackoverflow.com/users/8290", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://java.sun.com/developer/technicalArticles/J2SE/jconsole.html\" rel=\"nofollow noreferrer\">JConsole</a> is an easy way to monitor a running Java application or you can use a Profiler to get more detailed information on your application. I like using the <a href=\"http://profiler.netbeans.org/\" rel=\"nofollow noreferrer\">NetBeans Profiler</a> for this.</p>\n" }, { "answer_id": 74759, "author": "Bill K", "author_id": 12943, "author_profile": "https://Stackoverflow.com/users/12943", "pm_score": 2, "selected": false, "text": "<p>If you use the runtime/totalMemory solution that has been posted in many answers here (I've done that a lot), be sure to force two garbage collections first if you want fairly accurate/consistent results.</p>\n\n<p>For effiency Java usually allows garbage to fill up all of memory before forcing a GC, and even then it's not usually a complete GC, so your results for runtime.freeMemory() always be somewhere between the \"real\" amount of free memory and 0.</p>\n\n<p>The first GC doesn't get everything, it gets most of it.</p>\n\n<p>The upswing is that if you just do the freeMemory() call you will get a number that is absolutely useless and varies widely, but if do 2 gc's first it is a very reliable gauge. It also makes the routine MUCH slower (seconds, possibly).</p>\n" }, { "answer_id": 74763, "author": "Jeremy", "author_id": 4419, "author_profile": "https://Stackoverflow.com/users/4419", "pm_score": 6, "selected": false, "text": "<p>If you are looking specifically for memory in JVM:</p>\n\n<pre><code>Runtime runtime = Runtime.getRuntime();\n\nNumberFormat format = NumberFormat.getInstance();\n\nStringBuilder sb = new StringBuilder();\nlong maxMemory = runtime.maxMemory();\nlong allocatedMemory = runtime.totalMemory();\nlong freeMemory = runtime.freeMemory();\n\nsb.append(\"free memory: \" + format.format(freeMemory / 1024) + \"&lt;br/&gt;\");\nsb.append(\"allocated memory: \" + format.format(allocatedMemory / 1024) + \"&lt;br/&gt;\");\nsb.append(\"max memory: \" + format.format(maxMemory / 1024) + \"&lt;br/&gt;\");\nsb.append(\"total free memory: \" + format.format((freeMemory + (maxMemory - allocatedMemory)) / 1024) + \"&lt;br/&gt;\");\n</code></pre>\n\n<p>However, these should be taken only as an estimate...</p>\n" }, { "answer_id": 74801, "author": "Telcontar", "author_id": 518, "author_profile": "https://Stackoverflow.com/users/518", "pm_score": 3, "selected": false, "text": "<p>Since Java 1.5 the JDK comes with a new tool: <a href=\"http://java.sun.com/developer/technicalArticles/J2SE/jconsole.html\" rel=\"noreferrer\">JConsole</a> wich can show you the CPU and memory usage of any 1.5 or later JVM. It can do charts of these parameters, export to CSV, show the number of classes loaded, the number of instances, deadlocks, threads etc...</p>\n" }, { "answer_id": 75051, "author": "Gregg", "author_id": 7994, "author_profile": "https://Stackoverflow.com/users/7994", "pm_score": 1, "selected": false, "text": "<p>The <a href=\"http://www.yourkit.com/\" rel=\"nofollow noreferrer\">YourKit</a> Java profiler is an excellent commercial solution. You can find further information in the docs on <a href=\"http://www.yourkit.com/docs/75/help/cpu_profiling/cpu_intro.jsp\" rel=\"nofollow noreferrer\">CPU profiling</a> and <a href=\"http://www.yourkit.com/docs/75/help/memory_profiling/memory_telemetry.jsp\" rel=\"nofollow noreferrer\">memory profiling</a>.</p>\n" }, { "answer_id": 75129, "author": "Javamann", "author_id": 10166, "author_profile": "https://Stackoverflow.com/users/10166", "pm_score": 4, "selected": false, "text": "<p>JMX, The MXBeans (ThreadMXBean, etc) provided will give you Memory and CPU usages.</p>\n\n<pre><code>OperatingSystemMXBean operatingSystemMXBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();\noperatingSystemMXBean.getSystemCpuLoad();\n</code></pre>\n" }, { "answer_id": 76113, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>If you are using the Sun JVM, and are interested in the internal memory usage of the application (how much out of the allocated memory your app is using) I prefer to turn on the JVMs built-in garbage collection logging. You simply add -verbose:gc to the startup command.</p>\n\n<p>From the Sun documentation:</p>\n\n<blockquote>\n <p>The command line argument -verbose:gc prints information at every\n collection. Note that the format of the -verbose:gc output is subject\n to change between releases of the J2SE platform. For example, here is\n output from a large server application:</p>\n\n<pre><code>[GC 325407K-&gt;83000K(776768K), 0.2300771 secs]\n[GC 325816K-&gt;83372K(776768K), 0.2454258 secs]\n[Full GC 267628K-&gt;83769K(776768K), 1.8479984 secs]\n</code></pre>\n \n <p>Here we see two minor collections and one major one. The numbers\n before and after the arrow</p>\n\n<pre><code>325407K-&gt;83000K (in the first line)\n</code></pre>\n \n <p>indicate the combined size of live objects before and after garbage\n collection, respectively. After minor collections the count includes\n objects that aren't necessarily alive but can't be reclaimed, either\n because they are directly alive, or because they are within or\n referenced from the tenured generation. The number in parenthesis</p>\n\n<pre><code>(776768K) (in the first line)\n</code></pre>\n \n <p>is the total available space, not counting the space in the permanent\n generation, which is the total heap minus one of the survivor spaces.\n The minor collection took about a quarter of a second.</p>\n\n<pre><code>0.2300771 secs (in the first line)\n</code></pre>\n</blockquote>\n\n<p>For more info see: <a href=\"http://java.sun.com/docs/hotspot/gc5.0/gc_tuning_5.html\" rel=\"noreferrer\">http://java.sun.com/docs/hotspot/gc5.0/gc_tuning_5.html</a></p>\n" }, { "answer_id": 7870722, "author": "Phil", "author_id": 661773, "author_profile": "https://Stackoverflow.com/users/661773", "pm_score": 2, "selected": false, "text": "<p>Here is some simple code to calculate the current memory usage in megabytes:</p>\n\n<pre><code>double currentMemory = ( (double)((double)(Runtime.getRuntime().totalMemory()/1024)/1024))- ((double)((double)(Runtime.getRuntime().freeMemory()/1024)/1024));\n</code></pre>\n" }, { "answer_id": 8038928, "author": "Fuangwith S.", "author_id": 24550, "author_profile": "https://Stackoverflow.com/users/24550", "pm_score": 0, "selected": false, "text": "<p>For Eclipse, you can use TPTP (Test and Performance Tools Platform) for analyse memory usage and etc. <a href=\"http://eclipse.org/articles/Article-TPTP-Profiling-Tool/tptpProfilingArticle.html\" rel=\"nofollow\">more information</a></p>\n" }, { "answer_id": 8973770, "author": "Dave", "author_id": 1165214, "author_profile": "https://Stackoverflow.com/users/1165214", "pm_score": 5, "selected": false, "text": "<pre><code>import java.io.File;\nimport java.text.NumberFormat;\n\npublic class SystemInfo {\n\n private Runtime runtime = Runtime.getRuntime();\n\n public String info() {\n StringBuilder sb = new StringBuilder();\n sb.append(this.osInfo());\n sb.append(this.memInfo());\n sb.append(this.diskInfo());\n return sb.toString();\n }\n\n public String osName() {\n return System.getProperty(&quot;os.name&quot;);\n }\n\n public String osVersion() {\n return System.getProperty(&quot;os.version&quot;);\n }\n\n public String osArch() {\n return System.getProperty(&quot;os.arch&quot;);\n }\n\n public long totalMem() {\n return Runtime.getRuntime().totalMemory();\n }\n\n public long usedMem() {\n return Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();\n }\n\n public String memInfo() {\n NumberFormat format = NumberFormat.getInstance();\n StringBuilder sb = new StringBuilder();\n long maxMemory = runtime.maxMemory();\n long allocatedMemory = runtime.totalMemory();\n long freeMemory = runtime.freeMemory();\n sb.append(&quot;Free memory: &quot;);\n sb.append(format.format(freeMemory / 1024));\n sb.append(&quot;&lt;br/&gt;&quot;);\n sb.append(&quot;Allocated memory: &quot;);\n sb.append(format.format(allocatedMemory / 1024));\n sb.append(&quot;&lt;br/&gt;&quot;);\n sb.append(&quot;Max memory: &quot;);\n sb.append(format.format(maxMemory / 1024));\n sb.append(&quot;&lt;br/&gt;&quot;);\n sb.append(&quot;Total free memory: &quot;);\n sb.append(format.format((freeMemory + (maxMemory - allocatedMemory)) / 1024));\n sb.append(&quot;&lt;br/&gt;&quot;);\n return sb.toString();\n\n }\n\n public String osInfo() {\n StringBuilder sb = new StringBuilder();\n sb.append(&quot;OS: &quot;);\n sb.append(this.osName());\n sb.append(&quot;&lt;br/&gt;&quot;);\n sb.append(&quot;Version: &quot;);\n sb.append(this.osVersion());\n sb.append(&quot;&lt;br/&gt;&quot;);\n sb.append(&quot;: &quot;);\n sb.append(this.osArch());\n sb.append(&quot;&lt;br/&gt;&quot;);\n sb.append(&quot;Available processors (cores): &quot;);\n sb.append(runtime.availableProcessors());\n sb.append(&quot;&lt;br/&gt;&quot;);\n return sb.toString();\n }\n\n public String diskInfo() {\n /* Get a list of all filesystem roots on this system */\n File[] roots = File.listRoots();\n StringBuilder sb = new StringBuilder();\n\n /* For each filesystem root, print some info */\n for (File root : roots) {\n sb.append(&quot;File system root: &quot;);\n sb.append(root.getAbsolutePath());\n sb.append(&quot;&lt;br/&gt;&quot;);\n sb.append(&quot;Total space (bytes): &quot;);\n sb.append(root.getTotalSpace());\n sb.append(&quot;&lt;br/&gt;&quot;);\n sb.append(&quot;Free space (bytes): &quot;);\n sb.append(root.getFreeSpace());\n sb.append(&quot;&lt;br/&gt;&quot;);\n sb.append(&quot;Usable space (bytes): &quot;);\n sb.append(root.getUsableSpace());\n sb.append(&quot;&lt;br/&gt;&quot;);\n }\n return sb.toString();\n }\n}\n</code></pre>\n" }, { "answer_id": 15733233, "author": "danieln", "author_id": 1083423, "author_profile": "https://Stackoverflow.com/users/1083423", "pm_score": 4, "selected": false, "text": "<p>From <a href=\"http://knight76.blogspot.co.il/2009/05/how-to-get-java-cpu-usage-jvm-instance.html\">here</a></p>\n\n<pre><code> OperatingSystemMXBean operatingSystemMXBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();\n RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();\n int availableProcessors = operatingSystemMXBean.getAvailableProcessors();\n long prevUpTime = runtimeMXBean.getUptime();\n long prevProcessCpuTime = operatingSystemMXBean.getProcessCpuTime();\n double cpuUsage;\n try\n {\n Thread.sleep(500);\n }\n catch (Exception ignored) { }\n\n operatingSystemMXBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();\n long upTime = runtimeMXBean.getUptime();\n long processCpuTime = operatingSystemMXBean.getProcessCpuTime();\n long elapsedCpu = processCpuTime - prevProcessCpuTime;\n long elapsedTime = upTime - prevUpTime;\n\n cpuUsage = Math.min(99F, elapsedCpu / (elapsedTime * 10000F * availableProcessors));\n System.out.println(\"Java CPU: \" + cpuUsage);\n</code></pre>\n" }, { "answer_id": 31187628, "author": "sbeliakov", "author_id": 2182091, "author_profile": "https://Stackoverflow.com/users/2182091", "pm_score": 2, "selected": false, "text": "<p>I would also add the following way to track CPU Load:</p>\n\n<pre><code>import java.lang.management.ManagementFactory;\nimport com.sun.management.OperatingSystemMXBean;\n\ndouble getCpuLoad() {\n OperatingSystemMXBean osBean =\n (com.sun.management.OperatingSystemMXBean) ManagementFactory.\n getPlatformMXBeans(OperatingSystemMXBean.class);\n return osBean.getProcessCpuLoad();\n}\n</code></pre>\n\n<p>You can read more <a href=\"https://www.java.net/community-item/hidden-java-7-features-%E2%80%93-system-and-process-cpu-load-monitoring\" rel=\"nofollow\">here</a></p>\n" }, { "answer_id": 69076398, "author": "Antonio Noack", "author_id": 4979303, "author_profile": "https://Stackoverflow.com/users/4979303", "pm_score": 0, "selected": false, "text": "<p>I want to add a note to the existing answers:</p>\n<p>These methods only keep track of JVM Memory. The actual process may consume more memory.</p>\n<p>java.nio.ByteBuffer.allocateDirect() is a function/library, that is easily missed, and indeed allocated native memory, that is not part of the Java memory management.</p>\n<p>On Linux, you may use something like this to get the actually consumed memory: <a href=\"https://linuxhint.com/check_memory_usage_process_linux/\" rel=\"nofollow noreferrer\">https://linuxhint.com/check_memory_usage_process_linux/</a></p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/74674", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13123/" ]
I need to check CPU and memory usage for the server in java, anyone know how it could be done?
If you are looking specifically for memory in JVM: ``` Runtime runtime = Runtime.getRuntime(); NumberFormat format = NumberFormat.getInstance(); StringBuilder sb = new StringBuilder(); long maxMemory = runtime.maxMemory(); long allocatedMemory = runtime.totalMemory(); long freeMemory = runtime.freeMemory(); sb.append("free memory: " + format.format(freeMemory / 1024) + "<br/>"); sb.append("allocated memory: " + format.format(allocatedMemory / 1024) + "<br/>"); sb.append("max memory: " + format.format(maxMemory / 1024) + "<br/>"); sb.append("total free memory: " + format.format((freeMemory + (maxMemory - allocatedMemory)) / 1024) + "<br/>"); ``` However, these should be taken only as an estimate...
74,723
<p>This problem has been afflicting me for quite a while and it's been really annoying.</p> <p>Every time I login after a reboot/power cycle the explorer takes some time to show up. I've taken the step of waiting for all the services to boot up and then I login, but it doesn't make any difference. The result is always the same: Some of the icons do not show up even if the applications have started.</p> <p>I've dug a bit on the code that makes one application "stick" an icon in there, but is there an API call that one can perform so explorer re-reads all that icon info? Like invalidate or redraw or something of the sort?</p> <hr> <p>Apparently, it looks like Jon was right and it's not possible to do it.</p> <p>I've followed Bob Dizzle and Mark Ransom code and build this (Delphi Code):</p> <pre><code>procedure Refresh; var hSysTray: THandle; begin hSysTray := GetSystrayHandle; SendMessage(hSysTray, WM_PAINT, 0, 0); end; function GetSystrayHandle: THandle; var hTray, hNotify, hSysPager: THandle; begin hTray := FindWindow('Shell_TrayWnd', ''); if hTray = 0 then begin Result := hTray; exit; end; hNotify := FindWindowEx(hTray, 0, 'TrayNotifyWnd', ''); if hNotify = 0 then begin Result := hNotify; exit; end; hSyspager := FindWindowEx(hNotify, 0, 'SysPager', ''); if hSyspager = 0 then begin Result := hSyspager; exit; end; Result := FindWindowEx(hSysPager, 0, 'ToolbarWindow32', 'Notification Area'); end;</code></pre> <p>But to no avail.</p> <p>I've even tried with <pre><code>InvalidateRect()</code></pre> and still no show.</p> <p>Any other suggestions?</p>
[ { "answer_id": 74769, "author": "Jonathan Sayce", "author_id": 13153, "author_profile": "https://Stackoverflow.com/users/13153", "pm_score": 2, "selected": false, "text": "<p>As far as I know that isn't possible Gustavo - it's up to each application to put its notifyicon in the systray, and ensure it's kept in the right state. </p>\n\n<p>You'll notice sometimes when explorer.exe crashes that certain icons don't reappear - this isn't because their process has crashed, simply that their application hasn't put the notifyicon in the systray when the new instance of explorer.exe started up. Once again, it's the application that's responsible.</p>\n\n<p>Sorry not to have better news for you!</p>\n" }, { "answer_id": 74781, "author": "Bob Dizzle", "author_id": 9581, "author_profile": "https://Stackoverflow.com/users/9581", "pm_score": 2, "selected": false, "text": "<p>Include following code with yours to refresh System Tray.</p>\n\n<pre><code>public const int WM_PAINT = 0xF;\n[DllImport(\"USER32.DLL\")]\npublic static extern int SendMessage(IntPtr hwnd, int msg, int character,\n IntPtr lpsText);\n\nSend WM_PAINT Message to paint System Tray which will refresh it.\nSendMessage(traynotifywnd, WM_PAINT, 0, IntPtr.Zero);\n</code></pre>\n" }, { "answer_id": 74871, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 1, "selected": false, "text": "<p>I use the following C++ code to get the window handle to the tray window. <strong>Note:</strong> this has only been tested on Windows XP.</p>\n\n<p><pre><code>HWND FindSystemTrayIcons(void)\n{\n // the system tray icons are contained in a specific window hierarchy;\n // use the Spy++ utility to see the chain\n HWND hwndTray = ::FindWindow(\"Shell_TrayWnd\", \"\");\n if (hwndTray == NULL)\n return NULL;\n HWND hwndNotifyWnd = ::FindWindowEx(hwndTray, NULL, \"TrayNotifyWnd\", \"\");\n if (hwndNotifyWnd == NULL)\n return NULL;\n HWND hwndSysPager = ::FindWindowEx(hwndNotifyWnd, NULL, \"SysPager\", \"\");\n if (hwndSysPager == NULL)\n return NULL;\n return ::FindWindowEx(hwndSysPager, NULL, \"ToolbarWindow32\", \"Notification Area\");\n}\n</pre></code></p>\n" }, { "answer_id": 1052920, "author": "Louis Davis", "author_id": 103205, "author_profile": "https://Stackoverflow.com/users/103205", "pm_score": 5, "selected": true, "text": "<p>Take a look at this blog entry: <a href=\"http://malwareanalysis.com/CommunityServer/blogs/geffner/archive/2008/02/15/985.aspx\" rel=\"noreferrer\">REFRESHING THE TASKBAR NOTIFICATION AREA</a>. I am using this code to refresh the system tray to get rid of orphaned icons and it works perfectly.\nThe blog entry is very informative and gives a great explanation of the steps the author performed to discover his solution.</p>\n\n<pre><code>#define FW(x,y) FindWindowEx(x, NULL, y, L\"\")\n\nvoid RefreshTaskbarNotificationArea()\n{\n HWND hNotificationArea;\n RECT r;\n\n GetClientRect(\n hNotificationArea = FindWindowEx(\n FW(FW(FW(NULL, L\"Shell_TrayWnd\"), L\"TrayNotifyWnd\"), L\"SysPager\"),\n NULL,\n L\"ToolbarWindow32\",\n // L\"Notification Area\"), // Windows XP\n L\"User Promoted Notification Area\"), // Windows 7 and up\n &amp;r);\n\n for (LONG x = 0; x &lt; r.right; x += 5)\n for (LONG y = 0; y &lt; r.bottom; y += 5)\n SendMessage(\n hNotificationArea,\n WM_MOUSEMOVE,\n 0,\n (y &lt;&lt; 16) + x);\n}\n</code></pre>\n" }, { "answer_id": 1052937, "author": "bugmagnet", "author_id": 426, "author_profile": "https://Stackoverflow.com/users/426", "pm_score": 2, "selected": false, "text": "<p>I covered this issue last year on my <a href=\"http://codeaholic.blogspot.com\" rel=\"nofollow noreferrer\">Codeaholic</a> weblog in an article entitled <a href=\"http://codeaholic.blogspot.com/2008/07/delphi-updating-systray.html\" rel=\"nofollow noreferrer\">[Delphi] Updating SysTray</a>. </p>\n\n<p>My solution is a Delphi ActiveX/COM DLL. The download link still works (though for how much longer I don't know as my <a href=\"http://www.plug.org.au\" rel=\"nofollow noreferrer\">PLUG</a> membership has lapsed.)</p>\n" }, { "answer_id": 18038441, "author": "Stephen Klancher", "author_id": 221018, "author_profile": "https://Stackoverflow.com/users/221018", "pm_score": 4, "selected": false, "text": "<p>Two important details for anyone using Louis's answer (from <a href=\"http://malwareanalysis.com/CommunityServer/blogs/geffner/archive/2008/02/15/985.aspx\">REFRESHING THE TASKBAR NOTIFICATION AREA</a>) on Windows 7 or Windows 8:</p>\n\n<p>First, as the answer was reflected to show, the window titled \"Notification Area\" in XP is now titled \"User Promoted Notification Area\" in Windows 7 (actually probably Vista) and up.</p>\n\n<p>Second, this code does not clear icons that are currently hidden. These are contained in a separate window. Use the original code to refresh visible icons, and the following to refresh hidden icons.</p>\n\n<pre><code>//Hidden icons\nGetClientRect(\n hNotificationArea = FindWindowEx(\n FW(NULL, L\"NotifyIconOverflowWindow\"),\n NULL,\n L\"ToolbarWindow32\",\n L\"Overflow Notification Area\"),\n &amp;r);\n\nfor (LONG x = 0; x &lt; r.right; x += 5)\n for (LONG y = 0; y &lt; r.bottom; y += 5)\n SendMessage(\n hNotificationArea,\n WM_MOUSEMOVE,\n 0,\n (y &lt;&lt; 16) + x);\n</code></pre>\n\n<p>For anyone who just needs a utility to run to accomplish this, rather than code, I built a simple exe with this update: <a href=\"http://projects.stephenklancher.com/project/id/88/Refresh_Notification_Area\">Refresh Notification Area</a></p>\n" }, { "answer_id": 53938471, "author": "user2712225", "author_id": 2712225, "author_profile": "https://Stackoverflow.com/users/2712225", "pm_score": 0, "selected": false, "text": "<p>@Skip R, and anyone else wanting to do this in C, with this code verified compiled in a recent (most recent) mingw on Windows 10 64 bit (but with the mingw 32 bit package installed), this seems to work in Windows XP / 2003 to get rid of stale notification area icons.</p>\n\n<p>I installed mingw via Chocolatey, like this:</p>\n\n<pre><code>choco install mingw --x86 --force --params \"/exception:sjlj\"\n</code></pre>\n\n<p>(your mileage may vary on that, on my system, the compiler was then installed here:</p>\n\n<pre><code>C:\\ProgramData\\chocolatey\\lib\\mingw\\tools\\install\\mingw32\\bin\\gcc.exe\n</code></pre>\n\n<p>and then a simple</p>\n\n<pre><code>gcc refresh_notification_area.c\n</code></pre>\n\n<p>yielded an a.exe which solved a stale notification area icon problem I was having on Windows 2003 (32 bit).</p>\n\n<p>The code, adapted from @Stephen Klancher above is (note this may only work on Windows XP/2003, which fulfilled my purposes):</p>\n\n<pre><code>#include &lt;windows.h&gt;\n\n#define FW(x,y) FindWindowEx(x, NULL, y, \"\")\n\nint main ()\n{\n\n HWND hNotificationArea;\n RECT r;\n\n //WinXP\n // technique found at:\n // https://stackoverflow.com/questions/74723/can-you-send-a-signal-to-windows-explorer-to-make-it-refresh-the-systray-icons#18038441\n GetClientRect(\n hNotificationArea = FindWindowEx(\n FW(FW(FW(NULL, \"Shell_TrayWnd\"), \"TrayNotifyWnd\"), \"SysPager\"),\n NULL,\n \"ToolbarWindow32\",\n \"Notification Area\"),\n &amp;r);\n\n for (LONG x = 0; x &lt; r.right; x += 5)\n for (LONG y = 0; y &lt; r.bottom; y += 5)\n SendMessage(\n hNotificationArea,\n WM_MOUSEMOVE,\n 0,\n (y &lt;&lt; 16) + x);\n\n return 0;\n\n}\n</code></pre>\n" }, { "answer_id": 56088800, "author": "Yuanhui", "author_id": 5001634, "author_profile": "https://Stackoverflow.com/users/5001634", "pm_score": 1, "selected": false, "text": "<p>After lots of times trying I found that there are three issues you must to know:</p>\n\n<ul>\n<li>The parent of hidden tray window is <code>NotifyIconOverflowWindow</code>, other than <code>Shell_TrayWnd</code>.</li>\n<li>You shouldn't use <code>caption</code> parameter of <code>FindWindowEx</code> to find a window, because these is lots of langue versions of Windows OS, they are not always be the same title Obviously.</li>\n<li>Use <code>spy++</code> of Visual Studio to find or make assurance what you want.</li>\n</ul>\n\n<p>So, I changed code from @Stephen Klancher and @Louis Davis, thank you guys.</p>\n\n<p>The following code worked for me.</p>\n\n<pre><code>#define FW(x,y) FindWindowEx(x, NULL, y, L\"\")\nvoid RefreshTaskbarNotificationArea()\n{\n HWND hNotificationArea;\n RECT r;\n GetClientRect(hNotificationArea = FindWindowEx(FW(NULL, L\"NotifyIconOverflowWindow\"), NULL, L\"ToolbarWindow32\", NULL), &amp;r);\n for (LONG x = 0; x &lt; r.right; x += 5)\n {\n for (LONG y = 0; y &lt; r.bottom; y += 5)\n {\n SendMessage(hNotificationArea, WM_MOUSEMOVE, 0, (y &lt;&lt; 16) + x);\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 73008007, "author": "tom42", "author_id": 10959519, "author_profile": "https://Stackoverflow.com/users/10959519", "pm_score": 0, "selected": false, "text": "<p>Powershell solution, put this in your script</p>\n<pre><code>Add-Type -AssemblyName System.Windows.Forms\nAdd-Type @&quot;\nusing System;\nusing System.Runtime.InteropServices;\n\npublic struct RECT {\n public int left;\n public int top;\n public int right;\n public int bottom;\n}\n\npublic class pInvoke {\n [DllImport(&quot;user32.dll&quot;)]\n public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);\n\n [DllImport(&quot;user32.dll&quot;)]\n public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);\n\n [DllImport(&quot;user32.dll&quot;)]\n public static extern bool GetClientRect(IntPtr hWnd, out RECT lpRect);\n\n [DllImport(&quot;user32.dll&quot;)]\n public static extern IntPtr SendMessage(IntPtr hWnd, uint msg, int wParam, int lParam);\n \n public static void RefreshTrayArea() {\n IntPtr systemTrayContainerHandle = FindWindow(&quot;Shell_TrayWnd&quot;, null);\n IntPtr systemTrayHandle = FindWindowEx(systemTrayContainerHandle, IntPtr.Zero, &quot;TrayNotifyWnd&quot;, null);\n IntPtr sysPagerHandle = FindWindowEx(systemTrayHandle, IntPtr.Zero, &quot;SysPager&quot;, null);\n IntPtr notificationAreaHandle = FindWindowEx(sysPagerHandle, IntPtr.Zero, &quot;ToolbarWindow32&quot;, &quot;Notification Area&quot;);\n if (notificationAreaHandle == IntPtr.Zero) {\n notificationAreaHandle = FindWindowEx(sysPagerHandle, IntPtr.Zero, &quot;ToolbarWindow32&quot;, &quot;User Promoted Notification Area&quot;);\n IntPtr notifyIconOverflowWindowHandle = FindWindow(&quot;NotifyIconOverflowWindow&quot;, null);\n IntPtr overflowNotificationAreaHandle = FindWindowEx(notifyIconOverflowWindowHandle, IntPtr.Zero, &quot;ToolbarWindow32&quot;, &quot;Overflow Notification Area&quot;);\n RefreshTrayArea(overflowNotificationAreaHandle);\n }\n RefreshTrayArea(notificationAreaHandle);\n }\n\n private static void RefreshTrayArea(IntPtr windowHandle) {\n const uint wmMousemove = 0x0200;\n RECT rect;\n GetClientRect(windowHandle, out rect);\n for (var x = 0; x &lt; rect.right; x += 5)\n for (var y = 0; y &lt; rect.bottom; y += 5)\n SendMessage(windowHandle, wmMousemove, 0, (y &lt;&lt; 16) + x);\n }\n}\n&quot;@\n</code></pre>\n<p>Then use <code>[pInvoke]::RefreshTrayArea()</code> to reset</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/74723", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8167/" ]
This problem has been afflicting me for quite a while and it's been really annoying. Every time I login after a reboot/power cycle the explorer takes some time to show up. I've taken the step of waiting for all the services to boot up and then I login, but it doesn't make any difference. The result is always the same: Some of the icons do not show up even if the applications have started. I've dug a bit on the code that makes one application "stick" an icon in there, but is there an API call that one can perform so explorer re-reads all that icon info? Like invalidate or redraw or something of the sort? --- Apparently, it looks like Jon was right and it's not possible to do it. I've followed Bob Dizzle and Mark Ransom code and build this (Delphi Code): ``` procedure Refresh; var hSysTray: THandle; begin hSysTray := GetSystrayHandle; SendMessage(hSysTray, WM_PAINT, 0, 0); end; function GetSystrayHandle: THandle; var hTray, hNotify, hSysPager: THandle; begin hTray := FindWindow('Shell_TrayWnd', ''); if hTray = 0 then begin Result := hTray; exit; end; hNotify := FindWindowEx(hTray, 0, 'TrayNotifyWnd', ''); if hNotify = 0 then begin Result := hNotify; exit; end; hSyspager := FindWindowEx(hNotify, 0, 'SysPager', ''); if hSyspager = 0 then begin Result := hSyspager; exit; end; Result := FindWindowEx(hSysPager, 0, 'ToolbarWindow32', 'Notification Area'); end; ``` But to no avail. I've even tried with ``` InvalidateRect() ``` and still no show. Any other suggestions?
Take a look at this blog entry: [REFRESHING THE TASKBAR NOTIFICATION AREA](http://malwareanalysis.com/CommunityServer/blogs/geffner/archive/2008/02/15/985.aspx). I am using this code to refresh the system tray to get rid of orphaned icons and it works perfectly. The blog entry is very informative and gives a great explanation of the steps the author performed to discover his solution. ``` #define FW(x,y) FindWindowEx(x, NULL, y, L"") void RefreshTaskbarNotificationArea() { HWND hNotificationArea; RECT r; GetClientRect( hNotificationArea = FindWindowEx( FW(FW(FW(NULL, L"Shell_TrayWnd"), L"TrayNotifyWnd"), L"SysPager"), NULL, L"ToolbarWindow32", // L"Notification Area"), // Windows XP L"User Promoted Notification Area"), // Windows 7 and up &r); for (LONG x = 0; x < r.right; x += 5) for (LONG y = 0; y < r.bottom; y += 5) SendMessage( hNotificationArea, WM_MOUSEMOVE, 0, (y << 16) + x); } ```
74,782
<p>What's the difference between eruby and erb? What considerations would drive me to choose one or the other?</p> <p>My application is generating config files for network devices (routers, load balancers, firewalls, etc.). My plan is to template the config files, using embedded ruby (via either eruby or erb) within the source files to do things like iteratively generate all the interface config blocks for a router (these blocks are all very similar, differing only in a label and an IP address). For example, I might have a config template file like this:</p> <pre><code>hostname sample-router &lt;%= r = String.new; [ ["GigabitEthernet1/1", "10.5.16.1"], ["GigabitEthernet1/2", "10.5.17.1"], ["GigabitEthernet1/3", "10.5.18.1"] ].each { |tuple| r &lt;&lt; "interface #{tuple[0]}\n" r &lt;&lt; " ip address #{tuple[1]} netmask 255.255.255.0\n" } r.chomp %&gt; logging 10.5.16.26 </code></pre> <p>which, when run through an embedded ruby interpreter (either erb or eruby), produces the following output:</p> <pre><code>hostname sample-router interface GigabitEthernet1/1 ip address 10.5.16.1 netmask 255.255.255.0 interface GigabitEthernet1/2 ip address 10.5.17.1 netmask 255.255.255.0 interface GigabitEthernet1/3 ip address 10.5.18.1 netmask 255.255.255.0 logging 10.5.16.26 </code></pre>
[ { "answer_id": 74807, "author": "Jordi Bunster", "author_id": 4272, "author_profile": "https://Stackoverflow.com/users/4272", "pm_score": 3, "selected": false, "text": "<p>Doesn't really matter, they're both the same. erb is pure ruby, eruby is written in C so it's a bit faster.</p>\n\n<p>erubis (a third one) is pure ruby, and faster than both the ones listed above. But I doubt the speed of that is the bottleneck for you, so just use erb. It's part of Ruby Standard Library.</p>\n" }, { "answer_id": 74823, "author": "Daniel Spiewak", "author_id": 9815, "author_profile": "https://Stackoverflow.com/users/9815", "pm_score": 2, "selected": false, "text": "<p>Eruby is an external executable, while erb is a library within Ruby. You would use the former if you wanted independent processing of your template files (e.g. quick-and-dirty PHP replacement), and the latter if you needed to process them within the context of some other Ruby script. It is more common to use ERB simply because it is more flexible, but I'll admit that I have been guilty of dabbling in eruby to execute <code>.rhtml</code> files for quick little utility websites.</p>\n" }, { "answer_id": 81574, "author": "Jon Wood", "author_id": 25258, "author_profile": "https://Stackoverflow.com/users/25258", "pm_score": 0, "selected": false, "text": "<p>I'm doing something similar using erb, and the performance is fine for me.</p>\n\n<p>As Jordi said though, it depends what context you want to run this in - if you're literally going to use templates like the one you listed, eruby would probably work better, but I'd guess you're actually going to be passing variables to the template, in which case you want erb.</p>\n\n<p>Just for reference, when using erb you'll need to pass it the binding for the object you want to take variables from, something like this:</p>\n\n<pre><code>device = Device.new\ndevice.add_interface(\"GigabitEthernet1/1\", \"10.5.16.1\")\ndevice.add_interface(\"GigabitEthernet1/2\", \"10.5.17.1\")\n\ntemplate = File.read(\"/path/to/your/template.erb\")\nconfig = ERB.new(template).result(device.binding)\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/74782", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13157/" ]
What's the difference between eruby and erb? What considerations would drive me to choose one or the other? My application is generating config files for network devices (routers, load balancers, firewalls, etc.). My plan is to template the config files, using embedded ruby (via either eruby or erb) within the source files to do things like iteratively generate all the interface config blocks for a router (these blocks are all very similar, differing only in a label and an IP address). For example, I might have a config template file like this: ``` hostname sample-router <%= r = String.new; [ ["GigabitEthernet1/1", "10.5.16.1"], ["GigabitEthernet1/2", "10.5.17.1"], ["GigabitEthernet1/3", "10.5.18.1"] ].each { |tuple| r << "interface #{tuple[0]}\n" r << " ip address #{tuple[1]} netmask 255.255.255.0\n" } r.chomp %> logging 10.5.16.26 ``` which, when run through an embedded ruby interpreter (either erb or eruby), produces the following output: ``` hostname sample-router interface GigabitEthernet1/1 ip address 10.5.16.1 netmask 255.255.255.0 interface GigabitEthernet1/2 ip address 10.5.17.1 netmask 255.255.255.0 interface GigabitEthernet1/3 ip address 10.5.18.1 netmask 255.255.255.0 logging 10.5.16.26 ```
Doesn't really matter, they're both the same. erb is pure ruby, eruby is written in C so it's a bit faster. erubis (a third one) is pure ruby, and faster than both the ones listed above. But I doubt the speed of that is the bottleneck for you, so just use erb. It's part of Ruby Standard Library.
74,829
<p>What should I type on the Mac OS X terminal to run a script as root?</p>
[ { "answer_id": 74830, "author": "Bob Wintemberg", "author_id": 12999, "author_profile": "https://Stackoverflow.com/users/12999", "pm_score": 2, "selected": false, "text": "<p>sudo ./<em>scriptname</em></p>\n" }, { "answer_id": 74833, "author": "dF.", "author_id": 3002, "author_profile": "https://Stackoverflow.com/users/3002", "pm_score": 7, "selected": true, "text": "<p>As in any unix-based environment, you can use the <a href=\"http://xkcd.com/149/\" rel=\"noreferrer\"><code>sudo</code></a> command:</p>\n\n<pre><code>$ sudo script-name\n</code></pre>\n\n<p>It will ask for your password (your own, not a separate <code>root</code> password).</p>\n" }, { "answer_id": 74846, "author": "Dana", "author_id": 7856, "author_profile": "https://Stackoverflow.com/users/7856", "pm_score": -1, "selected": false, "text": "<p>sudo ./scriptname</p>\n\n<p>sudo bash will basically switch you over to running a shell as root, although it's probably best to stay as su as little as possible.</p>\n" }, { "answer_id": 75016, "author": "jackrabbit", "author_id": 3707, "author_profile": "https://Stackoverflow.com/users/3707", "pm_score": 2, "selected": false, "text": "<p>In order for sudo to work the way everyone suggest, you need to be in the <code>admin</code> group.</p>\n" }, { "answer_id": 5622489, "author": "Rob B", "author_id": 141325, "author_profile": "https://Stackoverflow.com/users/141325", "pm_score": 4, "selected": false, "text": "<p>Or you can access root terminal by typing sudo -s</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/74829", "https://Stackoverflow.com", "https://Stackoverflow.com/users/877/" ]
What should I type on the Mac OS X terminal to run a script as root?
As in any unix-based environment, you can use the [`sudo`](http://xkcd.com/149/) command: ``` $ sudo script-name ``` It will ask for your password (your own, not a separate `root` password).
74,847
<p>Typically I use <code>E_ALL</code> to see anything that PHP might say about my code to try and improve it.</p> <p>I just noticed a error constant <code>E_STRICT</code>, but have never used or heard about it, is this a good setting to use for development? The manual says:</p> <blockquote> <p>Run-time notices. Enable to have PHP suggest changes to your code which will ensure the best interoperability and forward compatibility of your code. </p> </blockquote> <p>So I'm wondering if I'm using the best <code>error_reporting</code> level with <code>E_ALL</code> or would that along with <code>E_STRICT</code> be the best? Or is there any other combination I've yet to learn?</p>
[ { "answer_id": 74864, "author": "Tim Boland", "author_id": 70, "author_profile": "https://Stackoverflow.com/users/70", "pm_score": -1, "selected": false, "text": "<p>ini_set(\"display_errors\",\"2\");\nERROR_REPORTING(E_ALL);</p>\n" }, { "answer_id": 74907, "author": "Daniel Papasian", "author_id": 7548, "author_profile": "https://Stackoverflow.com/users/7548", "pm_score": 3, "selected": false, "text": "<p>In my opinion, the higher you set the error reporting level in development phase, the better. </p>\n\n<p>In a live environment, you want a slightly (but only slightly) reduced set, but you want them logged somewhere that they can't be seen by the user (I prefer <code>syslog</code>).</p>\n\n<p><a href=\"http://php.net/error_reporting\" rel=\"nofollow noreferrer\">http://php.net/error_reporting</a></p>\n\n<p><code>E_ALL | E_STRICT</code> for development with PHP before 5.2.0.</p>\n\n<p>5.2 introduces <code>E_RECOVERABLE_ERROR</code> and 5.3 introduces <code>E_DEPRECATED</code> and <code>E_USER_DEPRECATED</code>. You'll probably want to turn those on if you're running one of those versions.</p>\n\n<p>If you wanted to use magic numbers you could just set the <code>error_reporting</code> value to some fairly high value of <code>2^n-1</code> - say, <code>16777215</code>, and that would really just turn on all the bits between <code>1..n</code>. But I don't think using magic numbers is a good idea...</p>\n\n<p>In my opinion, PHP has dropped the ball a bit by having <code>E_ALL</code> not really be all. But apparently it's going to be fixed in PHP 6...</p>\n" }, { "answer_id": 74923, "author": "Jim", "author_id": 8427, "author_profile": "https://Stackoverflow.com/users/8427", "pm_score": 6, "selected": true, "text": "<p>In PHP 5, the things covered by <code>E_STRICT</code> are not covered by <code>E_ALL</code>, so to get the most information, you need to combine them:</p>\n\n<pre><code> error_reporting(E_ALL | E_STRICT);\n</code></pre>\n\n<p>In PHP 5.4, <code>E_STRICT</code> will be included in <code>E_ALL</code>, so you can use just <code>E_ALL</code>.</p>\n\n<p>You can also use</p>\n\n<pre><code>error_reporting(-1);\n</code></pre>\n\n<p>which will always enable <em>all</em> errors. Which is more semantically correct as:</p>\n\n<pre><code>error_reporting(~0);\n</code></pre>\n" }, { "answer_id": 74924, "author": "Jan Krüger", "author_id": 12471, "author_profile": "https://Stackoverflow.com/users/12471", "pm_score": 2, "selected": false, "text": "<p>In newer PHP versions, E_ALL includes more classes of errors. Since PHP 5.3, E_ALL includes everything <em>except</em> E_STRICT. In PHP 6 it will alledgedly include even that. This is a good hint: it's better to see more error messages rather than less.</p>\n\n<p>What's included in E_ALL is documented in the <a href=\"http://uk.php.net/manual/en/errorfunc.constants.php\" rel=\"nofollow noreferrer\">PHP predefined constants</a> page in the online manual.</p>\n\n<p>Personally, I think it doesn't matter all that much if you use E_STRICT. It certainly won't hurt you, especially since it may prevent you from writing scripts that have a small chance of getting broken in future versions of PHP. On the other hand, in some cases strict messages may be too noisy, perhaps especially if you're in a hurry. I suggest that you turn it on by default and turn it off when it gets annoying.</p>\n" }, { "answer_id": 74963, "author": "stormlash", "author_id": 12657, "author_profile": "https://Stackoverflow.com/users/12657", "pm_score": 1, "selected": false, "text": "<p>Depending on your long term support plans for this code, debugging with <code>E_STRICT</code> enabled may help your code to continue working in the distant future, but it is probably overkill for day-to-day use. There are two important things about <code>E_STRICT</code> to keep in mind:</p>\n\n<ol>\n<li><a href=\"http://us3.php.net/error_reporting\" rel=\"nofollow noreferrer\">Per the manual</a>, most <code>E_STRICT</code> errors are generated at compile time, not runtime. If you are increasing the error level to <code>E_ALL</code> within your code (and not via <em>php.ini</em>), you may never see <code>E_STRICT</code> errors anyway.</li>\n<li><code>E_STRICT</code> is contained within <code>E_ALL</code> under PHP 6, but not under PHP 5. If you upgrade your server to PHP6, and have <code>E_ALL</code> configured as described in #1 above, you will begin to see <code>E_STRICT</code> errors without requiring any additional changes on your part.</li>\n</ol>\n" }, { "answer_id": 75368, "author": "Pablo Borowicz", "author_id": 13275, "author_profile": "https://Stackoverflow.com/users/13275", "pm_score": 0, "selected": false, "text": "<p>Not strictly speaking of error_reporting, I'd <strong>strongly</strong> suggest using any IDE that automatically shows parsing errors and common glitches (eg, assignment in condition).</p>\n\n<p>Zend Studio for Eclipse has this feature enabled by default, and since I started using it, it has been helping me <strong>a lot</strong> at catching errors before they occur.</p>\n\n<p>For example, I had this piece of code where I was caching some data in the <code>$GLOBALS</code> variable, but I inadvertently wrote <code>$_GLOBALS</code> instead. The data never got cached up, and I'd never knew if Zend didn't tell me: \"Hey, this <code>$_GLOBALS</code> thingy appears only once, that might be an error\".</p>\n" }, { "answer_id": 75392, "author": "Eduardo Marinho", "author_id": 13211, "author_profile": "https://Stackoverflow.com/users/13211", "pm_score": 3, "selected": false, "text": "<p>Use the following in php.ini:</p>\n\n<pre><code>error_reporting = E_ALL | E_STRICT\n</code></pre>\n\n<p>Also you should install <a href=\"http://xdebug.org\" rel=\"nofollow noreferrer\" title=\"Xdebug\">Xdebug</a>, it can highlight your errors in blinding bright colors and print useful detailed information. </p>\n\n<p>Never let any error or notice in your code, even if it's harmless.</p>\n" }, { "answer_id": 7227429, "author": "RiaD", "author_id": 768110, "author_profile": "https://Stackoverflow.com/users/768110", "pm_score": 2, "selected": false, "text": "<p>You may use <code>error_reporting = -1</code><br>\nIt will always consist of all bits (even if they are not in E_ALL)</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/74847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5261/" ]
Typically I use `E_ALL` to see anything that PHP might say about my code to try and improve it. I just noticed a error constant `E_STRICT`, but have never used or heard about it, is this a good setting to use for development? The manual says: > > Run-time notices. Enable to have PHP suggest changes to your code which will ensure the best interoperability and forward compatibility of your code. > > > So I'm wondering if I'm using the best `error_reporting` level with `E_ALL` or would that along with `E_STRICT` be the best? Or is there any other combination I've yet to learn?
In PHP 5, the things covered by `E_STRICT` are not covered by `E_ALL`, so to get the most information, you need to combine them: ``` error_reporting(E_ALL | E_STRICT); ``` In PHP 5.4, `E_STRICT` will be included in `E_ALL`, so you can use just `E_ALL`. You can also use ``` error_reporting(-1); ``` which will always enable *all* errors. Which is more semantically correct as: ``` error_reporting(~0); ```
74,880
<p>Conceptually, I would like to accomplish the following but have had trouble understand how to code it properly in C#:</p> <pre><code> SomeMethod { // Member of AClass{} DoSomething; Start WorkerMethod() from BClass in another thread; DoSomethingElse; } </code></pre> <p>Then, when WorkerMethod() is complete, run this:</p> <p><pre><code> void SomeOtherMethod() // Also member of AClass{} { ... } </pre></code></p> <p>Can anyone please give an example of that? </p>
[ { "answer_id": 74917, "author": "MagicKat", "author_id": 8505, "author_profile": "https://Stackoverflow.com/users/8505", "pm_score": 1, "selected": false, "text": "<p>Check out BackgroundWorker.</p>\n" }, { "answer_id": 74948, "author": "Isak Savo", "author_id": 8521, "author_profile": "https://Stackoverflow.com/users/8521", "pm_score": 5, "selected": true, "text": "<p>The <a href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx\" rel=\"noreferrer\">BackgroundWorker</a> class was added to .NET 2.0 for this exact purpose.</p>\n\n<p>In a nutshell you do:</p>\n\n<pre><code>BackgroundWorker worker = new BackgroundWorker();\nworker.DoWork += delegate { myBClass.DoHardWork(); }\nworker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(SomeOtherMethod);\nworker.RunWorkerAsync();\n</code></pre>\n\n<p>You can also add fancy stuff like cancellation and progress reporting if you want :)</p>\n" }, { "answer_id": 75050, "author": "Randolpho", "author_id": 12716, "author_profile": "https://Stackoverflow.com/users/12716", "pm_score": 0, "selected": false, "text": "<p>Ok, I'm unsure of how you want to go about this. From your example, it looks like WorkerMethod does not create its own thread to execute under, but you want to call that method on another thread. </p>\n\n<p>In that case, create a short worker method that calls WorkerMethod then calls SomeOtherMethod, and queue that method up on another thread. Then when WorkerMethod completes, SomeOtherMethod is called. For example:</p>\n\n<pre><code>public class AClass\n{\n public void SomeMethod()\n {\n DoSomething();\n\n ThreadPool.QueueUserWorkItem(delegate(object state)\n {\n BClass.WorkerMethod();\n SomeOtherMethod();\n });\n\n DoSomethingElse();\n }\n\n private void SomeOtherMethod()\n {\n // handle the fact that WorkerMethod has completed. \n // Note that this is called on the Worker Thread, not\n // the main thread.\n }\n}\n</code></pre>\n" }, { "answer_id": 75164, "author": "Vivek", "author_id": 7418, "author_profile": "https://Stackoverflow.com/users/7418", "pm_score": 1, "selected": false, "text": "<p>Use Async Delegates:</p>\n\n<pre><code>// Method that does the real work\npublic int SomeMethod(int someInput)\n{\nThread.Sleep(20);\nConsole.WriteLine(”Processed input : {0}”,someInput);\nreturn someInput+1;\n} \n\n\n// Method that will be called after work is complete\npublic void EndSomeOtherMethod(IAsyncResult result)\n{\nSomeMethodDelegate myDelegate = result.AsyncState as SomeMethodDelegate;\n// obtain the result\nint resultVal = myDelegate.EndInvoke(result);\nConsole.WriteLine(”Returned output : {0}”,resultVal);\n}\n\n// Define a delegate\ndelegate int SomeMethodDelegate(int someInput);\nSomeMethodDelegate someMethodDelegate = SomeMethod;\n\n// Call the method that does the real work\n// Give the method name that must be called once the work is completed.\nsomeMethodDelegate.BeginInvoke(10, // Input parameter to SomeMethod()\nEndSomeOtherMethod, // Callback Method\nsomeMethodDelegate); // AsyncState\n</code></pre>\n" }, { "answer_id": 75513, "author": "ashwnacharya", "author_id": 1909, "author_profile": "https://Stackoverflow.com/users/1909", "pm_score": 2, "selected": false, "text": "<p>You have to use AsyncCallBacks. You can use AsyncCallBacks to specify a delegate to a method, and then specify CallBack Methods that get called once the execution of the target method completes.</p>\n\n<p>Here is a small Example, run and see it for yourself.</p>\n\n<p>class Program\n {</p>\n\n<pre><code> public delegate void AsyncMethodCaller();\n\n\n public static void WorkerMethod()\n {\n Console.WriteLine(\"I am the first method that is called.\");\n Thread.Sleep(5000);\n Console.WriteLine(\"Exiting from WorkerMethod.\");\n }\n\n public static void SomeOtherMethod(IAsyncResult result)\n {\n Console.WriteLine(\"I am called after the Worker Method completes.\");\n }\n\n\n\n static void Main(string[] args)\n {\n AsyncMethodCaller asyncCaller = new AsyncMethodCaller(WorkerMethod);\n AsyncCallback callBack = new AsyncCallback(SomeOtherMethod);\n IAsyncResult result = asyncCaller.BeginInvoke(callBack, null);\n Console.WriteLine(\"Worker method has been called.\");\n Console.WriteLine(\"Waiting for all invocations to complete.\");\n Console.Read();\n\n }\n}\n</code></pre>\n" }, { "answer_id": 75743, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 3, "selected": false, "text": "<p>In .Net 2 the BackgroundWorker was introduced, this makes running async operations really easy:</p>\n\n<pre><code>BackgroundWorker bw = new BackgroundWorker { WorkerReportsProgress = true };\n\nbw.DoWork += (sender, e) =&gt; \n {\n //what happens here must not touch the form\n //as it's in a different thread\n };\n\nbw.ProgressChanged += ( sender, e ) =&gt;\n {\n //update progress bars here\n };\n\nbw.RunWorkerCompleted += (sender, e) =&gt; \n {\n //now you're back in the UI thread you can update the form\n //remember to dispose of bw now\n };\n\nworker.RunWorkerAsync();\n</code></pre>\n\n<p>In .Net 1 you have to use threads.</p>\n" }, { "answer_id": 77113, "author": "Romain Verdier", "author_id": 4687, "author_profile": "https://Stackoverflow.com/users/4687", "pm_score": 2, "selected": false, "text": "<p>Although there are several possibilities here, I would use a delegate, asynchronously called using <code>BeginInvoke</code> method.</p>\n\n<p><strong>Warning</strong> : don't forget to always call <code>EndInvoke</code> on the <code>IAsyncResult</code> to avoid eventual memory leaks, as described in <a href=\"http://www.ondotnet.com/pub/a/dotnet/2003/02/24/asyncdelegates.html?page=2\" rel=\"nofollow noreferrer\">this article</a>.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/74880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10505/" ]
Conceptually, I would like to accomplish the following but have had trouble understand how to code it properly in C#: ``` SomeMethod { // Member of AClass{} DoSomething; Start WorkerMethod() from BClass in another thread; DoSomethingElse; } ``` Then, when WorkerMethod() is complete, run this: ``` void SomeOtherMethod() // Also member of AClass{} { ... } ``` Can anyone please give an example of that?
The [BackgroundWorker](http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx) class was added to .NET 2.0 for this exact purpose. In a nutshell you do: ``` BackgroundWorker worker = new BackgroundWorker(); worker.DoWork += delegate { myBClass.DoHardWork(); } worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(SomeOtherMethod); worker.RunWorkerAsync(); ``` You can also add fancy stuff like cancellation and progress reporting if you want :)
74,883
<p>I cannot seem to compile mod_dontdothat on Windows. Has anybody managed to achieve this?</p> <p>Edit:</p> <p>I've tried compiling the file according to the readme on the site and I've tried to add extra libs to reduce the link errors. Ive got the following installed:</p> <ol> <li>Apache 2.2.9</li> <li>Visual Studio 2008</li> <li>ActivePerl</li> <li>apxs-win32 from ApacheLounge</li> <li>Subversion libs and headers</li> </ol> <p>I run the following command line:</p> <pre> C:\Program Files\Apache Software Foundation\Apache2.2\bin>apxs -c -I ..\include\ svn_config.h -L ..\lib -L C:\Progra~1\Micros~1.0\VC\lib -l apr-1.lib -l aprutil- 1.lib -l svn_subr-1.lib -l libapr-1.lib -l libaprutil-1.lib -l libhttpd.lib -l l ibsvn_subr-1.lib -l mod_dav.lib mod_dontdothat.c </pre> <p>Then I get the following errors:</p> <pre> cl /nologo /MD /W3 /O2 /D WIN32 /D _WINDOWS /D NDEBUG -I"C:\PROGRA~1\APACHE~ 1\Apache2.2\include" /I"..\include\svn_config.h" /c /Fomod_dontdothat.lo mod_d ontdothat.c mod_dontdothat.c link kernel32.lib /nologo /subsystem:windows /dll /machine:I386 /libpath:"C:\PRO GRA~1\APACHE~1\Apache2.2\lib" /out:mod_dontdothat.so /libpath:"..\lib" /libpat h:"C:\Progra~1\Micros~1.0\VC\lib" apr-1.lib aprutil-1.lib svn_subr-1.lib libapr -1.lib libaprutil-1.lib libhttpd.lib libsvn_subr-1.lib mod_dav.lib mod_dontdot hat.lo Creating library mod_dontdothat.lib and object mod_dontdothat.exp mod_dontdothat.lo : error LNK2019: unresolved external symbol _dav_svn_split_uri @32 referenced in function _is_this_legal svn_subr-1.lib(io.obj) : error LNK2001: unresolved external symbol __imp__libint l_dgettext svn_subr-1.lib(subst.obj) : error LNK2001: unresolved external symbol __imp__lib intl_dgettext svn_subr-1.lib(config_auth.obj) : error LNK2001: unresolved external symbol __im p__libintl_dgettext svn_subr-1.lib(time.obj) : error LNK2001: unresolved external symbol __imp__libi ntl_dgettext svn_subr-1.lib(nls.obj) : error LNK2001: unresolved external symbol __imp__libin tl_dgettext svn_subr-1.lib(dso.obj) : error LNK2001: unresolved external symbol __imp__libin tl_dgettext svn_subr-1.lib(path.obj) : error LNK2001: unresolved external symbol __imp__libi ntl_dgettext svn_subr-1.lib(prompt.obj) : error LNK2001: unresolved external symbol __imp__li bintl_dgettext svn_subr-1.lib(error.obj) : error LNK2019: unresolved external symbol __imp__lib intl_dgettext referenced in function _print_error svn_subr-1.lib(config.obj) : error LNK2001: unresolved external symbol __imp__li bintl_dgettext svn_subr-1.lib(utf.obj) : error LNK2001: unresolved external symbol __imp__libin tl_dgettext svn_subr-1.lib(cmdline.obj) : error LNK2001: unresolved external symbol __imp__l ibintl_dgettext svn_subr-1.lib(utf.obj) : error LNK2019: unresolved external symbol __imp__libin tl_sprintf referenced in function _fuzzy_escape svn_subr-1.lib(path.obj) : error LNK2001: unresolved external symbol __imp__libi ntl_sprintf svn_subr-1.lib(cmdline.obj) : error LNK2019: unresolved external symbol __imp__l ibintl_fprintf referenced in function _svn_cmdline_init svn_subr-1.lib(config_win.obj) : error LNK2019: unresolved external symbol __imp __SHGetFolderPathA@20 referenced in function _svn_config__win_config_path svn_subr-1.lib(config_win.obj) : error LNK2019: unresolved external symbol __imp __SHGetFolderPathW@20 referenced in function _svn_config__win_config_path svn_subr-1.lib(config_win.obj) : error LNK2019: unresolved external symbol __imp __RegCloseKey@4 referenced in function _svn_config__parse_registry svn_subr-1.lib(config_win.obj) : error LNK2019: unresolved external symbol __imp __RegEnumKeyExA@32 referenced in function _svn_config__parse_registry svn_subr-1.lib(config_win.obj) : error LNK2019: unresolved external symbol __imp __RegOpenKeyExA@20 referenced in function _svn_config__parse_registry svn_subr-1.lib(config_win.obj) : error LNK2019: unresolved external symbol __imp __RegQueryValueExA@24 referenced in function _parse_section svn_subr-1.lib(config_win.obj) : error LNK2019: unresolved external symbol __imp __RegEnumValueA@32 referenced in function _parse_section svn_subr-1.lib(win32_xlate.obj) : error LNK2019: unresolved external symbol __im p__CoUninitialize@0 referenced in function _svn_subr__win32_xlate_open svn_subr-1.lib(win32_xlate.obj) : error LNK2019: unresolved external symbol __im p__CoInitializeEx@8 referenced in function _svn_subr__win32_xlate_open svn_subr-1.lib(win32_xlate.obj) : error LNK2019: unresolved external symbol __im p__CoCreateInstance@20 referenced in function _get_page_id_from_name svn_subr-1.lib(nls.obj) : error LNK2019: unresolved external symbol __imp__libin tl_bindtextdomain referenced in function _svn_nls_init svn_subr-1.lib(stream.obj) : error LNK2019: unresolved external symbol _inflate referenced in function _read_handler_gz svn_subr-1.lib(stream.obj) : error LNK2019: unresolved external symbol _inflateI nit_ referenced in function _read_handler_gz svn_subr-1.lib(stream.obj) : error LNK2019: unresolved external symbol _deflate referenced in function _write_handler_gz svn_subr-1.lib(stream.obj) : error LNK2019: unresolved external symbol _deflateI nit_ referenced in function _write_handler_gz svn_subr-1.lib(stream.obj) : error LNK2019: unresolved external symbol _deflateE nd referenced in function _close_handler_gz svn_subr-1.lib(stream.obj) : error LNK2019: unresolved external symbol _inflateE nd referenced in function _close_handler_gz mod_dontdothat.so : fatal error LNK1120: 21 unresolved externals apxs:Error: Command failed with rc=6291456 . </pre> <p>I'm not too much of a C guru, so any help in finding these unresolved external symbols will be much appreciated!</p>
[ { "answer_id": 77964, "author": "Jason Dagit", "author_id": 5113, "author_profile": "https://Stackoverflow.com/users/5113", "pm_score": 1, "selected": false, "text": "<p>Thanks for revising the question.</p>\n\n<p>It looks like a definite linker issue. I see that the first undefined symbol is related to webdav. Are you sure you have that library in the right place? I see you give a nice long path with lots of svn libs, maybe it's possible you overlooked just one?</p>\n" }, { "answer_id": 482896, "author": "agnul", "author_id": 6069, "author_profile": "https://Stackoverflow.com/users/6069", "pm_score": 2, "selected": false, "text": "<p>Googling around I've got </p>\n\n<ul>\n<li><code>mod_dav_svn.lib</code> for <code>_dav_svn_split_uri</code></li>\n<li><code>intl3_svn.lib</code> for all things <code>_libintl</code></li>\n<li><code>shell32.lib</code> for SHGetFolderPath</li>\n<li><code>advapi32.lib</code> for <code>Reg</code>istry stuff</li>\n<li><code>ole32.lib</code> for <code>CoInitialize</code> and it's ilk</li>\n<li><code>inflate</code> and <code>deflate</code> smell like <code>zlib1.lib</code> or something like that</li>\n</ul>\n\n<p>Hope that helps.</p>\n" }, { "answer_id": 499837, "author": "Eduard Wirch", "author_id": 17428, "author_profile": "https://Stackoverflow.com/users/17428", "pm_score": 4, "selected": true, "text": "<p>I managed to compile the module. Prerequisites:</p>\n\n<ul>\n<li>Apache 2.2.11</li>\n<li><a href=\"http://www.apachelounge.com/download/apxs_win32.zip\" rel=\"noreferrer\">apxs-win32</a> from www.apachelounge.com</li>\n<li>Visual Studio 2005</li>\n<li><a href=\"http://www.activestate.com/activeperl/\" rel=\"noreferrer\">Active Perl 5.8.8</a> (you need perl for apxs-win32 installation)</li>\n</ul>\n\n<p>Here is a step-by-step guide.\nDownload these packages:</p>\n\n<ul>\n<li><a href=\"http://subversion.tigris.org/files/documents/15/44595/svn-win32-1.5.5_dev.zip\" rel=\"noreferrer\">http://subversion.tigris.org/files/documents/15/44595/svn-win32-1.5.5_dev.zip</a> (we need the libraries and header files from this package)</li>\n<li><a href=\"http://subversion.tigris.org/downloads/subversion-1.5.5.zip\" rel=\"noreferrer\">http://subversion.tigris.org/downloads/subversion-1.5.5.zip</a> (we will be using the <code>mod_dav_svn</code> sources to compile a static lib)</li>\n</ul>\n\n<p>Unpack the dev package to <code>c:\\temp\\svn</code> and the other package to <code>c:\\temp\\svn-src</code> and the <code>mod_dontdothat</code> files to <code>C:\\Temp\\dontdothat</code>.</p>\n\n<p>One of the dependencies of <code>mod_dontdothat</code> module is <code>mod_dav_svn</code> module. Unfortunately you'll find the <code>mod_dav_svn</code> binary only as a shared library (DLL). You cannot link against\na DLL. So the first step is to build a static <code>mod_dav_svn</code> library:</p>\n\n<pre><code>cd C:\\Temp\\svn-src\\subversion\\mod_dav_svn\napxs -c -I ..\\include -L C:\\Temp\\svn\\lib -l libsvn_delta-1.lib -l libsvn_diff-1.lib -l libsvn_fs-1.lib -l libsvn_fs_base-1.lib -l libsvn_fs_fs-1.lib -l libsvn_fs_util-1.lib -l libsvn_repos-1.lib -l libsvn_subr-1.lib -l libapr-1.lib -l libaprutil-1.lib -l libhttpd.lib -l mod_dav.lib -l xml.lib -n mod_dav_svn mod_dav_svn.c activity.c authz.c deadprops.c liveprops.c lock.c merge.c mirror.c repos.c util.c version.c reports\\dated-rev.c reports\\file-revs.c reports\\get-locations.c reports\\get-location-segments.c reports\\get-locks.c reports\\log.c reports\\mergeinfo.c reports\\replay.c reports\\update.c\n</code></pre>\n\n<p>The apxs call will print the commands it executes. The last command is a link call which builds the DLL. Copy it replace \"link\" by \"lib\", remove the \"/dll\" param, and change the \"out\" param file name to \"<code>libmod_dav_svn.lib</code>\". You should get something similar to: </p>\n\n<pre><code>lib kernel32.lib /nologo /subsystem:windows /machine:I386 /libpath:\"C:\\PROGRA~1\\APACHE~1\\Apache2.2\\lib\" /out:libmod_dav_svn.lib /libpath:\"C:\\Temp\\svn\\lib\" libsvn_delta-1.lib libsvn_diff-1.lib libsvn_fs-1.lib libsvn_fs_base-1.lib libsvn_fs_fs-1.lib libsvn_fs_util-1.lib libsvn_repos-1.lib libsvn_subr-1.lib libapr-1.lib libaprutil-1.lib libhttpd.lib mod_dav.lib xml.lib reports\\update.lo reports\\replay.lo reports\\mergeinfo.lo reports\\log.lo reports\\get-locks.lo reports\\get-location-segments.lo reports\\get-locations.lo reports\\file-revs.lo reports\\dated-rev.lo version.lo util.lo repos.lo mirror.lo merge.lo lock.lo liveprops.lo deadprops.lo authz.lo activity.lo mod_dav_svn.lo\n</code></pre>\n\n<p>You will get some link warnings. You can ignore them. Copy the <code>libmod_dav_svn.lib</code> to the <code>mod_dontdothat</code> directory. Now start the compilation process for <code>mod_dontdothat</code>:</p>\n\n<pre><code>C:\\Temp\\dontdothat\napxs -c -I C:\\Temp\\svn\\include -L C:\\Temp\\svn\\lib -l libsvn_subr-1.lib -l libapr-1.lib -l libaprutil-1.lib -l libhttpd.lib -l mod_dav.lib -l xml.lib -l libmod_dav_svn.lib mod_dontdothat.c\napxs -i -n dontdothat mod_dontdothat.so\n</code></pre>\n\n<p>This should do the trick.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/74883", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2822/" ]
I cannot seem to compile mod\_dontdothat on Windows. Has anybody managed to achieve this? Edit: I've tried compiling the file according to the readme on the site and I've tried to add extra libs to reduce the link errors. Ive got the following installed: 1. Apache 2.2.9 2. Visual Studio 2008 3. ActivePerl 4. apxs-win32 from ApacheLounge 5. Subversion libs and headers I run the following command line: ``` C:\Program Files\Apache Software Foundation\Apache2.2\bin>apxs -c -I ..\include\ svn_config.h -L ..\lib -L C:\Progra~1\Micros~1.0\VC\lib -l apr-1.lib -l aprutil- 1.lib -l svn_subr-1.lib -l libapr-1.lib -l libaprutil-1.lib -l libhttpd.lib -l l ibsvn_subr-1.lib -l mod_dav.lib mod_dontdothat.c ``` Then I get the following errors: ``` cl /nologo /MD /W3 /O2 /D WIN32 /D _WINDOWS /D NDEBUG -I"C:\PROGRA~1\APACHE~ 1\Apache2.2\include" /I"..\include\svn_config.h" /c /Fomod_dontdothat.lo mod_d ontdothat.c mod_dontdothat.c link kernel32.lib /nologo /subsystem:windows /dll /machine:I386 /libpath:"C:\PRO GRA~1\APACHE~1\Apache2.2\lib" /out:mod_dontdothat.so /libpath:"..\lib" /libpat h:"C:\Progra~1\Micros~1.0\VC\lib" apr-1.lib aprutil-1.lib svn_subr-1.lib libapr -1.lib libaprutil-1.lib libhttpd.lib libsvn_subr-1.lib mod_dav.lib mod_dontdot hat.lo Creating library mod_dontdothat.lib and object mod_dontdothat.exp mod_dontdothat.lo : error LNK2019: unresolved external symbol _dav_svn_split_uri @32 referenced in function _is_this_legal svn_subr-1.lib(io.obj) : error LNK2001: unresolved external symbol __imp__libint l_dgettext svn_subr-1.lib(subst.obj) : error LNK2001: unresolved external symbol __imp__lib intl_dgettext svn_subr-1.lib(config_auth.obj) : error LNK2001: unresolved external symbol __im p__libintl_dgettext svn_subr-1.lib(time.obj) : error LNK2001: unresolved external symbol __imp__libi ntl_dgettext svn_subr-1.lib(nls.obj) : error LNK2001: unresolved external symbol __imp__libin tl_dgettext svn_subr-1.lib(dso.obj) : error LNK2001: unresolved external symbol __imp__libin tl_dgettext svn_subr-1.lib(path.obj) : error LNK2001: unresolved external symbol __imp__libi ntl_dgettext svn_subr-1.lib(prompt.obj) : error LNK2001: unresolved external symbol __imp__li bintl_dgettext svn_subr-1.lib(error.obj) : error LNK2019: unresolved external symbol __imp__lib intl_dgettext referenced in function _print_error svn_subr-1.lib(config.obj) : error LNK2001: unresolved external symbol __imp__li bintl_dgettext svn_subr-1.lib(utf.obj) : error LNK2001: unresolved external symbol __imp__libin tl_dgettext svn_subr-1.lib(cmdline.obj) : error LNK2001: unresolved external symbol __imp__l ibintl_dgettext svn_subr-1.lib(utf.obj) : error LNK2019: unresolved external symbol __imp__libin tl_sprintf referenced in function _fuzzy_escape svn_subr-1.lib(path.obj) : error LNK2001: unresolved external symbol __imp__libi ntl_sprintf svn_subr-1.lib(cmdline.obj) : error LNK2019: unresolved external symbol __imp__l ibintl_fprintf referenced in function _svn_cmdline_init svn_subr-1.lib(config_win.obj) : error LNK2019: unresolved external symbol __imp __SHGetFolderPathA@20 referenced in function _svn_config__win_config_path svn_subr-1.lib(config_win.obj) : error LNK2019: unresolved external symbol __imp __SHGetFolderPathW@20 referenced in function _svn_config__win_config_path svn_subr-1.lib(config_win.obj) : error LNK2019: unresolved external symbol __imp __RegCloseKey@4 referenced in function _svn_config__parse_registry svn_subr-1.lib(config_win.obj) : error LNK2019: unresolved external symbol __imp __RegEnumKeyExA@32 referenced in function _svn_config__parse_registry svn_subr-1.lib(config_win.obj) : error LNK2019: unresolved external symbol __imp __RegOpenKeyExA@20 referenced in function _svn_config__parse_registry svn_subr-1.lib(config_win.obj) : error LNK2019: unresolved external symbol __imp __RegQueryValueExA@24 referenced in function _parse_section svn_subr-1.lib(config_win.obj) : error LNK2019: unresolved external symbol __imp __RegEnumValueA@32 referenced in function _parse_section svn_subr-1.lib(win32_xlate.obj) : error LNK2019: unresolved external symbol __im p__CoUninitialize@0 referenced in function _svn_subr__win32_xlate_open svn_subr-1.lib(win32_xlate.obj) : error LNK2019: unresolved external symbol __im p__CoInitializeEx@8 referenced in function _svn_subr__win32_xlate_open svn_subr-1.lib(win32_xlate.obj) : error LNK2019: unresolved external symbol __im p__CoCreateInstance@20 referenced in function _get_page_id_from_name svn_subr-1.lib(nls.obj) : error LNK2019: unresolved external symbol __imp__libin tl_bindtextdomain referenced in function _svn_nls_init svn_subr-1.lib(stream.obj) : error LNK2019: unresolved external symbol _inflate referenced in function _read_handler_gz svn_subr-1.lib(stream.obj) : error LNK2019: unresolved external symbol _inflateI nit_ referenced in function _read_handler_gz svn_subr-1.lib(stream.obj) : error LNK2019: unresolved external symbol _deflate referenced in function _write_handler_gz svn_subr-1.lib(stream.obj) : error LNK2019: unresolved external symbol _deflateI nit_ referenced in function _write_handler_gz svn_subr-1.lib(stream.obj) : error LNK2019: unresolved external symbol _deflateE nd referenced in function _close_handler_gz svn_subr-1.lib(stream.obj) : error LNK2019: unresolved external symbol _inflateE nd referenced in function _close_handler_gz mod_dontdothat.so : fatal error LNK1120: 21 unresolved externals apxs:Error: Command failed with rc=6291456 . ``` I'm not too much of a C guru, so any help in finding these unresolved external symbols will be much appreciated!
I managed to compile the module. Prerequisites: * Apache 2.2.11 * [apxs-win32](http://www.apachelounge.com/download/apxs_win32.zip) from www.apachelounge.com * Visual Studio 2005 * [Active Perl 5.8.8](http://www.activestate.com/activeperl/) (you need perl for apxs-win32 installation) Here is a step-by-step guide. Download these packages: * <http://subversion.tigris.org/files/documents/15/44595/svn-win32-1.5.5_dev.zip> (we need the libraries and header files from this package) * <http://subversion.tigris.org/downloads/subversion-1.5.5.zip> (we will be using the `mod_dav_svn` sources to compile a static lib) Unpack the dev package to `c:\temp\svn` and the other package to `c:\temp\svn-src` and the `mod_dontdothat` files to `C:\Temp\dontdothat`. One of the dependencies of `mod_dontdothat` module is `mod_dav_svn` module. Unfortunately you'll find the `mod_dav_svn` binary only as a shared library (DLL). You cannot link against a DLL. So the first step is to build a static `mod_dav_svn` library: ``` cd C:\Temp\svn-src\subversion\mod_dav_svn apxs -c -I ..\include -L C:\Temp\svn\lib -l libsvn_delta-1.lib -l libsvn_diff-1.lib -l libsvn_fs-1.lib -l libsvn_fs_base-1.lib -l libsvn_fs_fs-1.lib -l libsvn_fs_util-1.lib -l libsvn_repos-1.lib -l libsvn_subr-1.lib -l libapr-1.lib -l libaprutil-1.lib -l libhttpd.lib -l mod_dav.lib -l xml.lib -n mod_dav_svn mod_dav_svn.c activity.c authz.c deadprops.c liveprops.c lock.c merge.c mirror.c repos.c util.c version.c reports\dated-rev.c reports\file-revs.c reports\get-locations.c reports\get-location-segments.c reports\get-locks.c reports\log.c reports\mergeinfo.c reports\replay.c reports\update.c ``` The apxs call will print the commands it executes. The last command is a link call which builds the DLL. Copy it replace "link" by "lib", remove the "/dll" param, and change the "out" param file name to "`libmod_dav_svn.lib`". You should get something similar to: ``` lib kernel32.lib /nologo /subsystem:windows /machine:I386 /libpath:"C:\PROGRA~1\APACHE~1\Apache2.2\lib" /out:libmod_dav_svn.lib /libpath:"C:\Temp\svn\lib" libsvn_delta-1.lib libsvn_diff-1.lib libsvn_fs-1.lib libsvn_fs_base-1.lib libsvn_fs_fs-1.lib libsvn_fs_util-1.lib libsvn_repos-1.lib libsvn_subr-1.lib libapr-1.lib libaprutil-1.lib libhttpd.lib mod_dav.lib xml.lib reports\update.lo reports\replay.lo reports\mergeinfo.lo reports\log.lo reports\get-locks.lo reports\get-location-segments.lo reports\get-locations.lo reports\file-revs.lo reports\dated-rev.lo version.lo util.lo repos.lo mirror.lo merge.lo lock.lo liveprops.lo deadprops.lo authz.lo activity.lo mod_dav_svn.lo ``` You will get some link warnings. You can ignore them. Copy the `libmod_dav_svn.lib` to the `mod_dontdothat` directory. Now start the compilation process for `mod_dontdothat`: ``` C:\Temp\dontdothat apxs -c -I C:\Temp\svn\include -L C:\Temp\svn\lib -l libsvn_subr-1.lib -l libapr-1.lib -l libaprutil-1.lib -l libhttpd.lib -l mod_dav.lib -l xml.lib -l libmod_dav_svn.lib mod_dontdothat.c apxs -i -n dontdothat mod_dontdothat.so ``` This should do the trick.
74,886
<p>I need to rearrange some content in various directories but it's a bit of a pain. In order to debug the application I'm working on (a ruby app) I need to move my gems into my gem folder one at a time (long story; nutshell: one is broken and I can't figure out which one).</p> <p>So I need to do something like:</p> <pre><code>sudo mv backup/gem/foo gem/ sudo mv backup/doc/foo doc/ sudo mv backup/specification/foo.gemspec specification/ </code></pre> <p>replacing "foo" each time. How can I author a simple shell script to let me do something like: gemMove("foo") and it fill in the blanks for me?</p>
[ { "answer_id": 74920, "author": "pjz", "author_id": 8002, "author_profile": "https://Stackoverflow.com/users/8002", "pm_score": 4, "selected": true, "text": "<p>Put the following into a file named <code>gemmove</code>:</p>\n<pre><code>#!/bin/bash\n\nif [ &quot;x$1&quot; == x ]; then\n echo &quot;Must have an arg&quot;\n exit 1\nfi\n\nfor d in gem doc specification ; do \n mv &quot;backup/$d/$1&quot; &quot;$d&quot;\ndone\n</code></pre>\n<p>then do</p>\n<pre><code>chmod a+x gemmove\n</code></pre>\n<p>and then call <code>sudo /path/to/gemmove foo</code> to move the foo gem from the backup dirs into the real ones</p>\n" }, { "answer_id": 74937, "author": "sirprize", "author_id": 12902, "author_profile": "https://Stackoverflow.com/users/12902", "pm_score": 1, "selected": false, "text": "<p>You could simply use the bash shell arguments, like this:</p>\n\n<pre><code>#!/bin/bash\n# This is move.sh\nmv backup/gem/$1 gem/\nmv backup/doc/$1 doc/\n# ...\n</code></pre>\n\n<p>and then execute it as:</p>\n\n<pre><code>sudo ./move.sh foo\n</code></pre>\n\n<p>Be sure make the script executable, with</p>\n\n<pre><code>chmod +x move.sh\n</code></pre>\n" }, { "answer_id": 74995, "author": "catfood", "author_id": 12802, "author_profile": "https://Stackoverflow.com/users/12802", "pm_score": 1, "selected": false, "text": "<p>in bash, something like:</p>\n\n<pre><code>function gemMove()\n{\nfilename=$1\n mv backup/gem/$filename gem/$filename\n mv backup/doc/$filename doc/$filename\n mv backup/specification/$filename.spec specification\n}\n</code></pre>\n\n<p>then you can just call <code>gemMove(\"foo\")</code> elsewhere in the script.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/74886", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10071/" ]
I need to rearrange some content in various directories but it's a bit of a pain. In order to debug the application I'm working on (a ruby app) I need to move my gems into my gem folder one at a time (long story; nutshell: one is broken and I can't figure out which one). So I need to do something like: ``` sudo mv backup/gem/foo gem/ sudo mv backup/doc/foo doc/ sudo mv backup/specification/foo.gemspec specification/ ``` replacing "foo" each time. How can I author a simple shell script to let me do something like: gemMove("foo") and it fill in the blanks for me?
Put the following into a file named `gemmove`: ``` #!/bin/bash if [ "x$1" == x ]; then echo "Must have an arg" exit 1 fi for d in gem doc specification ; do mv "backup/$d/$1" "$d" done ``` then do ``` chmod a+x gemmove ``` and then call `sudo /path/to/gemmove foo` to move the foo gem from the backup dirs into the real ones
74,902
<p>I installed Mono on my iMac last night and I immidiately had a change of heart! I don't think Mono is ready for prime time. </p> <p>The Mono website says to run the following script to uninstall:</p> <pre><code>#!/bin/sh -x #This script removes Mono from an OS X System. It must be run as root rm -r /Library/Frameworks/Mono.framework rm -r /Library/Receipts/MonoFramework-SVN.pkg cd /usr/bin for i in `ls -al | grep Mono | awk '{print $9}'`; do rm ${i} done </code></pre> <p>Has anyone had to uninstall Mono? Was it as straight forward as running the above script or do I have to do more? How messy was it? Any pointers are appreciated.</p>
[ { "answer_id": 74919, "author": "Alex Fort", "author_id": 12624, "author_profile": "https://Stackoverflow.com/users/12624", "pm_score": 0, "selected": false, "text": "<p>Mono doesn't contain a lot of fluff, so just running those commands will be fine. It's as simple as deleting all the data folders, and the binaries.</p>\n" }, { "answer_id": 74934, "author": "Adrian Petrescu", "author_id": 12171, "author_profile": "https://Stackoverflow.com/users/12171", "pm_score": 5, "selected": true, "text": "<p>The above script simply deletes everything related to Mono on your system -- and since the developers wrote it, I'm sure they didn't miss anything :) Unlike some other operating systems made by software companies that rhyme with \"Macrosoft\", uninstalling software in OS X is as simple as deleting the files, 99% of the time.. no registry or anything like that.</p>\n\n<p>So, long story short, yes, that script is probably the only thing you need to do.</p>\n" }, { "answer_id": 768240, "author": "joev", "author_id": 3449, "author_profile": "https://Stackoverflow.com/users/3449", "pm_score": 2, "selected": false, "text": "<p>To expand on feelingsofwhite.com's answer, the Mono installer for Mac OS puts the uninstall script in the /Library/Receipts directory, not in the installer image as it says in the Notes.rtf file. The Receipts directory is what the Mac OS Installer.app uses to keep track of which packages were responsible for installing which files. Usually, a list of these is kept in a .bom (\"Bill of Materials\") file, which can be explored with the lsbom command.</p>\n\n<p>In the case of Mono, they also add a whole bunch of links from your /usr/bin and man directories. Their uninstall scripts finds these and removes them. Since the uninstall script lives in a place the uninstaller deletes, you should probably copy the uninstall script somewhere else before running it:</p>\n\n<pre><code>cd\ncp /Library/Receipts/MonoFramework-2.4_7.macos10.novell.universal.pkg/Contents/Resources/uninstallMono.sh .\nsudo ./uninstallMono.sh\nrm uninstallMono.sh\n</code></pre>\n" }, { "answer_id": 4471531, "author": "Theseven7", "author_id": 505479, "author_profile": "https://Stackoverflow.com/users/505479", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://dragthor.wordpress.com/2007/07/24/uninstall-mono-on-mac-os-x/\" rel=\"nofollow\">http://dragthor.wordpress.com/2007/07/24/uninstall-mono-on-mac-os-x/</a>\nWork for me, OSX, But I Use the uninstall script file (.sh) from the Mono Installer Package.</p>\n" }, { "answer_id": 6657711, "author": "Albireo", "author_id": 91696, "author_profile": "https://Stackoverflow.com/users/91696", "pm_score": 3, "selected": false, "text": "<p>Seems the uninstall script has been slightly modified as today (2011-07-12):</p>\n\n<pre><code>#!/bin/sh -x\n\n#This script removes Mono from an OS X System. It must be run as root\n\nrm -r /Library/Frameworks/Mono.framework\n\nrm -r /Library/Receipts/MonoFramework-*\n\nfor dir in /usr/bin /usr/share/man/man1 /usr/share/man/man3 /usr/share/man/man5; do\n (cd ${dir};\n for i in `ls -al | grep /Library/Frameworks/Mono.framework/ | awk '{print $9}'`; do\n rm ${i}\n done);\ndone\n</code></pre>\n\n<p>You can find the current version <a href=\"http://www.mono-project.com/Mono:OSX#Uninstalling_Mono_on_Mac_OS_X\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>By the way: it's the same exact thing that runs the uninstaller <a href=\"https://stackoverflow.com/questions/74902/uninstall-mono-from-mac-os-x-v10-5-leopard/768240#768240\">mentioned by joev</a> (although as <a href=\"https://stackoverflow.com/questions/74902/uninstall-mono-from-mac-os-x-v10-5-leopard/768240#comment-6661580\">jochem noted</a> it is <em>not</em> located in the <code>/Library/Receipts</code>, it must be found in the installation package=.</p>\n" }, { "answer_id": 11478972, "author": "Oldfrith", "author_id": 1524730, "author_profile": "https://Stackoverflow.com/users/1524730", "pm_score": -1, "selected": false, "text": "<p>I just deleted the mono.frameworks folder. I got tired of answering \"yes\" billions of times...</p>\n" }, { "answer_id": 46015929, "author": "montrealist", "author_id": 65232, "author_profile": "https://Stackoverflow.com/users/65232", "pm_score": 3, "selected": false, "text": "<p>Year 2017 answer for those, like myself, looking at SE first and <a href=\"http://www.mono-project.com/docs/about-mono/supported-platforms/osx/#uninstalling-mono-on-mac-os-x\" rel=\"noreferrer\">official docs</a> later (FYI I know the question was for OS Leopard). Run these commands in the terminal:</p>\n\n<pre><code>sudo rm -rf /Library/Frameworks/Mono.framework\nsudo pkgutil --forget com.xamarin.mono-MDK.pkg\nsudo rm -rf /etc/paths.d/mono-commands\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/74902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/877/" ]
I installed Mono on my iMac last night and I immidiately had a change of heart! I don't think Mono is ready for prime time. The Mono website says to run the following script to uninstall: ``` #!/bin/sh -x #This script removes Mono from an OS X System. It must be run as root rm -r /Library/Frameworks/Mono.framework rm -r /Library/Receipts/MonoFramework-SVN.pkg cd /usr/bin for i in `ls -al | grep Mono | awk '{print $9}'`; do rm ${i} done ``` Has anyone had to uninstall Mono? Was it as straight forward as running the above script or do I have to do more? How messy was it? Any pointers are appreciated.
The above script simply deletes everything related to Mono on your system -- and since the developers wrote it, I'm sure they didn't miss anything :) Unlike some other operating systems made by software companies that rhyme with "Macrosoft", uninstalling software in OS X is as simple as deleting the files, 99% of the time.. no registry or anything like that. So, long story short, yes, that script is probably the only thing you need to do.
74,928
<p>I'm trying to figure out the best way to parse a GE Logician MEL trace file to make it easier to read.</p> <p>It has segments like </p> <pre>>{!gDYNAMIC_3205_1215032915_810 = (clYN)} execute>GDYNAMIC_3205_1215032915_810 = "Yes, No" results>"Yes, No" execute>end results>"Yes, No" >{!gDYNAMIC_3205_1215032893_294 = (clYN)} execute>GDYNAMIC_3205_1215032893_294 = "Yes, No" results>"Yes, No" execute>end results>"Yes, No" </pre> <p>and</p> <pre>>{IF (STR(F3205_1220646638_285, F3205_1220646638_301) == "") THEN "" ELSE (\par\tab fnHeadingFormat("Depression") + CFMT(F3205_1220646638_285, "", "Have you often been bothered by feeling down, depressed or hopeless? ", "B", "\par ") + CFMT(F3205_1220646638_301, "", "Have you often been bothered by little interest or pleasure in doing things? ", "B", "\par ") ) ENDIF} execute>call STR("No", "No") results>"NoNo" execute>"NoNo" == "" results>FALSE execute>if FALSE results>FALSE execute>call FNHEADINGFORMAT("Depression") execute>call CFMT("Depression", "B,2") results>"\fs24\b Depression\b0\fs20 " execute>"\r\n" + "\fs24\b Depression\b0\fs20 " results>"\r\n\fs24\b Depression\b0\fs20 " execute>"\r\n\fs24\b Depression\b0\fs20 " + "\r\n" results>"\r\n\fs24\b Depression\b0\fs20 \r\n" results>return "\r\n\fs24\b Depression\b0\fs20 \r\n" execute>call CFMT("No", "", "Have you often been bothered by feeling down, depressed or hopeless? ", "B", "\par ") results>"\b Have you often been bothered by feeling down, depressed or hopeless? \b0 No\par " execute>"\r\n\fs24\b Depression\b0\fs20 \r\n" + "\b Have you often been bothered by feeling down, depressed or hopeless? \b0 No\par " results>"\r\n\fs24\b Depression\b0\fs20 \r\n\b Have you often been bothered by feeling down, depressed or hopeless? \b0 No\par " execute>call CFMT("No", "", "Have you often been bothered by little interest or pleasure in doing things? ", "B", "\par ") results>"\b Have you often been bothered by little interest or pleasure in doing things? \b0 No\par " execute>"\r\n\fs24\b Depression\b0\fs20 \r\n\b Have you often been bothered by feeling down, depressed or hopeless? \b0 No\par " + "\b Have you often been bothered by little interest or pleasure in doing things? \b0 No\par " results>"\r\n\fs24\b Depression\b0\fs20 \r\n\b Have you often been bothered by feeling down, depressed or hopeless? \b0 No\par \b Have you often been bothered by little interest or pleasure in doing things? \b0 No\par " </pre> <p>I could grovel through doing it procedurally, but after all the regexps I've worked with, I find it hard to believe there's nothing out there that will let me define the rules for parsing the file in a similar manner. Am I wrong?</p>
[ { "answer_id": 74942, "author": "metadave", "author_id": 7237, "author_profile": "https://Stackoverflow.com/users/7237", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://www.antlr.org\" rel=\"nofollow noreferrer\">Antlr</a> would do the trick.</p>\n" }, { "answer_id": 74944, "author": "INS", "author_id": 13136, "author_profile": "https://Stackoverflow.com/users/13136", "pm_score": 1, "selected": false, "text": "<p>You could try ANTLR or lex/yacc.</p>\n" }, { "answer_id": 74964, "author": "Daniel Spiewak", "author_id": 9815, "author_profile": "https://Stackoverflow.com/users/9815", "pm_score": 1, "selected": false, "text": "<p>If it were me, I would derive a context-free grammar and plug it into a parser generator, probably Scala's combinator library. However, this grammar looks reasonably easy to parse by hand, just bear in mind the automata theory and it shouldn't be a problem.</p>\n" }, { "answer_id": 74970, "author": "nimish", "author_id": 3926, "author_profile": "https://Stackoverflow.com/users/3926", "pm_score": 3, "selected": true, "text": "<p>Make a grammar using ANTLR. If you're using C, lex/yacc are native. ANTLR creates native parsers in Java, Python and .NET. Your output looks like a repl; try asking the vendor for a spec on the input language.</p>\n" }, { "answer_id": 74971, "author": "Mostlyharmless", "author_id": 12881, "author_profile": "https://Stackoverflow.com/users/12881", "pm_score": 1, "selected": false, "text": "<p>I would imagine you could use tools like LEX, FLEX, CUP, ANTLR or YACC (or their equivalents for whatever programming language you are using. Any mainstream programming language has some flavor of these available.) to parse the files if they have a specific structure [more accurately, if they could be represented by a grammar]. These might not work for finer points though.</p>\n" }, { "answer_id": 75018, "author": "chessguy", "author_id": 1908025, "author_profile": "https://Stackoverflow.com/users/1908025", "pm_score": 1, "selected": false, "text": "<p>There's a programming language called Haskell that has a great parsing library you might try. www.haskell.org and <a href=\"http://legacy.cs.uu.nl/daan/parsec.html\" rel=\"nofollow noreferrer\">http://legacy.cs.uu.nl/daan/parsec.html</a> for more details</p>\n" }, { "answer_id": 91500, "author": "tsee", "author_id": 13164, "author_profile": "https://Stackoverflow.com/users/13164", "pm_score": 2, "selected": false, "text": "<p>In case you're using Perl for parsing. The Perl equivalent of YACC would be <a href=\"http://search.cpan.org/dist/Parse-Yapp\" rel=\"nofollow noreferrer\">the Parse::Yapp</a> module. When I translated a yacc grammar for use with my Perl code, the translation was mostly mechanic. There's also a recursive descent parser generator, which is slow but powerful: <a href=\"http://search.cpan.org/dist/Parse-RecDescent\" rel=\"nofollow noreferrer\">Parse::RecDescent</a>.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/74928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2531/" ]
I'm trying to figure out the best way to parse a GE Logician MEL trace file to make it easier to read. It has segments like ``` >{!gDYNAMIC_3205_1215032915_810 = (clYN)} execute>GDYNAMIC_3205_1215032915_810 = "Yes, No" results>"Yes, No" execute>end results>"Yes, No" >{!gDYNAMIC_3205_1215032893_294 = (clYN)} execute>GDYNAMIC_3205_1215032893_294 = "Yes, No" results>"Yes, No" execute>end results>"Yes, No" ``` and ``` >{IF (STR(F3205_1220646638_285, F3205_1220646638_301) == "") THEN "" ELSE (\par\tab fnHeadingFormat("Depression") + CFMT(F3205_1220646638_285, "", "Have you often been bothered by feeling down, depressed or hopeless? ", "B", "\par ") + CFMT(F3205_1220646638_301, "", "Have you often been bothered by little interest or pleasure in doing things? ", "B", "\par ") ) ENDIF} execute>call STR("No", "No") results>"NoNo" execute>"NoNo" == "" results>FALSE execute>if FALSE results>FALSE execute>call FNHEADINGFORMAT("Depression") execute>call CFMT("Depression", "B,2") results>"\fs24\b Depression\b0\fs20 " execute>"\r\n" + "\fs24\b Depression\b0\fs20 " results>"\r\n\fs24\b Depression\b0\fs20 " execute>"\r\n\fs24\b Depression\b0\fs20 " + "\r\n" results>"\r\n\fs24\b Depression\b0\fs20 \r\n" results>return "\r\n\fs24\b Depression\b0\fs20 \r\n" execute>call CFMT("No", "", "Have you often been bothered by feeling down, depressed or hopeless? ", "B", "\par ") results>"\b Have you often been bothered by feeling down, depressed or hopeless? \b0 No\par " execute>"\r\n\fs24\b Depression\b0\fs20 \r\n" + "\b Have you often been bothered by feeling down, depressed or hopeless? \b0 No\par " results>"\r\n\fs24\b Depression\b0\fs20 \r\n\b Have you often been bothered by feeling down, depressed or hopeless? \b0 No\par " execute>call CFMT("No", "", "Have you often been bothered by little interest or pleasure in doing things? ", "B", "\par ") results>"\b Have you often been bothered by little interest or pleasure in doing things? \b0 No\par " execute>"\r\n\fs24\b Depression\b0\fs20 \r\n\b Have you often been bothered by feeling down, depressed or hopeless? \b0 No\par " + "\b Have you often been bothered by little interest or pleasure in doing things? \b0 No\par " results>"\r\n\fs24\b Depression\b0\fs20 \r\n\b Have you often been bothered by feeling down, depressed or hopeless? \b0 No\par \b Have you often been bothered by little interest or pleasure in doing things? \b0 No\par " ``` I could grovel through doing it procedurally, but after all the regexps I've worked with, I find it hard to believe there's nothing out there that will let me define the rules for parsing the file in a similar manner. Am I wrong?
Make a grammar using ANTLR. If you're using C, lex/yacc are native. ANTLR creates native parsers in Java, Python and .NET. Your output looks like a repl; try asking the vendor for a spec on the input language.
74,951
<p>Flex has built in drag-n-drop for list controls, and allows you to override this. But they don't cover this in examples. The built-in functionality automatically drags the list-item, if you want to override this you find the handlers are being set up on the list itself. What I specifically want to do, is my TileList shows small thumbnails of items I can drag onto a large Canvas. As I drag an item from the list, the drag proxy should be a different image.</p> <p><strong>So, I followed the technique suggested and it only works if I explicitly set the width/height on the proxy Image. Why?</strong></p>
[ { "answer_id": 75541, "author": "Theo", "author_id": 1109, "author_profile": "https://Stackoverflow.com/users/1109", "pm_score": 2, "selected": false, "text": "<p>It's not obvious until you've tried it =) I struggled with the same thing just a few weeks ago. This was my solution:</p>\n\n<p>The list:</p>\n\n<pre><code>&lt;List&gt;\n &lt;mouseDown&gt;onListMouseDown(event)&lt;/mouseDown&gt;\n&lt;/Tree&gt;\n</code></pre>\n\n<p>The mouse down handler:</p>\n\n<pre><code>private function onMouseDown( event : MouseEvent ) : void {\n var list : List = List(event.currentTarget);\n\n // the data of the clicked row, change the name of the class to your own\n var item : MyDataType = MyDataType(list.selectedItem);\n\n var source : DragSource = new DragSource();\n\n // MyAwsomeDragFormat is the key that you will retrieve the data by in the\n // component that handles the drop\n source.addData(item, \"MyAwsomeDragFormat\");\n\n // this is the component that will be shown as the drag proxy image\n var dragView : UIComponent = new Image();\n\n // set the source of the image to a bigger version here\n dragView.source = getABiggerImage(item);\n\n // get hold of the renderer of the clicked row, to use as the drag initiator\n var rowRenderer : UIComponent = UIComponent(list.indexToItemRenderer(list.selectedIndex));\n\n DragManager.doDrag(\n rowRenderer,\n source,\n event,\n dragView\n );\n}\n</code></pre>\n\n<p>That will start the drag when the user clicks an item in the list. Notice that I don't set <code>dragEnabled</code> and the other drag-related properties on the list since I handle all that myself.</p>\n\n<p>It can be useful to add this to the beginning of the event handler:</p>\n\n<pre><code>if ( event.target is ScrollThumb || event.target is Button ) {\n return;\n}\n</code></pre>\n\n<p>Just to short circuit if the user clicks somewhere in the scrollbar. It's not very elegant but it does the job.</p>\n" }, { "answer_id": 2185111, "author": "Ola", "author_id": 264449, "author_profile": "https://Stackoverflow.com/users/264449", "pm_score": 1, "selected": false, "text": "<p>I found a simpler answer <a href=\"http://www.dgrigg.com/post.cfm/11/03/2006/DataGrid-Drag-Image\" rel=\"nofollow noreferrer\">here</a>. That example extends a DataGrid control, but you can do the same with a List control. In my case, I use an image source instead of Class:</p>\n\n<pre><code>public class CustomDragList extends List {\n\n [Bindable]\n public var dragProxyImageSource:Object;\n\n override protected function get dragImage():IUIComponent {\n var image:Image = new Image();\n image.width = 50;\n image.height = 50;\n image.source = dragProxyImageSource;\n image.owner = this;\n return image;\n }\n}\n</code></pre>\n\n<p>Then use that custom list like this:</p>\n\n<pre><code>&lt;control:CustomDragList\n allowMultipleSelection=\"true\"\n dragEnabled=\"true\" \n dragProxyImageSource=\"{someImageSource}\"\n dragStart=\"onDragStart(event)\"/&gt;\n</code></pre>\n\n<p>Where 'someImageSource' can be anything you'd normally use for an image source (embedded, linked, etc.)</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/74951", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13220/" ]
Flex has built in drag-n-drop for list controls, and allows you to override this. But they don't cover this in examples. The built-in functionality automatically drags the list-item, if you want to override this you find the handlers are being set up on the list itself. What I specifically want to do, is my TileList shows small thumbnails of items I can drag onto a large Canvas. As I drag an item from the list, the drag proxy should be a different image. **So, I followed the technique suggested and it only works if I explicitly set the width/height on the proxy Image. Why?**
It's not obvious until you've tried it =) I struggled with the same thing just a few weeks ago. This was my solution: The list: ``` <List> <mouseDown>onListMouseDown(event)</mouseDown> </Tree> ``` The mouse down handler: ``` private function onMouseDown( event : MouseEvent ) : void { var list : List = List(event.currentTarget); // the data of the clicked row, change the name of the class to your own var item : MyDataType = MyDataType(list.selectedItem); var source : DragSource = new DragSource(); // MyAwsomeDragFormat is the key that you will retrieve the data by in the // component that handles the drop source.addData(item, "MyAwsomeDragFormat"); // this is the component that will be shown as the drag proxy image var dragView : UIComponent = new Image(); // set the source of the image to a bigger version here dragView.source = getABiggerImage(item); // get hold of the renderer of the clicked row, to use as the drag initiator var rowRenderer : UIComponent = UIComponent(list.indexToItemRenderer(list.selectedIndex)); DragManager.doDrag( rowRenderer, source, event, dragView ); } ``` That will start the drag when the user clicks an item in the list. Notice that I don't set `dragEnabled` and the other drag-related properties on the list since I handle all that myself. It can be useful to add this to the beginning of the event handler: ``` if ( event.target is ScrollThumb || event.target is Button ) { return; } ``` Just to short circuit if the user clicks somewhere in the scrollbar. It's not very elegant but it does the job.
74,957
<p>In PowerShell I'm reading in a text file. I'm then doing a Foreach-Object over the text file and am only interested in the lines that do NOT contain strings that are in <code>$arrayOfStringsNotInterestedIn</code>.</p> <p>What is the syntax for this?</p> <pre><code> Get-Content $filename | Foreach-Object {$_} </code></pre>
[ { "answer_id": 75034, "author": "Mark Schill", "author_id": 9482, "author_profile": "https://Stackoverflow.com/users/9482", "pm_score": 4, "selected": false, "text": "<p>You can use the -notmatch operator to get the lines that don't have the characters you are interested in. </p>\n\n<pre><code> Get-Content $FileName | foreach-object { \n if ($_ -notmatch $arrayofStringsNotInterestedIn) { $) }\n</code></pre>\n" }, { "answer_id": 75091, "author": "Chris Bilson", "author_id": 12934, "author_profile": "https://Stackoverflow.com/users/12934", "pm_score": 7, "selected": true, "text": "<p>If $arrayofStringsNotInterestedIn is an [array] you should use -notcontains:</p>\n\n<pre><code>Get-Content $FileName | foreach-object { `\n if ($arrayofStringsNotInterestedIn -notcontains $_) { $) }\n</code></pre>\n\n<p>or better (IMO)</p>\n\n<pre><code>Get-Content $FileName | where { $arrayofStringsNotInterestedIn -notcontains $_}\n</code></pre>\n" }, { "answer_id": 143727, "author": "Bruno Gomes", "author_id": 8669, "author_profile": "https://Stackoverflow.com/users/8669", "pm_score": 2, "selected": false, "text": "<p>To exclude the lines that contain any of the strings in $arrayOfStringsNotInterestedIn, you should use:</p>\n\n<pre><code>(Get-Content $FileName) -notmatch [String]::Join('|',$arrayofStringsNotInterestedIn)\n</code></pre>\n\n<p>The code proposed by Chris only works if $arrayofStringsNotInterestedIn contains the full lines you want to exclude.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/74957", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1463/" ]
In PowerShell I'm reading in a text file. I'm then doing a Foreach-Object over the text file and am only interested in the lines that do NOT contain strings that are in `$arrayOfStringsNotInterestedIn`. What is the syntax for this? ``` Get-Content $filename | Foreach-Object {$_} ```
If $arrayofStringsNotInterestedIn is an [array] you should use -notcontains: ``` Get-Content $FileName | foreach-object { ` if ($arrayofStringsNotInterestedIn -notcontains $_) { $) } ``` or better (IMO) ``` Get-Content $FileName | where { $arrayofStringsNotInterestedIn -notcontains $_} ```
74,960
<p>I'm looking at the SOAP output from a web service I'm developing, and I noticed something curious:</p> <pre><code>&lt;soapenv:Envelope xmlns:soapenv="http://www.w3.org/2003/05/soap-envelope"&gt; &lt;soapenv:Body&gt; &lt;ns1:CreateEntityTypesResponse xmlns:ns1="http://somedomain.com/wsinterface"&gt; &lt;newKeys&gt; &lt;value&gt;1234&lt;/value&gt; &lt;/newKeys&gt; &lt;newKeys&gt; &lt;value&gt;2345&lt;/value&gt; &lt;/newKeys&gt; &lt;newKeys&gt; &lt;value&gt;3456&lt;/value&gt; &lt;/newKeys&gt; &lt;newKeys xsi:nil="1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/&gt; &lt;newKeys xsi:nil="1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/&gt; &lt;errors&gt;Error1&lt;/errors&gt; &lt;errors&gt;Error2&lt;/errors&gt; &lt;/ns1:CreateEntityTypesResponse&gt; &lt;/soapenv:Body&gt; &lt;/soapenv:Envelope&gt; </code></pre> <p>I have two newKeys elements that are nil, and both elements insert a namespace reference for xsi. I'd like to include that namespace in the soapenv:Envelope element so that the namespace reference is only sent once.</p> <p>I am using WSDL2Java to generate the service skeleton, so I don't directly have access to the Axis2 API.</p>
[ { "answer_id": 75128, "author": "Michael Sharek", "author_id": 1958, "author_profile": "https://Stackoverflow.com/users/1958", "pm_score": 3, "selected": false, "text": "<h3>Using WSDL2Java</h3>\n\n<p>If you have used the Axis2 WSDL2Java tool you're kind of stuck with what it generates for you. However you can try to change the skeleton in this section:</p>\n\n<pre><code> // create SOAP envelope with that payload\n org.apache.axiom.soap.SOAPEnvelope env = null;\n env = toEnvelope(\n getFactory(_operationClient.getOptions().getSoapVersionURI()),\n methodName,\n optimizeContent(new javax.xml.namespace.QName\n (\"http://tempuri.org/\",\"methodName\")));\n\n//adding SOAP soap_headers\n_serviceClient.addHeadersToEnvelope(env);\n</code></pre>\n\n<p>To add the namespace to the envelope add these lines somewhere in there:</p>\n\n<pre><code>OMNamespace xsi = getFactory(_operationClient.getOptions().getSoapVersionURI()).\n createOMNamespace(\"http://www.w3.org/2001/XMLSchema-instance\", \"xsi\");\n\nenv.declareNamespace(xsi);\n</code></pre>\n\n<h3>Hand-coded</h3>\n\n<p>If you are \"hand-coding\" the service you might do something like this:</p>\n\n<pre><code>SOAPFactory fac = OMAbstractFactory.getSOAP11Factory(); \nSOAPEnvelope envelope = fac.getDefaultEnvelope();\nOMNamespace xsi = fac.createOMNamespace(\"http://www.w3.org/2001/XMLSchema-instance\", \"xsi\");\n\nenvelope.declareNamespace(xsi);\nOMNamespace methodNs = fac.createOMNamespace(\"http://somedomain.com/wsinterface\", \"ns1\");\n\nOMElement method = fac.createOMElement(\"CreateEntityTypesResponse\", methodNs);\n\n//add the newkeys and errors as OMElements here...\n</code></pre>\n\n<h3>Exposing service in aar</h3>\n\n<p>If you are creating a service inside an aar you may be able to influence the SOAP message produced by using the target namespace or schema namespace properties (see <a href=\"http://wso2.org/library/2060\" rel=\"noreferrer\">this article</a>).</p>\n\n<p>Hope that helps.</p>\n" }, { "answer_id": 11162724, "author": "dodoconr", "author_id": 726202, "author_profile": "https://Stackoverflow.com/users/726202", "pm_score": 1, "selected": false, "text": "<p>Other option is that the variable MY_QNAME has the prefix empty.</p>\n\n<pre><code>public static final QName MY_QNAME = new QName(\"http://www.hello.com/Service/\",\n \"tagname\",\n \"prefix\");\n</code></pre>\n\n<p>So, if you fill it, then it works.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/74960", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13224/" ]
I'm looking at the SOAP output from a web service I'm developing, and I noticed something curious: ``` <soapenv:Envelope xmlns:soapenv="http://www.w3.org/2003/05/soap-envelope"> <soapenv:Body> <ns1:CreateEntityTypesResponse xmlns:ns1="http://somedomain.com/wsinterface"> <newKeys> <value>1234</value> </newKeys> <newKeys> <value>2345</value> </newKeys> <newKeys> <value>3456</value> </newKeys> <newKeys xsi:nil="1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/> <newKeys xsi:nil="1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/> <errors>Error1</errors> <errors>Error2</errors> </ns1:CreateEntityTypesResponse> </soapenv:Body> </soapenv:Envelope> ``` I have two newKeys elements that are nil, and both elements insert a namespace reference for xsi. I'd like to include that namespace in the soapenv:Envelope element so that the namespace reference is only sent once. I am using WSDL2Java to generate the service skeleton, so I don't directly have access to the Axis2 API.
### Using WSDL2Java If you have used the Axis2 WSDL2Java tool you're kind of stuck with what it generates for you. However you can try to change the skeleton in this section: ``` // create SOAP envelope with that payload org.apache.axiom.soap.SOAPEnvelope env = null; env = toEnvelope( getFactory(_operationClient.getOptions().getSoapVersionURI()), methodName, optimizeContent(new javax.xml.namespace.QName ("http://tempuri.org/","methodName"))); //adding SOAP soap_headers _serviceClient.addHeadersToEnvelope(env); ``` To add the namespace to the envelope add these lines somewhere in there: ``` OMNamespace xsi = getFactory(_operationClient.getOptions().getSoapVersionURI()). createOMNamespace("http://www.w3.org/2001/XMLSchema-instance", "xsi"); env.declareNamespace(xsi); ``` ### Hand-coded If you are "hand-coding" the service you might do something like this: ``` SOAPFactory fac = OMAbstractFactory.getSOAP11Factory(); SOAPEnvelope envelope = fac.getDefaultEnvelope(); OMNamespace xsi = fac.createOMNamespace("http://www.w3.org/2001/XMLSchema-instance", "xsi"); envelope.declareNamespace(xsi); OMNamespace methodNs = fac.createOMNamespace("http://somedomain.com/wsinterface", "ns1"); OMElement method = fac.createOMElement("CreateEntityTypesResponse", methodNs); //add the newkeys and errors as OMElements here... ``` ### Exposing service in aar If you are creating a service inside an aar you may be able to influence the SOAP message produced by using the target namespace or schema namespace properties (see [this article](http://wso2.org/library/2060)). Hope that helps.
75,011
<p>In a VB6 application, I have a <code>Dictionary</code> whose keys are <code>String</code>s and values are instances of a custom class. If I call <code>RemoveAll()</code> on the <code>Dictionary</code>, will it first free the custom objects? Or do I explicitly need to do this myself?</p> <pre><code>Dim d as Scripting.Dictionary d("a") = New clsCustom d("b") = New clsCustom ' Are these two lines necessary? Set d("a") = Nothing Set d("b") = Nothing d.RemoveAll </code></pre>
[ { "answer_id": 75066, "author": "Neil C. Obremski", "author_id": 9642, "author_profile": "https://Stackoverflow.com/users/9642", "pm_score": 3, "selected": true, "text": "<p>Yes, all objects in the <code>Dictionary</code> will be released after a call to <code>RemoveAll()</code>. From a performance (as in speed) standpoint I would say those lines setting the variables to <code>Nothing</code> are unnecessary, because the code has to first look them up based on the key names whereas <code>RemoveAll()</code> will enumerate and release everything in one loop.</p>\n" }, { "answer_id": 75073, "author": "Chris Smith", "author_id": 9073, "author_profile": "https://Stackoverflow.com/users/9073", "pm_score": 2, "selected": false, "text": "<p><code>RemoveAll</code> will remove all the associations from the <code>Dictionary</code>: both the keys and values. \nIt would be a reference leak for the <code>Dictionary</code> to keep a reference to the values in the <code>Dictionary</code>.</p>\n" }, { "answer_id": 75107, "author": "palehorse", "author_id": 312, "author_profile": "https://Stackoverflow.com/users/312", "pm_score": 0, "selected": false, "text": "<p>If there are no other variables that reference the items in the collection then those objects should be handed to the Garbage Collector to be cleaned up the next time the GC is run.</p>\n\n<p>If you, for example do this where sObj is a static variable somewhere then the when the GC is invoked next by the system, the first object will be cleaned up but the second which still is referenced by sObj will not.</p>\n\n<pre><code>d(\"a\") = New clsCustom\nd(\"b\") = New clsCustom code.\nsObj = d(\"b\")\n\nd.RemoveAll()\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/75011", "https://Stackoverflow.com", "https://Stackoverflow.com/users/863/" ]
In a VB6 application, I have a `Dictionary` whose keys are `String`s and values are instances of a custom class. If I call `RemoveAll()` on the `Dictionary`, will it first free the custom objects? Or do I explicitly need to do this myself? ``` Dim d as Scripting.Dictionary d("a") = New clsCustom d("b") = New clsCustom ' Are these two lines necessary? Set d("a") = Nothing Set d("b") = Nothing d.RemoveAll ```
Yes, all objects in the `Dictionary` will be released after a call to `RemoveAll()`. From a performance (as in speed) standpoint I would say those lines setting the variables to `Nothing` are unnecessary, because the code has to first look them up based on the key names whereas `RemoveAll()` will enumerate and release everything in one loop.
75,052
<p>I have a flash player that has a set of songs loaded via an xml file.</p> <p>The files dont start getting stream until you pick one.</p> <p>If I quickly cycle through each of the 8 files, then flash starts trying to download each of the 8 files at the same time.</p> <p>I'm wondering if there is a way to clear the file that is being downloaded. So that bandwidth is not eaten up if someone decides to click on lots of track names.</p> <p>Something like mySound.clear would be great, or mySound.stopStreaming..</p> <p>Has anyone had this problem before?</p> <p>Regards,</p> <p>Chris</p>
[ { "answer_id": 75323, "author": "Jon", "author_id": 12261, "author_profile": "https://Stackoverflow.com/users/12261", "pm_score": 0, "selected": false, "text": "<p>If you do something like:</p>\n\n<p>MySoundObject = undefined;</p>\n\n<p>That should do it.</p>\n" }, { "answer_id": 259891, "author": "HanClinto", "author_id": 26933, "author_profile": "https://Stackoverflow.com/users/26933", "pm_score": 2, "selected": true, "text": "<p>Check out <a href=\"http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/media/Sound.html#close()\" rel=\"nofollow noreferrer\">Sound.Close()</a>.</p>\n\n<p>From the docs: \"<em>Closes the stream, causing any download of data to cease. No data may be read from the stream after the close() method is called.</em>\"</p>\n\n<p>This is the <a href=\"http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/media/Sound.html#close()\" rel=\"nofollow noreferrer\">source code example</a> from the linked docs:</p>\n\n<pre><code>package {\n import flash.display.Sprite;\n import flash.net.URLRequest;\n import flash.media.Sound; \n import flash.text.TextField;\n import flash.text.TextFieldAutoSize;\n import flash.events.MouseEvent;\n import flash.errors.IOError;\n import flash.events.IOErrorEvent;\n\n public class Sound_closeExample extends Sprite {\n private var snd:Sound = new Sound();\n private var button:TextField = new TextField();\n private var req:URLRequest = new URLRequest(\"http://av.adobe.com/podcast/csbu_dev_podcast_epi_2.mp3\");\n\n public function Sound_closeExample() {\n button.x = 10;\n button.y = 10;\n button.text = \"START\";\n button.border = true;\n button.background = true;\n button.selectable = false;\n button.autoSize = TextFieldAutoSize.LEFT;\n\n button.addEventListener(MouseEvent.CLICK, clickHandler);\n\n this.addChild(button);\n }\n\n private function clickHandler(e:MouseEvent):void {\n\n if(button.text == \"START\") {\n\n snd.load(req);\n snd.play(); \n\n snd.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);\n\n button.text = \"STOP\";\n }\n else if(button.text == \"STOP\") {\n\n try {\n snd.close();\n button.text = \"Wait for loaded stream to finish.\";\n }\n catch (error:IOError) {\n button.text = \"Couldn't close stream \" + error.message; \n }\n }\n }\n\n private function errorHandler(event:IOErrorEvent):void {\n button.text = \"Couldn't load the file \" + event.text;\n }\n }\n}\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/75052", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6822/" ]
I have a flash player that has a set of songs loaded via an xml file. The files dont start getting stream until you pick one. If I quickly cycle through each of the 8 files, then flash starts trying to download each of the 8 files at the same time. I'm wondering if there is a way to clear the file that is being downloaded. So that bandwidth is not eaten up if someone decides to click on lots of track names. Something like mySound.clear would be great, or mySound.stopStreaming.. Has anyone had this problem before? Regards, Chris
Check out [Sound.Close()](http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/media/Sound.html#close()). From the docs: "*Closes the stream, causing any download of data to cease. No data may be read from the stream after the close() method is called.*" This is the [source code example](http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/media/Sound.html#close()) from the linked docs: ``` package { import flash.display.Sprite; import flash.net.URLRequest; import flash.media.Sound; import flash.text.TextField; import flash.text.TextFieldAutoSize; import flash.events.MouseEvent; import flash.errors.IOError; import flash.events.IOErrorEvent; public class Sound_closeExample extends Sprite { private var snd:Sound = new Sound(); private var button:TextField = new TextField(); private var req:URLRequest = new URLRequest("http://av.adobe.com/podcast/csbu_dev_podcast_epi_2.mp3"); public function Sound_closeExample() { button.x = 10; button.y = 10; button.text = "START"; button.border = true; button.background = true; button.selectable = false; button.autoSize = TextFieldAutoSize.LEFT; button.addEventListener(MouseEvent.CLICK, clickHandler); this.addChild(button); } private function clickHandler(e:MouseEvent):void { if(button.text == "START") { snd.load(req); snd.play(); snd.addEventListener(IOErrorEvent.IO_ERROR, errorHandler); button.text = "STOP"; } else if(button.text == "STOP") { try { snd.close(); button.text = "Wait for loaded stream to finish."; } catch (error:IOError) { button.text = "Couldn't close stream " + error.message; } } } private function errorHandler(event:IOErrorEvent):void { button.text = "Couldn't load the file " + event.text; } } } ```
75,057
<p>What is the best way of ensuring that a user supplied password is a strong password in a registration or change password form?</p> <p>One idea I had (in python)</p> <pre><code>def validate_password(passwd): conditions_met = 0 conditions_total = 3 if len(passwd) &gt;= 6: if passwd.lower() != passwd: conditions_met += 1 if len([x for x in passwd if x.isdigit()]) &gt; 0: conditions_met += 1 if len([x for x in passwd if not x.isalnum()]) &gt; 0: conditions_met += 1 result = False print conditions_met if conditions_met &gt;= 2: result = True return result </code></pre>
[ { "answer_id": 75108, "author": "Mostlyharmless", "author_id": 12881, "author_profile": "https://Stackoverflow.com/users/12881", "pm_score": -1, "selected": false, "text": "<p>Password strength checkers, and if you have time+resources (its justified only if you are checking for more than a few passwords) use Rainbow Tables.</p>\n" }, { "answer_id": 75109, "author": "Peter Boughton", "author_id": 9360, "author_profile": "https://Stackoverflow.com/users/9360", "pm_score": -1, "selected": false, "text": "<p>With a series of checks to ensure it meets minimum criteria:<ul>\n<li>at least 8 characters long</li>\n<li>contains at least one non-alphanumeric symbol</li>\n<li>does not match or contain username/email/etc.</li>\n<li>etc</li>\n</ul></p>\n\n<p>Here's a jQuery plugin that reports password strength (not tried it myself):\n<a href=\"http://phiras.wordpress.com/2007/04/08/password-strength-meter-a-jquery-plugin/\" rel=\"nofollow noreferrer\">http://phiras.wordpress.com/2007/04/08/password-strength-meter-a-jquery-plugin/</a></p>\n\n<p>And the same thing ported to PHP:\n<a href=\"http://www.alixaxel.com/wordpress/2007/06/09/php-password-strength-algorithm/\" rel=\"nofollow noreferrer\">http://www.alixaxel.com/wordpress/2007/06/09/php-password-strength-algorithm/</a></p>\n" }, { "answer_id": 75149, "author": "VirtuosiMedia", "author_id": 13281, "author_profile": "https://Stackoverflow.com/users/13281", "pm_score": 4, "selected": false, "text": "<p>Depending on the language, I usually use regular expressions to check if it has:</p>\n\n<ul>\n<li>At least one uppercase and one\nlowercase letter</li>\n<li>At least one number</li>\n<li>At least one special character</li>\n<li>A length of at least six characters</li>\n</ul>\n\n<p>You can require all of the above, or use a strength meter type of script. For my strength meter, if the password has the right length, it is evaluated as follows:</p>\n\n<ul>\n<li>One condition met: weak password</li>\n<li>Two conditions met: medium password</li>\n<li>All conditions met: strong password</li>\n</ul>\n\n<p>You can adjust the above to meet your needs.</p>\n" }, { "answer_id": 75173, "author": "David Webb", "author_id": 3171, "author_profile": "https://Stackoverflow.com/users/3171", "pm_score": 2, "selected": false, "text": "<p>The two simplest metrics to check for are:</p>\n\n<ol>\n<li>Length. I'd say 8 characters as a minimum.</li>\n<li>Number of different character classes the password contains. These are usually, lowercase letters, uppercase letters, numbers and punctuation and other symbols. A strong password will contain characters from at least three of these classes; if you force a number or other non-alphabetic character you significantly reduce the effectiveness of dictionary attacks.</li>\n</ol>\n" }, { "answer_id": 75498, "author": "user9116", "author_id": 9116, "author_profile": "https://Stackoverflow.com/users/9116", "pm_score": 3, "selected": false, "text": "<p>The object-oriented approach would be a set of rules. Assign a weight to each rule and iterate through them. In psuedo-code:</p>\n\n<pre><code>abstract class Rule {\n\n float weight;\n\n float calculateScore( string password );\n\n}\n</code></pre>\n\n<p>Calculating the total score:</p>\n\n<pre><code>float getPasswordStrength( string password ) { \n\n float totalWeight = 0.0f;\n float totalScore = 0.0f;\n\n foreach ( rule in rules ) {\n\n totalWeight += weight;\n totalScore += rule.calculateScore( password ) * rule.weight;\n\n }\n\n return (totalScore / totalWeight) / rules.count;\n\n}\n</code></pre>\n\n<p>An example rule algorithm, based on number of character classes present:</p>\n\n<pre><code>float calculateScore( string password ) {\n\n float score = 0.0f;\n\n // NUMBER_CLASS is a constant char array { '0', '1', '2', ... }\n if ( password.contains( NUMBER_CLASS ) )\n score += 1.0f;\n\n if ( password.contains( UPPERCASE_CLASS ) )\n score += 1.0f;\n\n if ( password.contains( LOWERCASE_CLASS ) )\n score += 1.0f;\n\n // Sub rule as private method\n if ( containsPunctuation( password ) )\n score += 1.0f;\n\n return score / 4.0f;\n\n}\n</code></pre>\n" }, { "answer_id": 1872514, "author": "SapphireSun", "author_id": 210920, "author_profile": "https://Stackoverflow.com/users/210920", "pm_score": 0, "selected": false, "text": "<p>I don't know if anyone will find this useful, but I really liked the idea of a ruleset as suggested by phear so I went and wrote a rule Python 2.6 class (although it's probably compatible with 2.5):</p>\n\n<pre><code>import re\n\nclass SecurityException(Exception):\n pass\n\nclass Rule:\n \"\"\"Creates a rule to evaluate against a string.\n Rules can be regex patterns or a boolean returning function.\n Whether a rule is inclusive or exclusive is decided by the sign\n of the weight. Positive weights are inclusive, negative weights are\n exclusive. \n\n\n Call score() to return either 0 or the weight if the rule \n is fufilled. \n\n Raises a SecurityException if a required rule is violated.\n \"\"\"\n\n def __init__(self,rule,weight=1,required=False,name=u\"The Unnamed Rule\"):\n try:\n getattr(rule,\"__call__\")\n except AttributeError:\n self.rule = re.compile(rule) # If a regex, compile\n else:\n self.rule = rule # Otherwise it's a function and it should be scored using it\n\n if weight == 0:\n return ValueError(u\"Weights can not be 0\")\n\n self.weight = weight\n self.required = required\n self.name = name\n\n def exclusive(self):\n return self.weight &lt; 0\n def inclusive(self):\n return self.weight &gt;= 0\n exclusive = property(exclusive)\n inclusive = property(inclusive)\n\n def _score_regex(self,password):\n match = self.rule.search(password)\n if match is None:\n if self.exclusive: # didn't match an exclusive rule\n return self.weight\n elif self.inclusive and self.required: # didn't match on a required inclusive rule\n raise SecurityException(u\"Violation of Rule: %s by input \\\"%s\\\"\" % (self.name.title(), password))\n elif self.inclusive and not self.required:\n return 0\n else:\n if self.inclusive:\n return self.weight\n elif self.exclusive and self.required:\n raise SecurityException(u\"Violation of Rule: %s by input \\\"%s\\\"\" % (self.name,password))\n elif self.exclusive and not self.required:\n return 0\n\n return 0\n\n def score(self,password):\n try:\n getattr(self.rule,\"__call__\")\n except AttributeError:\n return self._score_regex(password)\n else:\n return self.rule(password) * self.weight\n\n def __unicode__(self):\n return u\"%s (%i)\" % (self.name.title(), self.weight)\n\n def __str__(self):\n return self.__unicode__()\n</code></pre>\n\n<p>I hope someone finds this useful!</p>\n\n<p>Example Usage:</p>\n\n<pre><code>rules = [ Rule(\"^foobar\",weight=20,required=True,name=u\"The Fubared Rule\"), ]\ntry:\n score = 0\n for rule in rules:\n score += rule.score()\nexcept SecurityException e:\n print e \nelse:\n print score\n</code></pre>\n\n<p>DISCLAIMER: Not unit tested</p>\n" }, { "answer_id": 4191130, "author": "Sean Reifschneider", "author_id": 267126, "author_profile": "https://Stackoverflow.com/users/267126", "pm_score": 2, "selected": false, "text": "<p>Cracklib is great, and in newer packages there is a Python module available for it. However, on systems that don't yet have it, such as CentOS 5, I've written a ctypes wrapper for the system cryptlib. This would also work on a system that you can't install python-libcrypt. It <em>does</em> require python with ctypes available, so for CentOS 5 you have to install and use the python26 package.</p>\n\n<p>It also has the advantage that it can take the username and check for passwords that contain it or are substantially similar, like the libcrypt \"FascistGecos\" function but without requiring the user to exist in /etc/passwd.</p>\n\n<p>My <a href=\"http://github.com/linsomniac/python-ctypescracklib\" rel=\"nofollow\">ctypescracklib library is available on github</a></p>\n\n<p>Some example uses:</p>\n\n<pre><code>&gt;&gt;&gt; FascistCheck('jafo1234', 'jafo')\n'it is based on your username'\n&gt;&gt;&gt; FascistCheck('myofaj123', 'jafo')\n'it is based on your username'\n&gt;&gt;&gt; FascistCheck('jxayfoxo', 'jafo')\n'it is too similar to your username'\n&gt;&gt;&gt; FascistCheck('cretse')\n'it is based on a dictionary word'\n</code></pre>\n" }, { "answer_id": 4298717, "author": "siznax", "author_id": 59037, "author_profile": "https://Stackoverflow.com/users/59037", "pm_score": 2, "selected": false, "text": "<p>after reading the other helpful answers, this is what i'm going with:</p>\n\n<p>-1 same as username<br>\n+0 contains username<br>\n+1 more than 7 chars<br>\n+1 more than 11 chars<br>\n+1 contains digits<br>\n+1 mix of lower and uppercase<br>\n+1 contains punctuation<br>\n+1 non-printable char </p>\n\n<p>pwscore.py:</p>\n\n<pre><code>import re\nimport string\nmax_score = 6\ndef score(username,passwd):\n if passwd == username:\n return -1\n if username in passwd:\n return 0\n score = 0\n if len(passwd) &gt; 7:\n score+=1\n if len(passwd) &gt; 11:\n score+=1\n if re.search('\\d+',passwd):\n score+=1\n if re.search('[a-z]',passwd) and re.search('[A-Z]',passwd):\n score+=1\n if len([x for x in passwd if x in string.punctuation]) &gt; 0:\n score+=1\n if len([x for x in passwd if x not in string.printable]) &gt; 0:\n score+=1\n return score\n</code></pre>\n\n<p>example usage:</p>\n\n<pre><code>import pwscore\n score = pwscore(username,passwd)\n if score &lt; 3:\n return \"weak password (score=\" \n + str(score) + \"/\"\n + str(pwscore.max_score)\n + \"), try again.\"\n</code></pre>\n\n<p>probably not the most efficient, but seems reasonable. \nnot sure FascistCheck => 'too similar to username' is \nworth it.</p>\n\n<p>'abc123ABC!@£' = score 6/6 if not a superset of username</p>\n\n<p>maybe that should score lower.</p>\n" }, { "answer_id": 7285380, "author": "varun", "author_id": 95967, "author_profile": "https://Stackoverflow.com/users/95967", "pm_score": 1, "selected": false, "text": "<p>Well this is what I use:</p>\n\n<pre><code> var getStrength = function (passwd) {\n intScore = 0;\n intScore = (intScore + passwd.length);\n if (passwd.match(/[a-z]/)) {\n intScore = (intScore + 1);\n }\n if (passwd.match(/[A-Z]/)) {\n intScore = (intScore + 5);\n }\n if (passwd.match(/\\d+/)) {\n intScore = (intScore + 5);\n }\n if (passwd.match(/(\\d.*\\d)/)) {\n intScore = (intScore + 5);\n }\n if (passwd.match(/[!,@#$%^&amp;*?_~]/)) {\n intScore = (intScore + 5);\n }\n if (passwd.match(/([!,@#$%^&amp;*?_~].*[!,@#$%^&amp;*?_~])/)) {\n intScore = (intScore + 5);\n }\n if (passwd.match(/[a-z]/) &amp;&amp; passwd.match(/[A-Z]/)) {\n intScore = (intScore + 2);\n }\n if (passwd.match(/\\d/) &amp;&amp; passwd.match(/\\D/)) {\n intScore = (intScore + 2);\n }\n if (passwd.match(/[a-z]/) &amp;&amp; passwd.match(/[A-Z]/) &amp;&amp; passwd.match(/\\d/) &amp;&amp; passwd.match(/[!,@#$%^&amp;*?_~]/)) {\n intScore = (intScore + 2);\n }\n return intScore;\n} \n</code></pre>\n" }, { "answer_id": 50489987, "author": "Johan", "author_id": 650492, "author_profile": "https://Stackoverflow.com/users/650492", "pm_score": 4, "selected": true, "text": "<p><strong>1: Eliminate often used passwords</strong><br>\nCheck the entered passwords against a list of often used passwords (see e.g. the top 100.000 passwords in the leaked LinkedIn password list: <a href=\"http://www.adeptus-mechanicus.com/codex/linkhap/combo_not.zip\" rel=\"noreferrer\">http://www.adeptus-mechanicus.com/codex/linkhap/combo_not.zip</a>), make sure to include <a href=\"http://www.gamehouse.com/blog/leet-speak-cheat-sheet/\" rel=\"noreferrer\">leetspeek substitutions</a>:\nA@, E3, B8, S5, etc.<br>\nRemove parts of the password that hit against this list from the entered phrase, before going to part 2 below.</p>\n\n<p><strong>2: Don't force any rules on the user</strong> </p>\n\n<p>The golden rule of passwords is that longer is better.<br>\nForget about forced use of caps, numbers, and symbols because (the vast majority of) users will:\n- Make the first letter a capital;\n- Put the number <code>1</code> at the end;\n- Put a <code>!</code> after that if a symbol is required.</p>\n\n<p><strong>Instead check password strength</strong> </p>\n\n<p>For a decent starting point see: <a href=\"http://www.passwordmeter.com/\" rel=\"noreferrer\">http://www.passwordmeter.com/</a> </p>\n\n<p>I suggest as a minimum the following rules:</p>\n\n<pre><code>Additions (better passwords)\n-----------------------------\n- Number of Characters Flat +(n*4) \n- Uppercase Letters Cond/Incr +((len-n)*2) \n- Lowercase Letters Cond/Incr +((len-n)*2) \n- Numbers Cond +(n*4) \n- Symbols Flat +(n*6)\n- Middle Numbers or Symbols Flat +(n*2) \n- Shannon Entropy Complex *EntropyScore\n\nDeductions (worse passwords)\n----------------------------- \n- Letters Only Flat -n \n- Numbers Only Flat -(n*16) \n- Repeat Chars (Case Insensitive) Complex - \n- Consecutive Uppercase Letters Flat -(n*2) \n- Consecutive Lowercase Letters Flat -(n*2) \n- Consecutive Numbers Flat -(n*2) \n- Sequential Letters (3+) Flat -(n*3) \n- Sequential Numbers (3+) Flat -(n*3) \n- Sequential Symbols (3+) Flat -(n*3)\n- Repeated words Complex - \n- Only 1st char is uppercase Flat -n\n- Last (non symbol) char is number Flat -n\n- Only last char is symbol Flat -n\n</code></pre>\n\n<p>Just following <a href=\"http://www.passwordmeter.com/\" rel=\"noreferrer\">passwordmeter</a> is not enough, because sure enough its naive algorithm sees <kbd>Password1!</kbd> as good, whereas it is exceptionally weak.\nMake sure to disregard initial capital letters when scoring as well as trailing numbers and symbols (as per the last 3 rules).</p>\n\n<p><strong>Calculating Shannon entropy</strong><br>\nSee: <a href=\"https://stackoverflow.com/questions/15450192/fastest-way-to-compute-entropy-in-python\">Fastest way to compute entropy in Python</a></p>\n\n<p><strong>3: Don't allow any passwords that are too weak</strong><br>\nRather than forcing the user to bend to self-defeating rules, allow anything that will give a high enough score. How high depends on your use case. </p>\n\n<p><strong>And most importantly</strong><br>\nWhen you accept the password and store it in a database, <a href=\"https://stackoverflow.com/questions/4578431/how-to-hash-and-salt-passwords\">make sure to salt and hash it!</a>.</p>\n" }, { "answer_id": 54055977, "author": "Braiam", "author_id": 792066, "author_profile": "https://Stackoverflow.com/users/792066", "pm_score": -1, "selected": false, "text": "<blockquote>\n <p>What is the best way of ensuring that a user supplied password is a strong password in a registration or change password form?</p>\n</blockquote>\n\n<p>Don't evaluate complexity and or strength, users will find a way to fool your system or get so frustrated that they will leave. That will only get you situations <a href=\"https://xkcd.com/936/\" rel=\"nofollow noreferrer\">like this</a>. Just require certain length and that leaked passwords aren't used. Bonus points: make sure whatever you implement allows the use of password managers and/or 2FA.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/75057", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13099/" ]
What is the best way of ensuring that a user supplied password is a strong password in a registration or change password form? One idea I had (in python) ``` def validate_password(passwd): conditions_met = 0 conditions_total = 3 if len(passwd) >= 6: if passwd.lower() != passwd: conditions_met += 1 if len([x for x in passwd if x.isdigit()]) > 0: conditions_met += 1 if len([x for x in passwd if not x.isalnum()]) > 0: conditions_met += 1 result = False print conditions_met if conditions_met >= 2: result = True return result ```
**1: Eliminate often used passwords** Check the entered passwords against a list of often used passwords (see e.g. the top 100.000 passwords in the leaked LinkedIn password list: <http://www.adeptus-mechanicus.com/codex/linkhap/combo_not.zip>), make sure to include [leetspeek substitutions](http://www.gamehouse.com/blog/leet-speak-cheat-sheet/): A@, E3, B8, S5, etc. Remove parts of the password that hit against this list from the entered phrase, before going to part 2 below. **2: Don't force any rules on the user** The golden rule of passwords is that longer is better. Forget about forced use of caps, numbers, and symbols because (the vast majority of) users will: - Make the first letter a capital; - Put the number `1` at the end; - Put a `!` after that if a symbol is required. **Instead check password strength** For a decent starting point see: <http://www.passwordmeter.com/> I suggest as a minimum the following rules: ``` Additions (better passwords) ----------------------------- - Number of Characters Flat +(n*4) - Uppercase Letters Cond/Incr +((len-n)*2) - Lowercase Letters Cond/Incr +((len-n)*2) - Numbers Cond +(n*4) - Symbols Flat +(n*6) - Middle Numbers or Symbols Flat +(n*2) - Shannon Entropy Complex *EntropyScore Deductions (worse passwords) ----------------------------- - Letters Only Flat -n - Numbers Only Flat -(n*16) - Repeat Chars (Case Insensitive) Complex - - Consecutive Uppercase Letters Flat -(n*2) - Consecutive Lowercase Letters Flat -(n*2) - Consecutive Numbers Flat -(n*2) - Sequential Letters (3+) Flat -(n*3) - Sequential Numbers (3+) Flat -(n*3) - Sequential Symbols (3+) Flat -(n*3) - Repeated words Complex - - Only 1st char is uppercase Flat -n - Last (non symbol) char is number Flat -n - Only last char is symbol Flat -n ``` Just following [passwordmeter](http://www.passwordmeter.com/) is not enough, because sure enough its naive algorithm sees `Password1!` as good, whereas it is exceptionally weak. Make sure to disregard initial capital letters when scoring as well as trailing numbers and symbols (as per the last 3 rules). **Calculating Shannon entropy** See: [Fastest way to compute entropy in Python](https://stackoverflow.com/questions/15450192/fastest-way-to-compute-entropy-in-python) **3: Don't allow any passwords that are too weak** Rather than forcing the user to bend to self-defeating rules, allow anything that will give a high enough score. How high depends on your use case. **And most importantly** When you accept the password and store it in a database, [make sure to salt and hash it!](https://stackoverflow.com/questions/4578431/how-to-hash-and-salt-passwords).
75,076
<p>I would like to be able to obtain all the parameter values from the stack frame in .NET. A bit like how you're able to see the values in the call stack when in the Visual Studio debugger. My approach has concentrated on using the <a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.stackframe%28v=vs.71%29.aspx" rel="noreferrer">StackFrame class</a> and then to reflect over a <a href="http://msdn.microsoft.com/en-us/library/system.reflection.parameterinfo%28v=vs.71%29.aspx" rel="noreferrer">ParameterInfo</a> array. I've had success with reflection and properties, but this is proving a bit trickier.</p> <p>Is there an approach for achieving this?</p> <p>The code so far looks like this:</p> <pre><code>class Program { static void Main(string[] args) { A a = new A(); a.Go(1); } } public class A { internal void Go(int x) { B b = new B(); b.Go(4); } } public class B { internal void Go(int y) { Console.WriteLine(GetStackTrace()); } public static string GetStackTrace() { StringBuilder sb = new StringBuilder(); StackTrace st = new StackTrace(true); StackFrame[] frames = st.GetFrames(); foreach (StackFrame frame in frames) { MethodBase method = frame.GetMethod(); sb.AppendFormat("{0} - {1}",method.DeclaringType, method.Name); ParameterInfo[] paramaters = method.GetParameters(); foreach (ParameterInfo paramater in paramaters) { sb.AppendFormat("{0}: {1}", paramater.Name, paramater.ToString()); } sb.AppendLine(); } return sb.ToString(); } } </code></pre> <h2>The output looks like this:</h2> <pre><code>SfApp.B - GetStackTrace SfApp.B - Go y: Int32 y SfApp.A - Go x: Int32 x SfApp.Program - Main args: System.String[] args </code></pre> <h2>I'd like it to look more like this:</h2> <pre><code>SfApp.B - GetStackTrace SfApp.B - Go y: 4 SfApp.A - Go x: 1 SfApp.Program - Main </code></pre> <hr/> <p>Just for a bit of context, my plan was to try and use this when I throw my own exceptions. I'll look at your suggestions in more detail and see if I can see it fitting.</p>
[ { "answer_id": 75297, "author": "Lars Truijens", "author_id": 1242, "author_profile": "https://Stackoverflow.com/users/1242", "pm_score": 4, "selected": true, "text": "<p>It seems it can't be done that way. It will only provide meta information about the method and its parameters. Not the actual value at the time of the callstack. </p>\n\n<p>Some suggest deriving your classes from <a href=\"http://msdn.microsoft.com/en-us/library/system.contextboundobject.aspx\" rel=\"noreferrer\">ContextBoundObject</a> and use <a href=\"http://msdn.microsoft.com/en-us/library/system.runtime.remoting.messaging.imessagesink.aspx\" rel=\"noreferrer\">IMessageSink</a> to be notified off all method calls and the values of the parameters. This is normally used for <a href=\"http://en.wikipedia.org/wiki/.NET_Remoting\" rel=\"noreferrer\">.NET Remoting</a>.</p>\n\n<p>Another suggestion might be to write a debugger. This is how the IDE gets its information. Microsoft has <a href=\"http://blogs.msdn.com/jmstall/archive/2004/09/30/236281.aspx\" rel=\"noreferrer\">Mdbg</a> of which you can get the source code. Or write a <a href=\"http://msdn.microsoft.com/en-us/magazine/cc300553.aspx\" rel=\"noreferrer\">CLR profiler</a>.</p>\n" }, { "answer_id": 70553027, "author": "Marco Luzzara", "author_id": 5587393, "author_profile": "https://Stackoverflow.com/users/5587393", "pm_score": 1, "selected": false, "text": "<p>I am quite sure this is possible somehow, but I am not competent enough to give you the answer you wish. I am suggesting a different approach, less flexible but still useful if you have a stack trace in advance and you would like to see the arguments passed to each frame.</p>\n<p>Typically you would scatter log messages at the start of each method present in your stack trace, but that is pretty cumbersome and not always possible: what if you call methods defined in an external library?</p>\n<hr />\n<p>While I was searching for an inspiration on how to tackle this problem, I found a library called <a href=\"https://github.com/pardeike/Harmony\" rel=\"nofollow noreferrer\">Harmony</a>, that allows you to patch methods at runtime. Basically a method can be decorated with a prefix, a postfix and/or a finalizer. It is all very well explained in the documentation, but the idea you could use in order to provide details about methods in a stack trace is to create a <a href=\"https://harmony.pardeike.net/articles/patching-prefix.html\" rel=\"nofollow noreferrer\">prefix</a> that prints the parameters of each frame.</p>\n<p>Unfortunately, with Harmony only, I do not think it is possible to do this for the methods in the current <code>StackTrace</code>, as you would like to do, even using a postfix/finalizer. Nonetheless it can be done before the target method is called.</p>\n<hr />\n<p>I have created a very simple library called <code>DebugLogger</code> that internally uses Harmony and that simplifies the procedure. <a href=\"https://github.com/marco-luzzara/DebugLogger\" rel=\"nofollow noreferrer\">Here</a> is the repository, but you can also find it on Nuget:</p>\n<pre><code>dotnet add package DebugLogger --version 1.0.0\n</code></pre>\n<p>It still has many limitations, in part because of Harmony, there are just a bunch of tests and is not ready to be considered a library, but it is a good starting point in my opinion. I have prepared a <a href=\"https://dotnetfiddle.net/79dHkJ\" rel=\"nofollow noreferrer\">Fiddle</a> showing the initialization of <code>DebugLogger</code> and a couple of dummy classes to make the demo &quot;meaningful&quot;.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/75076", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2422/" ]
I would like to be able to obtain all the parameter values from the stack frame in .NET. A bit like how you're able to see the values in the call stack when in the Visual Studio debugger. My approach has concentrated on using the [StackFrame class](http://msdn.microsoft.com/en-us/library/system.diagnostics.stackframe%28v=vs.71%29.aspx) and then to reflect over a [ParameterInfo](http://msdn.microsoft.com/en-us/library/system.reflection.parameterinfo%28v=vs.71%29.aspx) array. I've had success with reflection and properties, but this is proving a bit trickier. Is there an approach for achieving this? The code so far looks like this: ``` class Program { static void Main(string[] args) { A a = new A(); a.Go(1); } } public class A { internal void Go(int x) { B b = new B(); b.Go(4); } } public class B { internal void Go(int y) { Console.WriteLine(GetStackTrace()); } public static string GetStackTrace() { StringBuilder sb = new StringBuilder(); StackTrace st = new StackTrace(true); StackFrame[] frames = st.GetFrames(); foreach (StackFrame frame in frames) { MethodBase method = frame.GetMethod(); sb.AppendFormat("{0} - {1}",method.DeclaringType, method.Name); ParameterInfo[] paramaters = method.GetParameters(); foreach (ParameterInfo paramater in paramaters) { sb.AppendFormat("{0}: {1}", paramater.Name, paramater.ToString()); } sb.AppendLine(); } return sb.ToString(); } } ``` The output looks like this: --------------------------- ``` SfApp.B - GetStackTrace SfApp.B - Go y: Int32 y SfApp.A - Go x: Int32 x SfApp.Program - Main args: System.String[] args ``` I'd like it to look more like this: ----------------------------------- ``` SfApp.B - GetStackTrace SfApp.B - Go y: 4 SfApp.A - Go x: 1 SfApp.Program - Main ``` --- Just for a bit of context, my plan was to try and use this when I throw my own exceptions. I'll look at your suggestions in more detail and see if I can see it fitting.
It seems it can't be done that way. It will only provide meta information about the method and its parameters. Not the actual value at the time of the callstack. Some suggest deriving your classes from [ContextBoundObject](http://msdn.microsoft.com/en-us/library/system.contextboundobject.aspx) and use [IMessageSink](http://msdn.microsoft.com/en-us/library/system.runtime.remoting.messaging.imessagesink.aspx) to be notified off all method calls and the values of the parameters. This is normally used for [.NET Remoting](http://en.wikipedia.org/wiki/.NET_Remoting). Another suggestion might be to write a debugger. This is how the IDE gets its information. Microsoft has [Mdbg](http://blogs.msdn.com/jmstall/archive/2004/09/30/236281.aspx) of which you can get the source code. Or write a [CLR profiler](http://msdn.microsoft.com/en-us/magazine/cc300553.aspx).
75,123
<p>I have a DataSet which I get a DataTable from that I am being passed back from a function call. It has 15-20 columns, however I only want 10 columns of the data.</p> <p>Is there a way to remove those columns that I don't want, copy the DataTable to another that has only the columns defined that I want or is it just better to iterate the collection and just use the columns I need.</p> <p>I need to write the values out to a fixed length data file.</p>
[ { "answer_id": 75178, "author": "Tom Ritter", "author_id": 8435, "author_profile": "https://Stackoverflow.com/users/8435", "pm_score": 9, "selected": true, "text": "<p>Aside from limiting the columns selected to reduce bandwidth and memory:</p>\n\n<pre><code>DataTable t;\nt.Columns.Remove(\"columnName\");\nt.Columns.RemoveAt(columnIndex);\n</code></pre>\n" }, { "answer_id": 75558, "author": "Timothy Carter", "author_id": 4660, "author_profile": "https://Stackoverflow.com/users/4660", "pm_score": 5, "selected": false, "text": "<p>To remove all columns after the one you want, below code should work. It will remove at index 10 (remember Columns are 0 based), until the Column count is 10 or less.</p>\n\n<pre><code>DataTable dt;\nint desiredSize = 10;\n\nwhile (dt.Columns.Count &gt; desiredSize)\n{\n dt.Columns.RemoveAt(desiredSize);\n}\n</code></pre>\n" }, { "answer_id": 58115639, "author": "SU7", "author_id": 8043435, "author_profile": "https://Stackoverflow.com/users/8043435", "pm_score": 3, "selected": false, "text": "<p>The question has already been marked as answered, But I guess the question states that the person wants to remove multiple columns from a <code>DataTable</code>. </p>\n\n<p>So for that, here is what I did, when I came across the same problem.</p>\n\n<pre><code>string[] ColumnsToBeDeleted = { \"col1\", \"col2\", \"col3\", \"col4\" };\n\nforeach (string ColName in ColumnsToBeDeleted)\n{\n if (dt.Columns.Contains(ColName))\n dt.Columns.Remove(ColName);\n}\n</code></pre>\n" }, { "answer_id": 69431049, "author": "Hannington Mambo", "author_id": 1909689, "author_profile": "https://Stackoverflow.com/users/1909689", "pm_score": 0, "selected": false, "text": "<p>How about you just select the columns you want like this:</p>\n<pre><code>Dim Subjects As String = &quot;Math, English&quot;\nDim SubjectData As DataTable = Table.AsDataView.ToTable(True, Subjects.Split(&quot;,&quot;))\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/75123", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3208/" ]
I have a DataSet which I get a DataTable from that I am being passed back from a function call. It has 15-20 columns, however I only want 10 columns of the data. Is there a way to remove those columns that I don't want, copy the DataTable to another that has only the columns defined that I want or is it just better to iterate the collection and just use the columns I need. I need to write the values out to a fixed length data file.
Aside from limiting the columns selected to reduce bandwidth and memory: ``` DataTable t; t.Columns.Remove("columnName"); t.Columns.RemoveAt(columnIndex); ```
75,127
<p>I have a bulletin board (punBB based) that I was running out of the root directory for a couple of years. I foolishly decided to do a little gardening and in the process moved the punbb code into it's own subdirectory. The code works great; as long as you point the browser at the new subdirectory. The issue is that the users expect to see it at the root...</p> <p>I tried an index file in the root that had the following:</p> <pre><code>&lt;?php chdir('punbb'); include('index.php'); </code></pre> <p>But that didn't seem to do the trick. So, I tried using the "damn cool voodoo" of mod_rewrite in .htaccess but I can't seem to figure out the right combination of rules to make it work.</p> <p>Here is what I would like to make happen:</p> <p>User enters: </p> <pre><code> http://guardthe.net </code></pre> <p>Browser displays: </p> <pre><code> http://guardthe.net/punbb/ </code></pre> <p>or</p> <pre><code> http://punbb.guardthe.net/ </code></pre> <p>Is this possible, or should I just move the code base back into the root?</p>
[ { "answer_id": 75144, "author": "user13270", "author_id": 13270, "author_profile": "https://Stackoverflow.com/users/13270", "pm_score": 1, "selected": false, "text": "<p>a PHP file with a 301 HTTP permenant redirect.</p>\n\n<p>Put the following into index.php in the root directory of guardthe.net</p>\n\n<pre><code>&lt;?php\nHeader( \"HTTP/1.1 301 Moved Permanently\" );\nHeader( \"Location: http://guardthe.net/punbb/\" );\n?&gt;\n</code></pre>\n\n<p>browser will re-direct with search engine friendliness.</p>\n" }, { "answer_id": 75147, "author": "Jan Krüger", "author_id": 12471, "author_profile": "https://Stackoverflow.com/users/12471", "pm_score": 0, "selected": false, "text": "<p>Your example code is missing but here's one way to do it using mod_rewrite:</p>\n\n<pre><code>RewriteEngine on\nRewriteRule ^$ http://guardthe.net/punbb/ [L,R=301]\n</code></pre>\n" }, { "answer_id": 75185, "author": "toluju", "author_id": 12457, "author_profile": "https://Stackoverflow.com/users/12457", "pm_score": 0, "selected": false, "text": "<p>You could write a small redirect script to take care of this simply and quickly.</p>\n\n<pre><code>&lt;?php \nheader( 'Location: http://guardthe.net/punbb/' ); \n?&gt;\n</code></pre>\n\n<p>Enter that as the only content in your index.php in your root directory, and any requests sent to that folder will then redirect the user to the forum.</p>\n" }, { "answer_id": 75214, "author": "Mr Shark", "author_id": 6093, "author_profile": "https://Stackoverflow.com/users/6093", "pm_score": 2, "selected": false, "text": "<p>Something like this in .htacces should do it:</p>\n\n<pre><code> RewriteEngine On\n RewriteRule ^/?$ /punbb/ [R=301,L]\n</code></pre>\n\n<p>The 301 return code is to mark the move as permanentm making it posible for the browser to update bookmarks.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/75127", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a bulletin board (punBB based) that I was running out of the root directory for a couple of years. I foolishly decided to do a little gardening and in the process moved the punbb code into it's own subdirectory. The code works great; as long as you point the browser at the new subdirectory. The issue is that the users expect to see it at the root... I tried an index file in the root that had the following: ``` <?php chdir('punbb'); include('index.php'); ``` But that didn't seem to do the trick. So, I tried using the "damn cool voodoo" of mod\_rewrite in .htaccess but I can't seem to figure out the right combination of rules to make it work. Here is what I would like to make happen: User enters: ``` http://guardthe.net ``` Browser displays: ``` http://guardthe.net/punbb/ ``` or ``` http://punbb.guardthe.net/ ``` Is this possible, or should I just move the code base back into the root?
Something like this in .htacces should do it: ``` RewriteEngine On RewriteRule ^/?$ /punbb/ [R=301,L] ``` The 301 return code is to mark the move as permanentm making it posible for the browser to update bookmarks.
75,134
<p>How do I have two effects in jQuery run in <code>sequence</code>, not simultaneously? Take this piece of code for example:</p> <pre><code>$("#show-projects").click(function() { $(".page:visible").fadeOut("normal"); $("#projects").fadeIn("normal"); }); </code></pre> <p>The <code>fadeOut</code> and the <code>fadeIn</code> run simultaneously, how do I make them run one after the other?</p>
[ { "answer_id": 75194, "author": "neuroguy123", "author_id": 12529, "author_profile": "https://Stackoverflow.com/users/12529", "pm_score": 4, "selected": false, "text": "<p>What you want is a queue.</p>\n\n<p>Check out the reference page <a href=\"http://api.jquery.com/queue/\" rel=\"nofollow noreferrer\">http://api.jquery.com/queue/</a> for some working examples.</p>\n" }, { "answer_id": 75259, "author": "Jim", "author_id": 8427, "author_profile": "https://Stackoverflow.com/users/8427", "pm_score": 6, "selected": true, "text": "<p>You can supply a callback to the effects functions that run after the effect has completed.</p>\n\n<pre><code>$(\"#show-projects\").click(function() {\n $(\".page:visible\").fadeOut(\"normal\", function() {\n $(\"#projects\").fadeIn(\"normal\");\n });\n});\n</code></pre>\n" }, { "answer_id": 23672352, "author": "niall.campbell", "author_id": 323722, "author_profile": "https://Stackoverflow.com/users/323722", "pm_score": 0, "selected": false, "text": "<p>Does there have to be a target? surely you can use a random target to queue events sequentially so long as the target is constant...below I'm using the parent of an animation target to store the queue.</p>\n\n<pre><code>//example of adding sequential effects through\n//event handlers and a jquery event trigger\njQuery( document ).unbind( \"bk_prompt_collapse.slide_up\" );\njQuery( document ).bind( \"bk_prompt_collapse.slide_up\" , function( e, j_obj ) {\n jQuery(j_obj).queue(function() {\n //running our timed effect\n jQuery(this).find('div').slideUp(400);\n //adding a fill delay to the parent\n jQuery(this).delay(400).dequeue();\n });\n}); \n//the last action removes the content from the dom\n//if its in the queue then it will fire sequentially\njQuery( document ).unbind( \"bk_prompt_collapse.last_action\" );\njQuery( document ).bind( \"bk_prompt_collapse.last_action\" , function( e, j_obj ) {\n jQuery(j_obj).queue(function() {\n //Hot dog!!\n jQuery(this).remove().dequeue();\n });\n});\njQuery(\"tr.bk_removing_cart_row\").trigger( \n \"bk_prompt_collapse\" , \n jQuery(\"tr.bk_removing_cart_row\") \n);\n</code></pre>\n\n<p>Not sure if its possible but it seems like you could bind .dequeue() to fire when another jquery event fires, instead of firing inline in my example above? effectively halting an animation queue?</p>\n" }, { "answer_id": 26987154, "author": "brilliantairic", "author_id": 586204, "author_profile": "https://Stackoverflow.com/users/586204", "pm_score": 1, "selected": false, "text": "<pre><code>$( \"#foo\" ).fadeOut( 300 ).delay( 800 ).fadeIn( 400 );\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/75134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6967/" ]
How do I have two effects in jQuery run in `sequence`, not simultaneously? Take this piece of code for example: ``` $("#show-projects").click(function() { $(".page:visible").fadeOut("normal"); $("#projects").fadeIn("normal"); }); ``` The `fadeOut` and the `fadeIn` run simultaneously, how do I make them run one after the other?
You can supply a callback to the effects functions that run after the effect has completed. ``` $("#show-projects").click(function() { $(".page:visible").fadeOut("normal", function() { $("#projects").fadeIn("normal"); }); }); ```
75,139
<p>Google custom search code is provided as a form tag. However, Asp.net only allows a single form tag on a page. What is the best way to implement their code so you can include it on an aspx page (say as part of a Masterpage or navigation element). </p>
[ { "answer_id": 75234, "author": "Chris Van Opstal", "author_id": 7264, "author_profile": "https://Stackoverflow.com/users/7264", "pm_score": 3, "selected": false, "text": "<p>You can have multiple form tags on an ASP.NET page. The limitation is on server-side (runat=\"server\") form tags. </p>\n\n<p>You can implement two form tags (or more) as long as only one has the runat=\"server\" attribute and one is not contained in the other. Example:</p>\n\n<pre><code>&lt;body&gt;\n&lt;form action=\"http://www.google.com/cse\" id=\"cse-search-box\"&gt; ... &lt;/form&gt;\n&lt;form runat=\"server\" id=\"aspNetform\"&gt; ... &lt;/form&gt;\n&lt;body&gt;\n</code></pre>\n" }, { "answer_id": 75288, "author": "Eric Longman", "author_id": 13282, "author_profile": "https://Stackoverflow.com/users/13282", "pm_score": 2, "selected": false, "text": "<p>You may be able to have multiple form tags, but note that they cannot be nested. You'll run into all kinds of weirdness in that scenario (e.g., I've seen cases where the opening tag for the nested form apparently gets ignored and then its closing tag winds up closing the \"parent\" form out). </p>\n" }, { "answer_id": 75380, "author": "Timothy Lee Russell", "author_id": 12919, "author_profile": "https://Stackoverflow.com/users/12919", "pm_score": 0, "selected": false, "text": "<p>You could use Javascript:</p>\n\n<pre><code>&lt;input name=\"Query\" type=\"text\" class=\"searchField\" id=\"Query\" value=\"Search\" size=\"15\" onfocus=\"if(this.value == 'Search') { this.value = ''; }\" onblur=\"if(this.value == '') { this.value = 'Search'; }\" onkeydown=\"var event = event || window.event; var key = event.which || event.keyCode; if(key==13) window.open('http://www.google.com/search?q=' + getElementById('Query').value ); \" /&gt;&lt;input name=\"\" type=\"button\" class=\"searchButton\" value=\"go\" onclick=\"window.open('http://www.google.com/search?q=' + getElementById('Query').value );\" /&gt;\n</code></pre>\n" }, { "answer_id": 767329, "author": "sean", "author_id": 82371, "author_profile": "https://Stackoverflow.com/users/82371", "pm_score": 1, "selected": false, "text": "<p>You'll need to remove the form tag and use javascript send the query. Have a look at \n<a href=\"http://my6solutions.com/post/2009/04/19/Fixing-Google-Custom-Search-nested-form-tags-in-asp-net-pages.aspx\" rel=\"nofollow noreferrer\">http://my6solutions.com/post/2009/04/19/Fixing-Google-Custom-Search-nested-form-tags-in-asp-net-pages.aspx</a></p>\n\n<p>I have included the before and after code as well. So you can see what I've done to integrate it with blogengine .net.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/75139", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Google custom search code is provided as a form tag. However, Asp.net only allows a single form tag on a page. What is the best way to implement their code so you can include it on an aspx page (say as part of a Masterpage or navigation element).
You can have multiple form tags on an ASP.NET page. The limitation is on server-side (runat="server") form tags. You can implement two form tags (or more) as long as only one has the runat="server" attribute and one is not contained in the other. Example: ``` <body> <form action="http://www.google.com/cse" id="cse-search-box"> ... </form> <form runat="server" id="aspNetform"> ... </form> <body> ```
75,156
<p>This is a shared hosting environment. I control the server, but not necessarily the content. I've got a client with a Perl script that seems to run out of control every now and then and suck down 50% of the processor until the process is killed.</p> <p>With ASP scripts, I'm able to restrict the amount of time the script can run, and IIS will simply shut it down after, say, 90 seconds. This doesn't work for Perl scripts, since it's running as a cgi process (and actually launches an external process to execute the script). </p> <p>Similarly, techniques that look for excess resource consumption in a worker process will likely not see this, since the resource that's being consumed (the processor) is being chewed up by a child process rather than the WP itself.</p> <p>Is there a way to make IIS abort a Perl script (or other cgi-type process) that's running too long? How??</p>
[ { "answer_id": 75875, "author": "arclight", "author_id": 13366, "author_profile": "https://Stackoverflow.com/users/13366", "pm_score": 1, "selected": false, "text": "<p>On a UNIX-style system, I would use a signal handler trapping ALRM events, then use the alarm function to start a timer before starting an action that I expected might timeout. If the action completed, I'd use alarm(0) to turn off the alarm and exit normally, otherwise the signal handler should pick it up to close everything up gracefully.</p>\n\n<p>I have not worked with perl on Windows in a while and while Windows is somewhat POSIXy, I cannot guarantee this will work; you'll have to check the perl documentation to see if or to what extent signals are supported on your platform.</p>\n\n<p>More detailed information on signal handling and this sort of self-destruct programming using alarm() can be found in the Perl Cookbook. Here's a brief example lifted from another post and modified a little:</p>\n\n<pre><code>eval {\n # Create signal handler and make it local so it falls out of scope\n # outside the eval block\n local $SIG{ALRM} = sub {\n print \"Print this if we time out, then die.\\n\";\n die \"alarm\\n\";\n };\n\n # Set the alarm, take your chance running the routine, and turn off\n # the alarm if it completes.\n alarm(90);\n routine_that_might_take_a_while();\n alarm(0);\n};\n</code></pre>\n" }, { "answer_id": 76657, "author": "piCookie", "author_id": 8763, "author_profile": "https://Stackoverflow.com/users/8763", "pm_score": 0, "selected": false, "text": "<p>Googling for \"iis cpu limit\" gives these hits: </p>\n\n<p><a href=\"http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/38fb0130-b14b-48d5-a0a2-05ca131cf4f2.mspx?mfr=true\" rel=\"nofollow noreferrer\">http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/38fb0130-b14b-48d5-a0a2-05ca131cf4f2.mspx?mfr=true</a></p>\n\n<p>\"The CPU monitoring feature monitors and automatically shuts down worker processes that consume large amounts of CPU time. CPU monitoring is enabled for individual application pools.\"</p>\n\n<p><a href=\"http://technet.microsoft.com/en-us/library/cc728189.aspx\" rel=\"nofollow noreferrer\">http://technet.microsoft.com/en-us/library/cc728189.aspx</a></p>\n\n<p>\"By using CPU monitoring, you can monitor worker processes for CPU usage and optionally shut down the worker processes that consume large amounts of CPU time. CPU monitoring is only available in worker process isolation mode.\"</p>\n" }, { "answer_id": 76723, "author": "jwmiller5", "author_id": 7824, "author_profile": "https://Stackoverflow.com/users/7824", "pm_score": 1, "selected": false, "text": "<p>The ASP script timeout applies to all scripting languages. If the script is running in an ASP page, the script timeout will close the offending page.</p>\n" }, { "answer_id": 155999, "author": "Eric Longman", "author_id": 13282, "author_profile": "https://Stackoverflow.com/users/13282", "pm_score": 1, "selected": false, "text": "<p>An update on this one...</p>\n\n<p>It turns out that this particular script apparently is a little buggy, and that the Googlebot has the uncanny ability to \"press it's buttons\" and drive it crazy. The script is an older, commercial application that does calendaring. Apparently, it displays links for \"next month\" and \"previous month\", and if you follow the \"next month\" too many times, you'll fall off a cliff. The resulting page, however, still includes a \"next month\" link. Googlebot would continuously beat the script to death and chew up the processor.</p>\n\n<p>Curiously, adding a robots.txt with Disallow: / didn't solve the problem. Either the Googlebot had already gotten ahold of the script and wouldn't let loose, or else it simply was disregarding the robots.txt.</p>\n\n<p>Anyway, Microsoft's Process Explorer (<a href=\"http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx\" rel=\"nofollow noreferrer\">http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx</a>) was a huge help, as it allowed me to see the environment for the perl.exe process in more detail, and I was able to determine from it that it was the Googlebot causing my problems.</p>\n\n<p>Once I knew that (and determined that robots.txt wouldn't solve the problem), I was able to use IIS directly to block all traffic to this site from *.googlebot.com, which worked well in this case, since we don't care if Google indexes this content.</p>\n\n<p>Thanks much for the other ideas that everyone posted!</p>\n\n<p>Eric Longman</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/75156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13282/" ]
This is a shared hosting environment. I control the server, but not necessarily the content. I've got a client with a Perl script that seems to run out of control every now and then and suck down 50% of the processor until the process is killed. With ASP scripts, I'm able to restrict the amount of time the script can run, and IIS will simply shut it down after, say, 90 seconds. This doesn't work for Perl scripts, since it's running as a cgi process (and actually launches an external process to execute the script). Similarly, techniques that look for excess resource consumption in a worker process will likely not see this, since the resource that's being consumed (the processor) is being chewed up by a child process rather than the WP itself. Is there a way to make IIS abort a Perl script (or other cgi-type process) that's running too long? How??
On a UNIX-style system, I would use a signal handler trapping ALRM events, then use the alarm function to start a timer before starting an action that I expected might timeout. If the action completed, I'd use alarm(0) to turn off the alarm and exit normally, otherwise the signal handler should pick it up to close everything up gracefully. I have not worked with perl on Windows in a while and while Windows is somewhat POSIXy, I cannot guarantee this will work; you'll have to check the perl documentation to see if or to what extent signals are supported on your platform. More detailed information on signal handling and this sort of self-destruct programming using alarm() can be found in the Perl Cookbook. Here's a brief example lifted from another post and modified a little: ``` eval { # Create signal handler and make it local so it falls out of scope # outside the eval block local $SIG{ALRM} = sub { print "Print this if we time out, then die.\n"; die "alarm\n"; }; # Set the alarm, take your chance running the routine, and turn off # the alarm if it completes. alarm(90); routine_that_might_take_a_while(); alarm(0); }; ```
75,175
<p>Is it possible to create an instance of a generic type in Java? I'm thinking based on what I've seen that the answer is <code>no</code> (<em>due to type erasure</em>), but I'd be interested if anyone can see something I'm missing:</p> <pre><code>class SomeContainer&lt;E&gt; { E createContents() { return what??? } } </code></pre> <p>EDIT: It turns out that <a href="http://www.artima.com/weblogs/viewpost.jsp?thread=208860" rel="noreferrer">Super Type Tokens</a> could be used to resolve my issue, but it requires a lot of reflection-based code, as some of the answers below have indicated.</p> <p>I'll leave this open for a little while to see if anyone comes up with anything dramatically different than Ian Robertson's <a href="http://www.artima.com/weblogs/viewpost.jsp?thread=208860" rel="noreferrer">Artima Article</a>.</p>
[ { "answer_id": 75201, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 0, "selected": false, "text": "<p>As you said, you can't really do it because of type erasure. You can sort of do it using reflection, but it requires a lot of code and lot of error handling.</p>\n" }, { "answer_id": 75254, "author": "Justin Rudd", "author_id": 12968, "author_profile": "https://Stackoverflow.com/users/12968", "pm_score": 9, "selected": false, "text": "<p>You are correct. You can't do <code>new E()</code>. But you can change it to</p>\n\n<pre><code>private static class SomeContainer&lt;E&gt; {\n E createContents(Class&lt;E&gt; clazz) {\n return clazz.newInstance();\n }\n}\n</code></pre>\n\n<p>It's a pain. But it works. Wrapping it in the factory pattern makes it a little more tolerable.</p>\n" }, { "answer_id": 75313, "author": "Mike Stone", "author_id": 122, "author_profile": "https://Stackoverflow.com/users/122", "pm_score": 3, "selected": false, "text": "<p>Here is an option I came up with, it may help:</p>\n\n<pre><code>public static class Container&lt;E&gt; {\n private Class&lt;E&gt; clazz;\n\n public Container(Class&lt;E&gt; clazz) {\n this.clazz = clazz;\n }\n\n public E createContents() throws Exception {\n return clazz.newInstance();\n }\n}\n</code></pre>\n\n<p>EDIT: Alternatively you can use this constructor (but it requires an instance of E):</p>\n\n<pre><code>@SuppressWarnings(\"unchecked\")\npublic Container(E instance) {\n this.clazz = (Class&lt;E&gt;) instance.getClass();\n}\n</code></pre>\n" }, { "answer_id": 75345, "author": "noah", "author_id": 12034, "author_profile": "https://Stackoverflow.com/users/12034", "pm_score": 7, "selected": false, "text": "<p>I don't know if this helps, but when you subclass (including anonymously) a generic type, the type information is available via reflection. e.g.,</p>\n<pre><code>public abstract class Foo&lt;E&gt; {\n\n public E instance; \n\n public Foo() throws Exception {\n instance = ((Class)((ParameterizedType)this.getClass().\n getGenericSuperclass()).getActualTypeArguments()[0]).newInstance();\n ...\n }\n\n}\n</code></pre>\n<p>So, when you subclass Foo, you get an instance of Bar e.g.,</p>\n<pre><code>// notice that this in anonymous subclass of Foo\nassert( new Foo&lt;Bar&gt;() {}.instance instanceof Bar );\n</code></pre>\n<p>But it's a lot of work, and only works for subclasses. Can be handy though.</p>\n" }, { "answer_id": 75528, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 6, "selected": false, "text": "<p>You'll need some kind of abstract factory of one sort or another to pass the buck to:</p>\n\n<pre><code>interface Factory&lt;E&gt; {\n E create();\n}\n\nclass SomeContainer&lt;E&gt; {\n private final Factory&lt;E&gt; factory;\n SomeContainer(Factory&lt;E&gt; factory) {\n this.factory = factory;\n }\n E createContents() {\n return factory.create();\n }\n}\n</code></pre>\n" }, { "answer_id": 75595, "author": "Pavel Feldman", "author_id": 5507, "author_profile": "https://Stackoverflow.com/users/5507", "pm_score": 0, "selected": false, "text": "<p>If you mean \n<code>new E()</code> \nthen it is impossible. And I would add that it is not always correct - how do you know if E has public no-args constructor?\nBut you can always delegate creation to some other class that knows how to create an instance - it can be <code>Class&lt;E&gt;</code> or your custom code like this</p>\n\n<pre><code>interface Factory&lt;E&gt;{\n E create();\n} \n\nclass IntegerFactory implements Factory&lt;Integer&gt;{ \n private static int i = 0; \n Integer create() { \n return i++; \n }\n}\n</code></pre>\n" }, { "answer_id": 87187, "author": "jb.", "author_id": 7918, "author_profile": "https://Stackoverflow.com/users/7918", "pm_score": 3, "selected": false, "text": "<p>If you want not to type class name twice during instantiation like in:</p>\n\n<pre><code>new SomeContainer&lt;SomeType&gt;(SomeType.class);\n</code></pre>\n\n<p>You can use factory method:</p>\n\n<pre><code>&lt;E&gt; SomeContainer&lt;E&gt; createContainer(Class&lt;E&gt; class); \n</code></pre>\n\n<p>Like in:</p>\n\n<pre><code>public class Container&lt;E&gt; {\n\n public static &lt;E&gt; Container&lt;E&gt; create(Class&lt;E&gt; c) {\n return new Container&lt;E&gt;(c);\n }\n\n Class&lt;E&gt; c;\n\n public Container(Class&lt;E&gt; c) {\n super();\n this.c = c;\n }\n\n public E createInstance()\n throws InstantiationException,\n IllegalAccessException {\n return c.newInstance();\n }\n\n}\n</code></pre>\n" }, { "answer_id": 376216, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>You can use:</p>\n\n<pre><code>Class.forName(String).getConstructor(arguments types).newInstance(arguments)\n</code></pre>\n\n<p>But you need to supply the exact class name, including packages, eg. <code>java.io.FileInputStream</code>. I used this to create a math expressions parser.</p>\n" }, { "answer_id": 3635805, "author": "Lars Bohl", "author_id": 438960, "author_profile": "https://Stackoverflow.com/users/438960", "pm_score": 5, "selected": false, "text": "<pre><code>package org.foo.com;\n\nimport java.lang.reflect.ParameterizedType;\nimport java.lang.reflect.Type;\n\n/**\n * Basically the same answer as noah's.\n */\npublic class Home&lt;E&gt;\n{\n\n @SuppressWarnings (\"unchecked\")\n public Class&lt;E&gt; getTypeParameterClass()\n {\n Type type = getClass().getGenericSuperclass();\n ParameterizedType paramType = (ParameterizedType) type;\n return (Class&lt;E&gt;) paramType.getActualTypeArguments()[0];\n }\n\n private static class StringHome extends Home&lt;String&gt;\n {\n }\n\n private static class StringBuilderHome extends Home&lt;StringBuilder&gt;\n {\n }\n\n private static class StringBufferHome extends Home&lt;StringBuffer&gt;\n {\n } \n\n /**\n * This prints \"String\", \"StringBuilder\" and \"StringBuffer\"\n */\n public static void main(String[] args) throws InstantiationException, IllegalAccessException\n {\n Object object0 = new StringHome().getTypeParameterClass().newInstance();\n Object object1 = new StringBuilderHome().getTypeParameterClass().newInstance();\n Object object2 = new StringBufferHome().getTypeParameterClass().newInstance();\n System.out.println(object0.getClass().getSimpleName());\n System.out.println(object1.getClass().getSimpleName());\n System.out.println(object2.getClass().getSimpleName());\n }\n\n}\n</code></pre>\n" }, { "answer_id": 5389482, "author": "Rachid", "author_id": 670960, "author_profile": "https://Stackoverflow.com/users/670960", "pm_score": 0, "selected": false, "text": "<pre><code>return (E)((Class)((ParameterizedType)this.getClass().getGenericSuperclass()).getActualTypeArguments()[0]).newInstance();\n</code></pre>\n" }, { "answer_id": 10042797, "author": "Bogdan Veliscu", "author_id": 818753, "author_profile": "https://Stackoverflow.com/users/818753", "pm_score": 0, "selected": false, "text": "<p>You can achieve this with the following snippet:</p>\n\n<pre><code>import java.lang.reflect.ParameterizedType;\n\npublic class SomeContainer&lt;E&gt; {\n E createContents() throws InstantiationException, IllegalAccessException {\n ParameterizedType genericSuperclass = (ParameterizedType)\n getClass().getGenericSuperclass();\n @SuppressWarnings(\"unchecked\")\n Class&lt;E&gt; clazz = (Class&lt;E&gt;)\n genericSuperclass.getActualTypeArguments()[0];\n return clazz.newInstance();\n }\n public static void main( String[] args ) throws Throwable {\n SomeContainer&lt; Long &gt; scl = new SomeContainer&lt;&gt;();\n Long l = scl.createContents();\n System.out.println( l );\n }\n}\n</code></pre>\n" }, { "answer_id": 12407106, "author": "Sergiy Sokolenko", "author_id": 131337, "author_profile": "https://Stackoverflow.com/users/131337", "pm_score": 4, "selected": false, "text": "<p>From <a href=\"http://docs.oracle.com/javase/tutorial/java/generics/restrictions.html\" rel=\"nofollow noreferrer\">Java Tutorial - Restrictions on Generics</a>:</p>\n<p><strong><a href=\"http://docs.oracle.com/javase/tutorial/java/generics/restrictions.html#createObjects\" rel=\"nofollow noreferrer\">Cannot Create Instances of Type Parameters</a></strong></p>\n<p>You cannot create an instance of a type parameter. For example, the following code causes a compile-time error:</p>\n<pre><code>public static &lt;E&gt; void append(List&lt;E&gt; list) {\n E elem = new E(); // compile-time error\n list.add(elem);\n}\n</code></pre>\n<p>As a workaround, you can create an object of a type parameter through reflection:</p>\n<pre><code>public static &lt;E&gt; void append(List&lt;E&gt; list, Class&lt;E&gt; cls) throws Exception {\n E elem = cls.getDeclaredConstructor().newInstance(); // OK\n list.add(elem);\n}\n</code></pre>\n<p>You can invoke the append method as follows:</p>\n<pre><code>List&lt;String&gt; ls = new ArrayList&lt;&gt;();\nappend(ls, String.class);\n</code></pre>\n" }, { "answer_id": 14146479, "author": "Luigi R. Viggiano", "author_id": 258289, "author_profile": "https://Stackoverflow.com/users/258289", "pm_score": 2, "selected": false, "text": "<p>I thought I could do that, but quite disappointed: it doesn't work, but I think it still worths sharing. </p>\n\n<p>Maybe someone can correct:</p>\n\n<pre><code>import java.lang.reflect.InvocationHandler;\nimport java.lang.reflect.Method;\nimport java.lang.reflect.Proxy;\n\ninterface SomeContainer&lt;E&gt; {\n E createContents();\n}\n\npublic class Main {\n\n @SuppressWarnings(\"unchecked\")\n public static &lt;E&gt; SomeContainer&lt;E&gt; createSomeContainer() {\n return (SomeContainer&lt;E&gt;) Proxy.newProxyInstance(Main.class.getClassLoader(),\n new Class[]{ SomeContainer.class }, new InvocationHandler() {\n @Override\n public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {\n Class&lt;?&gt; returnType = method.getReturnType();\n return returnType.newInstance();\n }\n });\n }\n\n public static void main(String[] args) {\n SomeContainer&lt;String&gt; container = createSomeContainer();\n\n [*] System.out.println(\"String created: [\" +container.createContents()+\"]\");\n\n }\n}\n</code></pre>\n\n<p>It produces:</p>\n\n<pre><code>Exception in thread \"main\" java.lang.ClassCastException: java.lang.Object cannot be cast to java.lang.String\n at Main.main(Main.java:26)\n at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)\n at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\n at java.lang.reflect.Method.invoke(Method.java:601)\n at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)\n</code></pre>\n\n<p>Line 26 is the one with the <code>[*]</code>.</p>\n\n<p>The only viable solution is the one by @JustinRudd</p>\n" }, { "answer_id": 14191442, "author": "R2D2M2", "author_id": 1949703, "author_profile": "https://Stackoverflow.com/users/1949703", "pm_score": 5, "selected": false, "text": "<p>If you need a new instance of a type argument inside a generic class then make your constructors demand its class...</p>\n\n<pre><code>public final class Foo&lt;T&gt; {\n\n private Class&lt;T&gt; typeArgumentClass;\n\n public Foo(Class&lt;T&gt; typeArgumentClass) {\n\n this.typeArgumentClass = typeArgumentClass;\n }\n\n public void doSomethingThatRequiresNewT() throws Exception {\n\n T myNewT = typeArgumentClass.newInstance();\n ...\n }\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>Foo&lt;Bar&gt; barFoo = new Foo&lt;Bar&gt;(Bar.class);\nFoo&lt;Etc&gt; etcFoo = new Foo&lt;Etc&gt;(Etc.class);\n</code></pre>\n\n<p>Pros:</p>\n\n<ul>\n<li>Much simpler (and less problematic) than Robertson's Super Type Token (STT) approach.</li>\n<li>Much more efficient than the STT approach (which will eat your cellphone for breakfast).</li>\n</ul>\n\n<p>Cons:</p>\n\n<ul>\n<li>Can't pass Class to a default constructor (which is why Foo is final). If you really do need a default constructor you can always add a setter method but then you must remember to give her a call later.</li>\n<li>Robertson's objection... More Bars than a black sheep (although specifying the type argument class one more time won't exactly kill you). And contrary to Robertson's claims this does not violate the DRY principal anyway because the compiler will ensure type correctness.</li>\n<li>Not entirely <code>Foo&lt;L&gt;</code>proof. For starters... <code>newInstance()</code> will throw a wobbler if the type argument class does not have a default constructor. This does apply to all known solutions though anyway.</li>\n<li>Lacks the total encapsulation of the STT approach. Not a big deal though (considering the outrageous performance overhead of STT).</li>\n</ul>\n" }, { "answer_id": 21553287, "author": "Roald", "author_id": 2344378, "author_profile": "https://Stackoverflow.com/users/2344378", "pm_score": -1, "selected": false, "text": "<p>You can with a classloader and the class name, eventually some parameters.</p>\n\n<pre><code>final ClassLoader classLoader = ...\nfinal Class&lt;?&gt; aClass = classLoader.loadClass(\"java.lang.Integer\");\nfinal Constructor&lt;?&gt; constructor = aClass.getConstructor(int.class);\nfinal Object o = constructor.newInstance(123);\nSystem.out.println(\"o = \" + o);\n</code></pre>\n" }, { "answer_id": 21716855, "author": "Ira", "author_id": 3299647, "author_profile": "https://Stackoverflow.com/users/3299647", "pm_score": 3, "selected": false, "text": "<p>When you are working with E at compile time you don't really care the actual generic type &quot;E&quot; (either you use reflection or work with base class of generic type) so let the subclass provide instance of E.</p>\n<pre><code>abstract class SomeContainer&lt;E&gt;\n{\n abstract protected E createContents();\n public void doWork(){\n E obj = createContents();\n // Do the work with E \n }\n}\n\nclass BlackContainer extends SomeContainer&lt;Black&gt;{\n protected Black createContents() {\n return new Black();\n }\n}\n</code></pre>\n" }, { "answer_id": 25195050, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "<p>You can do this now and it doesn't require a bunch of reflection code.</p>\n\n<pre><code>import com.google.common.reflect.TypeToken;\n\npublic class Q26289147\n{\n public static void main(final String[] args) throws IllegalAccessException, InstantiationException\n {\n final StrawManParameterizedClass&lt;String&gt; smpc = new StrawManParameterizedClass&lt;String&gt;() {};\n final String string = (String) smpc.type.getRawType().newInstance();\n System.out.format(\"string = \\\"%s\\\"\",string);\n }\n\n static abstract class StrawManParameterizedClass&lt;T&gt;\n {\n final TypeToken&lt;T&gt; type = new TypeToken&lt;T&gt;(getClass()) {};\n }\n}\n</code></pre>\n\n<p>Of course if you need to call the constructor that will require some reflection, but that is very well documented, this trick isn't!</p>\n\n<p>Here is the <a href=\"https://google.github.io/guava/releases/19.0/api/docs/com/google/common/reflect/TypeToken.html\" rel=\"noreferrer\">JavaDoc for TypeToken</a>.</p>\n" }, { "answer_id": 26796874, "author": "Amio.io", "author_id": 1075289, "author_profile": "https://Stackoverflow.com/users/1075289", "pm_score": 2, "selected": false, "text": "<p>An imporovement of @Noah's answer. </p>\n\n<p><strong>Reason for Change</strong></p>\n\n<p><strong>a]</strong> Is safer if more then 1 generic type is used in case you changed the order.</p>\n\n<p><strong>b]</strong> A class generic type signature changes from time to time so that you will not be surprised by unexplained exceptions in the runtime.</p>\n\n<p><strong>Robust Code</strong></p>\n\n<pre><code>public abstract class Clazz&lt;P extends Params, M extends Model&gt; {\n\n protected M model;\n\n protected void createModel() {\n Type[] typeArguments = ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments();\n for (Type type : typeArguments) {\n if ((type instanceof Class) &amp;&amp; (Model.class.isAssignableFrom((Class) type))) {\n try {\n model = ((Class&lt;M&gt;) type).newInstance();\n } catch (InstantiationException | IllegalAccessException e) {\n throw new RuntimeException(e);\n }\n }\n }\n}\n</code></pre>\n\n<p>Or use the one liner</p>\n\n<p><strong>One Line Code</strong></p>\n\n<pre><code>model = ((Class&lt;M&gt;) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[1]).newInstance();\n</code></pre>\n" }, { "answer_id": 29680588, "author": "Ingo", "author_id": 86604, "author_profile": "https://Stackoverflow.com/users/86604", "pm_score": 4, "selected": false, "text": "<p>Think about a more functional approach: instead of creating some E out of nothing (which is clearly a code smell), pass a function that knows how to create one, i.e.</p>\n\n<pre><code>E createContents(Callable&lt;E&gt; makeone) {\n return makeone.call(); // most simple case clearly not that useful\n}\n</code></pre>\n" }, { "answer_id": 35315432, "author": "Neepsnikeep", "author_id": 5507619, "author_profile": "https://Stackoverflow.com/users/5507619", "pm_score": 3, "selected": false, "text": "<p>Java unfortunatly does not allow what you want to do. See the <a href=\"http://docs.oracle.com/javase/tutorial/java/generics/restrictions.html#createObjects\" rel=\"nofollow noreferrer\">official workaround</a> :</p>\n\n<blockquote>\n <p>You cannot create an instance of a type parameter. For example, the following code causes a compile-time error:</p>\n</blockquote>\n\n<pre><code>public static &lt;E&gt; void append(List&lt;E&gt; list) {\n E elem = new E(); // compile-time error\n list.add(elem);\n}\n</code></pre>\n\n<blockquote>\n <p>As a workaround, you can create an object of a type parameter through reflection:</p>\n</blockquote>\n\n<pre><code>public static &lt;E&gt; void append(List&lt;E&gt; list, Class&lt;E&gt; cls) throws Exception {\n E elem = cls.newInstance(); // OK\n list.add(elem);\n}\n</code></pre>\n\n<blockquote>\n <p>You can invoke the append method as follows:</p>\n</blockquote>\n\n<pre><code>List&lt;String&gt; ls = new ArrayList&lt;&gt;();\nappend(ls, String.class);\n</code></pre>\n" }, { "answer_id": 36315051, "author": "Daniel Pryden", "author_id": 128397, "author_profile": "https://Stackoverflow.com/users/128397", "pm_score": 7, "selected": false, "text": "<p>In Java 8 you can use the <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/function/Supplier.html\" rel=\"noreferrer\"><code>Supplier</code></a> functional interface to achieve this pretty easily:</p>\n\n<pre><code>class SomeContainer&lt;E&gt; {\n private Supplier&lt;E&gt; supplier;\n\n SomeContainer(Supplier&lt;E&gt; supplier) {\n this.supplier = supplier;\n }\n\n E createContents() {\n return supplier.get();\n }\n}\n</code></pre>\n\n<p>You would construct this class like this:</p>\n\n<pre><code>SomeContainer&lt;String&gt; stringContainer = new SomeContainer&lt;&gt;(String::new);\n</code></pre>\n\n<p>The syntax <code>String::new</code> on that line is a <a href=\"https://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html\" rel=\"noreferrer\">constructor reference</a>.</p>\n\n<p>If your constructor takes arguments you can use a lambda expression instead:</p>\n\n<pre><code>SomeContainer&lt;BigInteger&gt; bigIntegerContainer\n = new SomeContainer&lt;&gt;(() -&gt; new BigInteger(1));\n</code></pre>\n" }, { "answer_id": 53955316, "author": "Alexandr", "author_id": 511804, "author_profile": "https://Stackoverflow.com/users/511804", "pm_score": 0, "selected": false, "text": "<p>Here is an improved solution, based on <code>ParameterizedType.getActualTypeArguments</code>, already mentioned by @noah, @Lars Bohl, and some others. </p>\n\n<p>First small improvement in the implementation. Factory should not return instance, but a type. As soon as you return instance using <code>Class.newInstance()</code> you reduce a scope of usage. Because only no-arguments constructors can be invoke like this. A better way is to return a type, and allow a client to choose, which constructor he wants to invoke:</p>\n\n<pre><code>public class TypeReference&lt;T&gt; {\n public Class&lt;T&gt; type(){\n try {\n ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass();\n if (pt.getActualTypeArguments() == null || pt.getActualTypeArguments().length == 0){\n throw new IllegalStateException(\"Could not define type\");\n }\n if (pt.getActualTypeArguments().length != 1){\n throw new IllegalStateException(\"More than one type has been found\");\n }\n Type type = pt.getActualTypeArguments()[0];\n String typeAsString = type.getTypeName();\n return (Class&lt;T&gt;) Class.forName(typeAsString);\n\n } catch (Exception e){\n throw new IllegalStateException(\"Could not identify type\", e);\n }\n\n }\n}\n</code></pre>\n\n<p>Here is a usage examples. @Lars Bohl has shown only a signe way to get reified geneneric via extension. @noah only via creating an instance with <code>{}</code>. Here are tests to demonstrate both cases:</p>\n\n<pre><code>import java.lang.reflect.Constructor;\n\npublic class TypeReferenceTest {\n\n private static final String NAME = \"Peter\";\n\n private static class Person{\n final String name;\n\n Person(String name) {\n this.name = name;\n }\n }\n\n @Test\n public void erased() {\n TypeReference&lt;Person&gt; p = new TypeReference&lt;&gt;();\n Assert.assertNotNull(p);\n try {\n p.type();\n Assert.fail();\n } catch (Exception e){\n Assert.assertEquals(\"Could not identify type\", e.getMessage());\n }\n }\n\n @Test\n public void reified() throws Exception {\n TypeReference&lt;Person&gt; p = new TypeReference&lt;Person&gt;(){};\n Assert.assertNotNull(p);\n Assert.assertEquals(Person.class.getName(), p.type().getName());\n Constructor ctor = p.type().getDeclaredConstructor(NAME.getClass());\n Assert.assertNotNull(ctor);\n Person person = (Person) ctor.newInstance(NAME);\n Assert.assertEquals(NAME, person.name);\n }\n\n static class TypeReferencePerson extends TypeReference&lt;Person&gt;{}\n\n @Test\n public void reifiedExtenension() throws Exception {\n TypeReference&lt;Person&gt; p = new TypeReferencePerson();\n Assert.assertNotNull(p);\n Assert.assertEquals(Person.class.getName(), p.type().getName());\n Constructor ctor = p.type().getDeclaredConstructor(NAME.getClass());\n Assert.assertNotNull(ctor);\n Person person = (Person) ctor.newInstance(NAME);\n Assert.assertEquals(NAME, person.name);\n }\n}\n</code></pre>\n\n<p><strong>Note:</strong> you can force the clients of <code>TypeReference</code> always use <code>{}</code> when instance is created by making this class abstract: <code>public abstract class TypeReference&lt;T&gt;</code>. I've not done it, only to show erased test case. </p>\n" }, { "answer_id": 54213575, "author": "Se Song", "author_id": 3458608, "author_profile": "https://Stackoverflow.com/users/3458608", "pm_score": 3, "selected": false, "text": "<p>Hope this's not too late to help!!!</p>\n<p>Java is type-safe, meaning that only Objects are able to create instances.</p>\n<p>In my case I cannot pass parameters to the <code>createContents</code> method. My solution is using extends unlike the answer below.</p>\n<pre><code>private static class SomeContainer&lt;E extends Object&gt; {\n E e;\n E createContents() throws Exception{\n return (E) e.getClass().getDeclaredConstructor().newInstance();\n }\n}\n</code></pre>\n<p>This is my example case in which I can't pass parameters.</p>\n<pre><code>public class SomeContainer&lt;E extends Object&gt; {\n E object;\n\n void resetObject throws Exception{\n object = (E) object.getClass().getDeclaredConstructor().newInstance();\n }\n}\n</code></pre>\n<p>Using reflection create run time error, if you extends your generic class with none object type. To extends your generic type to object convert this error to compile time error.</p>\n" }, { "answer_id": 57112253, "author": "Sudhanshu Jain", "author_id": 6685277, "author_profile": "https://Stackoverflow.com/users/6685277", "pm_score": 2, "selected": false, "text": "<p>what you can do is -</p>\n\n<ol>\n<li><p>First declare the variable of that generic class </p>\n\n<p>2.Then make a constructor of it and instantiate that object</p></li>\n<li><p>Then use it wherever you want to use it</p></li>\n</ol>\n\n<p>example-</p>\n\n<p>1 </p>\n\n<blockquote>\n <p><code>private Class&lt;E&gt; entity;</code></p>\n</blockquote>\n\n<p>2 </p>\n\n<pre><code>public xyzservice(Class&lt;E&gt; entity) {\n this.entity = entity;\n }\n\n\n\npublic E getEntity(Class&lt;E&gt; entity) throws InstantiationException, IllegalAccessException {\n return entity.newInstance();\n }\n</code></pre>\n\n<p>3.</p>\n\n<blockquote>\n <p>E e = getEntity(entity);</p>\n</blockquote>\n" }, { "answer_id": 57125467, "author": "cacheoff", "author_id": 2549901, "author_profile": "https://Stackoverflow.com/users/2549901", "pm_score": 2, "selected": false, "text": "<p>Use the <a href=\"https://static.javadoc.io/com.google.code.gson/gson/2.6.2/com/google/gson/reflect/TypeToken.html\" rel=\"nofollow noreferrer\"><code>TypeToken&lt;T&gt;</code></a> class:</p>\n\n<pre><code>public class MyClass&lt;T&gt; {\n public T doSomething() {\n return (T) new TypeToken&lt;T&gt;(){}.getRawType().newInstance();\n }\n}\n</code></pre>\n" }, { "answer_id": 67363847, "author": "Braian Coronel", "author_id": 5279996, "author_profile": "https://Stackoverflow.com/users/5279996", "pm_score": 0, "selected": false, "text": "<p>Note that a generic type in kotlin could come without a default constructor.</p>\n<pre><code> implementation(&quot;org.objenesis&quot;,&quot;objenesis&quot;, &quot;3.2&quot;)\n</code></pre>\n<hr />\n<pre><code> val fooType = Foo::class.java\n var instance: T = try {\n fooType.newInstance()\n } catch (e: InstantiationException) {\n// Use Objenesis because the fooType class has not a default constructor\n val objenesis: Objenesis = ObjenesisStd()\n objenesis.newInstance(fooType)\n }\n</code></pre>\n<ul>\n<li><a href=\"https://stackoverflow.com/q/4133709/5279996\">Withou default constructor</a></li>\n<li><a href=\"http://objenesis.org/tutorial.html\" rel=\"nofollow noreferrer\">Objenesis</a></li>\n</ul>\n" }, { "answer_id": 68001457, "author": "michal.jakubeczy", "author_id": 2470765, "author_profile": "https://Stackoverflow.com/users/2470765", "pm_score": 0, "selected": false, "text": "<p>I was inspired with Ira's solution and slightly modified it.</p>\n<pre><code>abstract class SomeContainer&lt;E&gt;\n{\n protected E createContents() {\n throw new NotImplementedException();\n }\n\n public void doWork(){\n E obj = createContents();\n // Do the work with E \n }\n}\n\nclass BlackContainer extends SomeContainer&lt;Black&gt;{\n // this method is optional to implement in case you need it\n protected Black createContents() {\n return new Black();\n }\n}\n</code></pre>\n<p>In case you need <code>E</code> instance you can implement <code>createContents</code> method in your derived class (or leave it not implemented in case you don't need it.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/75175", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5309/" ]
Is it possible to create an instance of a generic type in Java? I'm thinking based on what I've seen that the answer is `no` (*due to type erasure*), but I'd be interested if anyone can see something I'm missing: ``` class SomeContainer<E> { E createContents() { return what??? } } ``` EDIT: It turns out that [Super Type Tokens](http://www.artima.com/weblogs/viewpost.jsp?thread=208860) could be used to resolve my issue, but it requires a lot of reflection-based code, as some of the answers below have indicated. I'll leave this open for a little while to see if anyone comes up with anything dramatically different than Ian Robertson's [Artima Article](http://www.artima.com/weblogs/viewpost.jsp?thread=208860).
You are correct. You can't do `new E()`. But you can change it to ``` private static class SomeContainer<E> { E createContents(Class<E> clazz) { return clazz.newInstance(); } } ``` It's a pain. But it works. Wrapping it in the factory pattern makes it a little more tolerable.
75,180
<p>If you have a statically allocated array, the Visual Studio debugger can easily display all of the array elements. However, if you have an array allocated dynamically and pointed to by a pointer, it will only display the first element of the array when you click the + to expand it. Is there an easy way to tell the debugger, show me this data as an array of type Foo and size X?</p>
[ { "answer_id": 75202, "author": "shoosh", "author_id": 9611, "author_profile": "https://Stackoverflow.com/users/9611", "pm_score": 9, "selected": true, "text": "<p>Yes, simple.\nsay you have</p>\n\n<pre><code>char *a = new char[10];\n</code></pre>\n\n<p>writing in the debugger:</p>\n\n<pre><code>a,10\n</code></pre>\n\n<p>would show you the content as if it were an array.</p>\n" }, { "answer_id": 75204, "author": "Drealmer", "author_id": 12291, "author_profile": "https://Stackoverflow.com/users/12291", "pm_score": 5, "selected": false, "text": "<p>In a watch window, add a comma after the name of the array, and the amount of items you want to be displayed.</p>\n" }, { "answer_id": 12477304, "author": "wog", "author_id": 1022328, "author_profile": "https://Stackoverflow.com/users/1022328", "pm_score": 0, "selected": false, "text": "<p>I haven't found a way to use this with a multidimensional array. But you can at least (if you know the index of your desired entry) add a watch to a specific value. Simply use the index-operator.</p>\n\n<p>For an Array named current, which has an Array named Attribs inside, which has an Array named Attrib inside, it should look like this if you like to have to position 26:</p>\n\n<pre><code>((*((*current).Attribs)).Attrib)[26]\n</code></pre>\n\n<p>You can also use an offset</p>\n\n<pre><code>((*((*current).Attribs)).Attrib)+25\n</code></pre>\n\n<p>will show ne \"next\" 25 elements. \n(I'm using VS2008, this shows only 25 elements maximum).</p>\n" }, { "answer_id": 21000009, "author": "dabinsi", "author_id": 3173933, "author_profile": "https://Stackoverflow.com/users/3173933", "pm_score": 1, "selected": false, "text": "<p>For MFC arrays (CArray, CStringArray, ...)\nfollowing the next link in its Tip #4</p>\n\n<p><a href=\"http://www.codeproject.com/Articles/469416/10-More-Visual-Studio-Debugging-Tips-for-Native-De\" rel=\"nofollow\">http://www.codeproject.com/Articles/469416/10-More-Visual-Studio-Debugging-Tips-for-Native-De</a></p>\n\n<p>For example for \"CArray pArray\", add in the Watch windows</p>\n\n<pre><code> pArray.m_pData,5 \n</code></pre>\n\n<p>to see the first 5 elements .</p>\n\n<p>If pArray is a two dimensional CArray you can look at any of the elements of the second dimension using the next syntax:</p>\n\n<pre><code> pArray.m_pData[x].m_pData,y\n</code></pre>\n" }, { "answer_id": 22239703, "author": "gpliu", "author_id": 337863, "author_profile": "https://Stackoverflow.com/users/337863", "pm_score": 3, "selected": false, "text": "<p>a revisit:</p>\n\n<p>let's assume you have a below pointer:</p>\n\n<pre><code>double ** a; // assume 5*10\n</code></pre>\n\n<p>then you can write below in Visual Studio debug watch:</p>\n\n<pre><code>(double(*)[10]) a[0],5\n</code></pre>\n\n<p>which will cast it into an array like below, and you can view all contents in one go.</p>\n\n<pre><code>double[5][10] a;\n</code></pre>\n" }, { "answer_id": 25690207, "author": "Riaz Rizvi", "author_id": 213307, "author_profile": "https://Stackoverflow.com/users/213307", "pm_score": 5, "selected": false, "text": "<p>There are two methods to view data in an array m4x4:</p>\n\n<pre><code>float m4x4[16]={\n 1.f,0.f,0.f,0.f,\n 0.f,2.f,0.f,0.f,\n 0.f,0.f,3.f,0.f,\n 0.f,0.f,0.f,4.f\n};\n</code></pre>\n\n<p>One way is with a Watch window (Debug/Windows/Watch). Add watch =</p>\n\n<pre><code>m4x4,16\n</code></pre>\n\n<p>This displays data in a list:</p>\n\n<p><img src=\"https://i.stack.imgur.com/K54SJ.png\" alt=\"enter image description here\"></p>\n\n<p>Another way is with a Memory window (Debug/Windows/Memory). Specify a memory start address = </p>\n\n<pre><code>m4x4\n</code></pre>\n\n<p>This displays data in a table, which is better for two and three dimensional matrices:</p>\n\n<p><img src=\"https://i.stack.imgur.com/kBbEI.png\" alt=\"enter image description here\"></p>\n\n<p>Right-click on the Memory window to determine how the binary data is visualized. Choices are limited to integers, floats and some text encodings.</p>\n" }, { "answer_id": 28973224, "author": "Taylor Price", "author_id": 3805, "author_profile": "https://Stackoverflow.com/users/3805", "pm_score": 2, "selected": false, "text": "<p>Yet another way to do this is specified here in <a href=\"https://msdn.microsoft.com/en-us/library/75w45ekt.aspx\" rel=\"nofollow\">MSDN</a>.</p>\n\n<p>In short, you can display a character array as several types of string. If you've got an array declared as:</p>\n\n<pre><code>char *a = new char[10];\n</code></pre>\n\n<p>You could print it as a unicode string in the watch window with the following:</p>\n\n<pre><code>a,su\n</code></pre>\n\n<p>See the tables on the MSDN page for all of the different conversions possible since there are quite a few. Many different string variants, variants to print individual items in the array, etc.</p>\n" }, { "answer_id": 31872247, "author": "Legolas", "author_id": 109787, "author_profile": "https://Stackoverflow.com/users/109787", "pm_score": 2, "selected": false, "text": "<p>You can find a list of many things you can do with variables in the watch window in this gem in the docs:\n<a href=\"https://msdn.microsoft.com/en-us/library/75w45ekt.aspx\" rel=\"nofollow\">https://msdn.microsoft.com/en-us/library/75w45ekt.aspx</a></p>\n\n<p>For a variable a, there are the things already mentioned in other answers like </p>\n\n<pre><code>a,10 \na,su \n</code></pre>\n\n<p>but there's a whole lot of other specifiers for format and size, like: </p>\n\n<pre><code>a,en (shows an enum value by name instead of the number)\na,mb (to show 1 line of 'memory' view right there in the watch window)\n</code></pre>\n" }, { "answer_id": 31900913, "author": "vicky", "author_id": 3922508, "author_profile": "https://Stackoverflow.com/users/3922508", "pm_score": 3, "selected": false, "text": "<p>For,</p>\n\n<pre><code>int **a; //row x col\n</code></pre>\n\n<p>add this to watch</p>\n\n<pre><code>(int(**)[col])a,row\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/75180", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9530/" ]
If you have a statically allocated array, the Visual Studio debugger can easily display all of the array elements. However, if you have an array allocated dynamically and pointed to by a pointer, it will only display the first element of the array when you click the + to expand it. Is there an easy way to tell the debugger, show me this data as an array of type Foo and size X?
Yes, simple. say you have ``` char *a = new char[10]; ``` writing in the debugger: ``` a,10 ``` would show you the content as if it were an array.
75,181
<p>Here's a very simple Prototype example.</p> <p>All it does is, on window load, an ajax call which sticks some html into a div.</p> <pre class="lang-html prettyprint-override"><code>&lt;html&gt; &lt;head&gt; &lt;script type=&quot;text/javascript&quot; src=&quot;scriptaculous/lib/prototype.js&quot;&gt;&lt;/script&gt; &lt;script type=&quot;text/javascript&quot;&gt; Event.observe(window, 'load', function(){ new Ajax.Request('get-table.php', { method: 'get', onSuccess: function(response){ $('content').innerHTML = response.responseText; //At this call, the div has HTML in it click1(); }, onFailure: function(){ alert('Fail!'); } }); //At this call, the div is empty click1(); }); function click1(){if($('content').innerHTML){alert('Found content');}else{alert('Empty div');}} &lt;/script&gt; &lt;/head&gt; &lt;body&gt;&lt;div id=&quot;content&quot;&gt;&lt;/div&gt;&lt;/body&gt; &lt;/html&gt; </code></pre> <p>The thing that's confusing is the context in which Prototype understands that the div actually has stuff in it.</p> <p>If you look at the onSuccess part of the ajax call, you'll see that at that point $('content').innerHTML has stuff in it.</p> <p>However when I check $('content').innerHTML right after the ajax call, it appears to be empty.</p> <p>This has to be some fundamental misunderstanding on my part. Anyone care to explain it to me?</p> <hr /> <p><strong>Edit</strong><br /> I just want to clarify something. I realize that the Ajax call is asynchronous.</p> <p>Here's the actual order that things are being executed and why it's confusing to me:</p> <ol> <li>The page loads.</li> <li>The Ajax request to get-table.php is made.</li> <li>The call to click1() INSIDE onSuccess happens. I see an alert that the div has content.</li> <li>The call to click1() AFTER the Ajax call happens. I see an alert that the div is empty.</li> </ol> <p>So it's like the code is executing in the order it's written but the DOM is not updating in the same order.</p> <hr /> <p><strong>Edit 2</strong> So the short answer is that putting the code in onSuccess is the correct place.</p> <p>Another case to consider is the one where you do an Ajax call and then do another Ajax call from the onSuccess of the first call like this:</p> <pre class="lang-js prettyprint-override"><code>new Ajax.Request('foo.php',{ method: 'get', onSuccess: function(response){ doAnotherAjaxCall(); } }); function doAnotherAjaxCall(){ new Ajax.Request('foo.php',{ method: 'get', onSuccess: function(response){ //Anything that needs to happen AFTER the call to doAnotherAjaxCall() above //needs to happen here! } }); } </code></pre>
[ { "answer_id": 75228, "author": "Jan Krüger", "author_id": 12471, "author_profile": "https://Stackoverflow.com/users/12471", "pm_score": 4, "selected": true, "text": "<p>The first letter of AJAX stands for \"asynchronous\". This means that the AJAX call is performed in the background, i.e. the AJAX request call <em>immediately returns</em>. This means that the code immediately after it is normally actually executed <em>before</em> the onSuccess handler gets called (and before the AJAX request has even finished).</p>\n\n<p>Taking into account your edited question: in some browsers (e.g. Firefox), alert boxes are not as modal as you might think. Asynchronous code may pop up an alert box even if another one is already open. In that case, the newer alert box (the one from the asynchronous code) gets displayed on top of the older one. This creates the illusion that the asynchronous code got executed first.</p>\n" }, { "answer_id": 75240, "author": "Lasar", "author_id": 9438, "author_profile": "https://Stackoverflow.com/users/9438", "pm_score": 0, "selected": false, "text": "<p>Without having tried your code: The AJAX call is executed asynchronously. Meaning that your Ajax.Request fires, then goes on to the click1() call that tells you the div is empty. At some point after that the Ajax request is finished and content is actually put into the div. At this point the onSuccess function is executed and you get the content you expected.</p>\n" }, { "answer_id": 75271, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>It's Ajax call, which is asynchronous. That means right after that request call, response hasn't come back yet, that's why $('content') is still empty.</p>\n" }, { "answer_id": 75486, "author": "Stimy", "author_id": 8852, "author_profile": "https://Stackoverflow.com/users/8852", "pm_score": 0, "selected": false, "text": "<p>The onSuccess element of the function call you are making to handle the AJAX call is executed at the time you receive a response from get-table.php. This is a separate Javascript function which you are telling the browser to call when you get an answer from get-table.php. The code below your AJAX.Request call is accessed as soon as the AJAX.Request call is made, but not necessarily before get-table.php is called. So yes I think there is a bit of a fundamental misunderstanding of how AJAX works, likely due to using a library to hide the details.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/75181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/305/" ]
Here's a very simple Prototype example. All it does is, on window load, an ajax call which sticks some html into a div. ```html <html> <head> <script type="text/javascript" src="scriptaculous/lib/prototype.js"></script> <script type="text/javascript"> Event.observe(window, 'load', function(){ new Ajax.Request('get-table.php', { method: 'get', onSuccess: function(response){ $('content').innerHTML = response.responseText; //At this call, the div has HTML in it click1(); }, onFailure: function(){ alert('Fail!'); } }); //At this call, the div is empty click1(); }); function click1(){if($('content').innerHTML){alert('Found content');}else{alert('Empty div');}} </script> </head> <body><div id="content"></div></body> </html> ``` The thing that's confusing is the context in which Prototype understands that the div actually has stuff in it. If you look at the onSuccess part of the ajax call, you'll see that at that point $('content').innerHTML has stuff in it. However when I check $('content').innerHTML right after the ajax call, it appears to be empty. This has to be some fundamental misunderstanding on my part. Anyone care to explain it to me? --- **Edit** I just want to clarify something. I realize that the Ajax call is asynchronous. Here's the actual order that things are being executed and why it's confusing to me: 1. The page loads. 2. The Ajax request to get-table.php is made. 3. The call to click1() INSIDE onSuccess happens. I see an alert that the div has content. 4. The call to click1() AFTER the Ajax call happens. I see an alert that the div is empty. So it's like the code is executing in the order it's written but the DOM is not updating in the same order. --- **Edit 2** So the short answer is that putting the code in onSuccess is the correct place. Another case to consider is the one where you do an Ajax call and then do another Ajax call from the onSuccess of the first call like this: ```js new Ajax.Request('foo.php',{ method: 'get', onSuccess: function(response){ doAnotherAjaxCall(); } }); function doAnotherAjaxCall(){ new Ajax.Request('foo.php',{ method: 'get', onSuccess: function(response){ //Anything that needs to happen AFTER the call to doAnotherAjaxCall() above //needs to happen here! } }); } ```
The first letter of AJAX stands for "asynchronous". This means that the AJAX call is performed in the background, i.e. the AJAX request call *immediately returns*. This means that the code immediately after it is normally actually executed *before* the onSuccess handler gets called (and before the AJAX request has even finished). Taking into account your edited question: in some browsers (e.g. Firefox), alert boxes are not as modal as you might think. Asynchronous code may pop up an alert box even if another one is already open. In that case, the newer alert box (the one from the asynchronous code) gets displayed on top of the older one. This creates the illusion that the asynchronous code got executed first.
75,213
<p>In C++, what is the purpose of the scope resolution operator when used without a scope? For instance:</p> <pre><code>::foo(); </code></pre>
[ { "answer_id": 75224, "author": "shoosh", "author_id": 9611, "author_profile": "https://Stackoverflow.com/users/9611", "pm_score": 2, "selected": false, "text": "<p>referring to the global scope</p>\n" }, { "answer_id": 75249, "author": "Drealmer", "author_id": 12291, "author_profile": "https://Stackoverflow.com/users/12291", "pm_score": 2, "selected": false, "text": "<p>When you already have a function named foo() in your local scope but you need to access the one in the global scope.</p>\n" }, { "answer_id": 75251, "author": "itsmatt", "author_id": 7862, "author_profile": "https://Stackoverflow.com/users/7862", "pm_score": 2, "selected": false, "text": "<p>My c++ is rusty but I believe if you have a function declared in the local scope, such as foo() and one at global scope, foo() refers to the local one. ::foo() will refer to the global one.</p>\n" }, { "answer_id": 75262, "author": "Mark", "author_id": 4405, "author_profile": "https://Stackoverflow.com/users/4405", "pm_score": 7, "selected": true, "text": "<p>It means global scope. You might need to use this operator when you have conflicting functions or variables in the same scope and you need to use a global one. You might have something like:</p>\n\n<pre><code>void bar(); // this is a global function\n\nclass foo {\n void some_func() { ::bar(); } // this function is calling the global bar() and not the class version\n void bar(); // this is a class member\n};\n</code></pre>\n\n<p>If you need to call the global bar() function from within a class member function, you should use ::bar() to get to the global version of the function.</p>\n" }, { "answer_id": 75309, "author": "Matt Price", "author_id": 852, "author_profile": "https://Stackoverflow.com/users/852", "pm_score": 3, "selected": false, "text": "<p>Also you should note, that name resolution happens before overload resolution. So if there is something with the same name in your current scope then it will stop looking for other names and try to use them.</p>\n\n<pre><code>void bar() {};\nclass foo {\n void bar(int) {};\n void foobar() { bar(); } // won't compile needs ::bar()\n void foobar(int i) { bar(i); } // ok\n}\n</code></pre>\n" }, { "answer_id": 22085788, "author": "Shafik Yaghmour", "author_id": 1708801, "author_profile": "https://Stackoverflow.com/users/1708801", "pm_score": 4, "selected": false, "text": "<p>A name that begins with the <a href=\"http://en.wikipedia.org/wiki/Scope_resolution_operator\" rel=\"noreferrer\">scope resolution operator </a>(<code>::</code>) is looked up in the global namespace. We can see this by looking at the <a href=\"http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3485.pdf\" rel=\"noreferrer\">draft C++ standard</a> section <code>3.4.3</code> <em>Qualified name lookup</em> paragraph <em>4</em> which says (<em>emphasis mine</em>):</p>\n\n<blockquote>\n <p>A name prefixed by the unary scope operator :: (5.1) <strong>is looked up in global scope</strong>, in the translation unit where it is used. The name shall be declared in global namespace scope or shall be a name whose declaration is visible in global scope because of a using-directive (3.4.3.2). The use of :: <strong>allows a global name to be referred to even if its identifier has been hidden</strong> (3.3.10).</p>\n</blockquote>\n\n<p>As the standard states this allows us to use names from the global namespace <a href=\"http://publib.boulder.ibm.com/infocenter/lnxpcomp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8l.doc%2Flanguage%2Fref%2Fcplr175.htm\" rel=\"noreferrer\">that would otherwise be hidden</a>, the example from the linked document is as follows:</p>\n\n<pre><code>int count = 0;\n\nint main(void) {\n int count = 0;\n ::count = 1; // set global count to 1\n count = 2; // set local count to 2\n return 0;\n}\n</code></pre>\n\n<p>The wording is very similar going back to <a href=\"http://www.open-std.org/Jtc1/sc22/wg21/docs/papers/2005/n1804.pdf\" rel=\"noreferrer\">N1804</a> which is the earliest draft standard available. </p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/75213", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1785/" ]
In C++, what is the purpose of the scope resolution operator when used without a scope? For instance: ``` ::foo(); ```
It means global scope. You might need to use this operator when you have conflicting functions or variables in the same scope and you need to use a global one. You might have something like: ``` void bar(); // this is a global function class foo { void some_func() { ::bar(); } // this function is calling the global bar() and not the class version void bar(); // this is a class member }; ``` If you need to call the global bar() function from within a class member function, you should use ::bar() to get to the global version of the function.
75,218
<p>How can I detect when an Exception has been thrown anywhere in my application?</p> <p>I'm try to auto-magically send myself an email whenever an exception is thrown anywhere in my Java Desktop Application. I figure this way I can be more proactive.</p> <p>I know I could just explicitly log and notify myself whenever an exception occurs, but I'd have to do it everywhere and I might(more likely will) miss a couple.</p> <p>Any suggestions?</p>
[ { "answer_id": 75274, "author": "toluju", "author_id": 12457, "author_profile": "https://Stackoverflow.com/users/12457", "pm_score": 0, "selected": false, "text": "<p>In this case I think your best bet might be to write a custom classloader to handle all classloading in your application, and whenever an exception class is requested you return a class that wraps the requested exception class. This wrapper calls through to the wrapped exception but also logs the exception event.</p>\n" }, { "answer_id": 75277, "author": "Jason Cohen", "author_id": 4926, "author_profile": "https://Stackoverflow.com/users/4926", "pm_score": 3, "selected": false, "text": "<p>The new debugging hooks in Java 1.5 let you do this. It enables e.g. \"break on any exception\" in debuggers.</p>\n\n<p><a href=\"http://java.sun.com/j2se/1.5.0/docs/guide/jpda/jdi/com/sun/jdi/event/ExceptionEvent.html\" rel=\"noreferrer\">Here's the specific Javadoc</a> you need.</p>\n" }, { "answer_id": 75285, "author": "Justin Rudd", "author_id": 12968, "author_profile": "https://Stackoverflow.com/users/12968", "pm_score": 2, "selected": false, "text": "<p>Check out <a href=\"http://java.sun.com/javase/6/docs/api/java/lang/Thread.UncaughtExceptionHandler.html\" rel=\"nofollow noreferrer\">Thread.UncaughtExceptionHandler</a>. You can set it per thread or a default one for the entire VM.</p>\n\n<p>This would at least help you catch the ones you miss.</p>\n" }, { "answer_id": 75298, "author": "Mat Mannion", "author_id": 6282, "author_profile": "https://Stackoverflow.com/users/6282", "pm_score": 1, "selected": false, "text": "<p>If you're using a web framework such as <a href=\"http://www.springframework.org\" rel=\"nofollow noreferrer\">Spring</a> then you can delegate in your web.xml to a page and then use the controller to send the email. For example:</p>\n\n<p>In web.xml:</p>\n\n<pre><code>&lt;error-page&gt;\n &lt;error-code&gt;500&lt;/error-code&gt;\n &lt;location&gt;/error/500.htm&lt;/location&gt;\n&lt;/error-page&gt;\n</code></pre>\n\n<p>Then define /error/500.htm as a controller. You can access the exception from the parameter javax.servlet.error.exception:</p>\n\n<pre><code>Exception exception = (Exception) request.getAttribute(\"javax.servlet.error.exception\");\n</code></pre>\n\n<p>If you're just running a regular Java program, then I would imagine you're stuck with public static void main(String[] args) { try { ... } catch (Exception e) {} }</p>\n" }, { "answer_id": 75302, "author": "David Webb", "author_id": 3171, "author_profile": "https://Stackoverflow.com/users/3171", "pm_score": 0, "selected": false, "text": "<p>I assume you don't mean <em>any</em> Exception but rather any <em>uncaught</em> Exception.</p>\n\n<p>If this is the case <a href=\"http://java.sun.com/developer/JDCTechTips/2001/tt0109.html#handling\" rel=\"nofollow noreferrer\">this article on the Sun Website</a> has some ideas. You need to wrap your top level method in a <code>try-catch</code> block and also do some extra work to handle other Threads.</p>\n" }, { "answer_id": 75439, "author": "shemnon", "author_id": 8020, "author_profile": "https://Stackoverflow.com/users/8020", "pm_score": 6, "selected": true, "text": "<p>You probobly don't want to mail on any exception. There are lots of code in the JDK that actaully depend on exceptions to work normally. What I presume you are more inerested in are uncaught exceptions. If you are catching the exceptions you should handle notifications there.</p>\n\n<p>In a desktop app there are two places to worry about this, in the <a href=\"/questions/tagged/event-dispatch-thread\" class=\"post-tag\" title=\"show questions tagged &#39;event-dispatch-thread&#39;\" rel=\"tag\">event-dispatch-thread</a> (EDT) and outside of the EDT. Globaly you can register a class implementing <code>java.util.Thread.UncaughtExceptionHandler</code> and register it via <code>java.util.Thread.setDefaultUncaughtExceptionHandler</code>. This will get called if an exception winds down to the bottom of the stack and the thread hasn't had a handler set on the current thread instance on the thread or the ThreadGroup.</p>\n\n<p>The EDT has a different hook for handling exceptions. A system property <code>'sun.awt.exception.handler'</code> needs to be registerd with the Fully Qualified Class Name of a class with a zero argument constructor. This class needs an instance method handle(<code>Throwable</code>) that does your work. The return type doesn't matter, and since a new instance is created every time, don't count on keeping state.</p>\n\n<p>So if you don't care what thread the exception occurred in a sample may look like this:</p>\n\n<pre><code>class ExceptionHandler implements Thread.UncaughtExceptionHandler {\n public void uncaughtException(Thread t, Throwable e) {\n handle(e);\n }\n\n public void handle(Throwable throwable) {\n try {\n // insert your e-mail code here\n } catch (Throwable t) {\n // don't let the exception get thrown out, will cause infinite looping!\n }\n }\n\n public static void registerExceptionHandler() {\n Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler());\n System.setProperty(\"sun.awt.exception.handler\", ExceptionHandler.class.getName());\n }\n}\n</code></pre>\n\n<p>Add this class into some random package, and then call the <code>registerExceptionHandler</code> method and you should be ready to go.</p>\n" }, { "answer_id": 75449, "author": "Nik", "author_id": 13267, "author_profile": "https://Stackoverflow.com/users/13267", "pm_score": 0, "selected": false, "text": "<p>Sending an email may not be possible if you are getting a runtime exception like OutOfMemoryError or StackOverflow. Most likely you will have to spawn another process and catch any exceptions thrown by it (with the various techniques mentioned above).</p>\n" }, { "answer_id": 76614, "author": "Alexandre Victoor", "author_id": 11897, "author_profile": "https://Stackoverflow.com/users/11897", "pm_score": 1, "selected": false, "text": "<p>If you are using java 1.3/1.4, Thread.UncaughtExceptionHandler is not available. \nIn this case you can use a solution based on AOP to trigger some code when an exception is thrown. Spring and/or aspectJ might be helpful.</p>\n" }, { "answer_id": 8152499, "author": "Alex Fedulov", "author_id": 336152, "author_profile": "https://Stackoverflow.com/users/336152", "pm_score": 1, "selected": false, "text": "<p>In my current project I faced the similar requirement regarding the errors detection. For this purpose I have applied the following approach: I use log4j for logging across my app, and everywhere, where the exception is caught I do the standard thing: <code>log.error(\"Error's description goes here\", e);</code>, where e is the Exception being thrown (see log4j documentation for details regarding the initialization of the \"log\").\nIn order to detect the error, I use my own Appender, which extends the log4j AppenderSkeleton class:</p>\n\n<pre><code>import org.apache.log4j.AppenderSkeleton;\nimport org.apache.log4j.spi.LoggingEvent;\n\npublic class ErrorsDetectingAppender extends AppenderSkeleton {\n\n private static boolean errorsOccured = false;\n\n public static boolean errorsOccured() {\n return errorsOccured;\n }\n\n public ErrorsDetectingAppender() {\n super();\n }\n\n @Override\n public void close() {\n // TODO Auto-generated method stub\n }\n\n @Override\n public boolean requiresLayout() {\n return false;\n }\n\n @Override\n protected void append(LoggingEvent event) {\n if (event.getLevel().toString().toLowerCase().equals(\"error\")) {\n System.out.println(\"-----------------Errors detected\");\n this.errorsOccured = true;\n }\n }\n}\n</code></pre>\n\n<p>The log4j configuration file has to just contain a definition of the new appender and its attachement to the selected logger (root in my case):</p>\n\n<pre><code>log4j.rootLogger = OTHER_APPENDERS, ED\nlog4j.appender.ED=com.your.package.ErrorsDetectingAppender\n</code></pre>\n\n<p>You can either call the errorsOccured() method of the ErrorsDetectingAppender at some significant point in your programs's execution flow or react immidiately by adding functionality to the if block in the append() method. This approach is consistent with the semantics: things that you consider errors and log them as such, are detected. If you will later consider selected errors not so important, you just change the logging level to log.warn() and report will not be sent.</p>\n" }, { "answer_id": 57960747, "author": "Raedwald", "author_id": 545127, "author_profile": "https://Stackoverflow.com/users/545127", "pm_score": 0, "selected": false, "text": "<p>There is simply no good reason to be informed of every thrown exception. I guess you are assuming that a thrown exception indicates a \"problem\" that your \"need\" to know about. But this is wrong. If an exception is thrown, caught and handled, all is well. The only thing you <em>need</em> to be worried about is an exception that is thrown but not handled (not caught). But you can do that in a <code>try</code>...<code>catch</code> clause yourself.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/75218", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2443/" ]
How can I detect when an Exception has been thrown anywhere in my application? I'm try to auto-magically send myself an email whenever an exception is thrown anywhere in my Java Desktop Application. I figure this way I can be more proactive. I know I could just explicitly log and notify myself whenever an exception occurs, but I'd have to do it everywhere and I might(more likely will) miss a couple. Any suggestions?
You probobly don't want to mail on any exception. There are lots of code in the JDK that actaully depend on exceptions to work normally. What I presume you are more inerested in are uncaught exceptions. If you are catching the exceptions you should handle notifications there. In a desktop app there are two places to worry about this, in the [event-dispatch-thread](/questions/tagged/event-dispatch-thread "show questions tagged 'event-dispatch-thread'") (EDT) and outside of the EDT. Globaly you can register a class implementing `java.util.Thread.UncaughtExceptionHandler` and register it via `java.util.Thread.setDefaultUncaughtExceptionHandler`. This will get called if an exception winds down to the bottom of the stack and the thread hasn't had a handler set on the current thread instance on the thread or the ThreadGroup. The EDT has a different hook for handling exceptions. A system property `'sun.awt.exception.handler'` needs to be registerd with the Fully Qualified Class Name of a class with a zero argument constructor. This class needs an instance method handle(`Throwable`) that does your work. The return type doesn't matter, and since a new instance is created every time, don't count on keeping state. So if you don't care what thread the exception occurred in a sample may look like this: ``` class ExceptionHandler implements Thread.UncaughtExceptionHandler { public void uncaughtException(Thread t, Throwable e) { handle(e); } public void handle(Throwable throwable) { try { // insert your e-mail code here } catch (Throwable t) { // don't let the exception get thrown out, will cause infinite looping! } } public static void registerExceptionHandler() { Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler()); System.setProperty("sun.awt.exception.handler", ExceptionHandler.class.getName()); } } ``` Add this class into some random package, and then call the `registerExceptionHandler` method and you should be ready to go.
75,245
<p>Is it possible to reach the individual columns of table2 using HQL with a configuration like this?</p> <pre><code>&lt;hibernate-mapping&gt; &lt;class table="table1"&gt; &lt;set name="table2" table="table2" lazy="true" cascade="all"&gt; &lt;key column="result_id"/&gt; &lt;many-to-many column="group_id"/&gt; &lt;/set&gt; &lt;/class&gt; &lt;/hibernate-mapping&gt; </code></pre>
[ { "answer_id": 75272, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 1, "selected": false, "text": "<p>They're just properties of table1's table2 property.</p>\n\n<pre><code>select t1.table2.property1, t1.table2.property2, ... from table1 as t1\n</code></pre>\n\n<p>You might have to join, like so</p>\n\n<pre><code>select t2.property1, t2.property2, ... \n from table1 as t1\n inner join t1.table2 as t2\n</code></pre>\n\n<p>Here's the relevant part of the <a href=\"http://www.hibernate.org/hib_docs/reference/en/html/queryhql.html#queryhql-select\" rel=\"nofollow noreferrer\">hibernate doc</a>.</p>\n" }, { "answer_id": 75402, "author": "Mike Desjardins", "author_id": 10466, "author_profile": "https://Stackoverflow.com/users/10466", "pm_score": 1, "selected": false, "text": "<p>You can query on them, but you can't make it part of the where clause. E.g.,</p>\n\n<pre><code>select t1.table2.x from table1 as t1\n</code></pre>\n\n<p>would work, but</p>\n\n<pre><code>select t1 from table1 as t1 where t1.table2.x = foo\n</code></pre>\n\n<p>would not.</p>\n" }, { "answer_id": 76181, "author": "Michael", "author_id": 13379, "author_profile": "https://Stackoverflow.com/users/13379", "pm_score": 0, "selected": false, "text": "<p>Let's say table2 has a column \"<code>color varchar(128)</code>\" and this column is properly mapped to Hibernate.</p>\n\n<p>You should be able to do something like this:</p>\n\n<pre><code>from table1 where table2.color = 'red'\n</code></pre>\n\n<p>This will return all <code>table1</code> rows that are linked to a <code>table2</code> row whose <code>color</code> column is 'red'. Note that in your Hibernate mapping, your <code>set</code> has the same name as the table it references. The above query uses the name of the <em>set</em>, <strong>not</strong> the name of the table.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/75245", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Is it possible to reach the individual columns of table2 using HQL with a configuration like this? ``` <hibernate-mapping> <class table="table1"> <set name="table2" table="table2" lazy="true" cascade="all"> <key column="result_id"/> <many-to-many column="group_id"/> </set> </class> </hibernate-mapping> ```
They're just properties of table1's table2 property. ``` select t1.table2.property1, t1.table2.property2, ... from table1 as t1 ``` You might have to join, like so ``` select t2.property1, t2.property2, ... from table1 as t1 inner join t1.table2 as t2 ``` Here's the relevant part of the [hibernate doc](http://www.hibernate.org/hib_docs/reference/en/html/queryhql.html#queryhql-select).
75,261
<p>I got this output when running <code>sudo cpan Scalar::Util::Numeric</code></p> <pre> jmm@freekbox:~/bfwsandbox/sa/angel/astroportal/dtu8e/resources$ sudo cpan Scalar::Util::Numeric [sudo] password for jmm: CPAN: Storable loaded ok Going to read /home/jmm/.cpan/Metadata Database was generated on Tue, 09 Sep 2008 16:02:51 GMT CPAN: LWP::UserAgent loaded ok Fetching with LWP: ftp://ftp.perl.org/pub/CPAN/authors/01mailrc.txt.gz Going to read /home/jmm/.cpan/sources/authors/01mailrc.txt.gz Fetching with LWP: ftp://ftp.perl.org/pub/CPAN/modules/02packages.details.txt.gz Going to read /home/jmm/.cpan/sources/modules/02packages.details.txt.gz Database was generated on Tue, 16 Sep 2008 16:02:50 GMT There's a new CPAN.pm version (v1.9205) available! [Current version is v1.7602] You might want to try install Bundle::CPAN reload cpan without quitting the current session. It should be a seamless upgrade while we are running... Fetching with LWP: ftp://ftp.perl.org/pub/CPAN/modules/03modlist.data.gz Going to read /home/jmm/.cpan/sources/modules/03modlist.data.gz Going to write /home/jmm/.cpan/Metadata Running install for module Scalar::Util::Numeric Running make for C/CH/CHOCOLATE/Scalar-Util-Numeric-0.02.tar.gz CPAN: Digest::MD5 loaded ok Checksum for /home/jmm/.cpan/sources/authors/id/C/CH/CHOCOLATE/Scalar-Util-Numeric-0.02.tar.gz ok Scanning cache /home/jmm/.cpan/build for sizes Scalar-Util-Numeric-0.02/ Scalar-Util-Numeric-0.02/Changes Scalar-Util-Numeric-0.02/lib/ Scalar-Util-Numeric-0.02/lib/Scalar/ Scalar-Util-Numeric-0.02/lib/Scalar/Util/ Scalar-Util-Numeric-0.02/lib/Scalar/Util/Numeric.pm Scalar-Util-Numeric-0.02/Makefile.PL Scalar-Util-Numeric-0.02/MANIFEST Scalar-Util-Numeric-0.02/META.yml Scalar-Util-Numeric-0.02/Numeric.xs Scalar-Util-Numeric-0.02/ppport.h Scalar-Util-Numeric-0.02/README Scalar-Util-Numeric-0.02/t/ Scalar-Util-Numeric-0.02/t/pod.t Scalar-Util-Numeric-0.02/t/Scalar-Util-Numeric.t Removing previously used /home/jmm/.cpan/build/Scalar-Util-Numeric-0.02 CPAN.pm: Going to build C/CH/CHOCOLATE/Scalar-Util-Numeric-0.02.tar.gz Checking if your kit is complete... Looks good Writing Makefile for Scalar::Util::Numeric cp lib/Scalar/Util/Numeric.pm blib/lib/Scalar/Util/Numeric.pm AutoSplitting blib/lib/Scalar/Util/Numeric.pm (blib/lib/auto/Scalar/Util/Numeric) /usr/bin/perl /usr/share/perl/5.8/ExtUtils/xsubpp -typemap /usr/share/perl/5.8/ExtUtils/typemap Numeric.xs > Numeric.xsc && mv Numeric.xsc Numeric.c cc -c -D_REENTRANT -D_GNU_SOURCE -DTHREADS_HAVE_PIDS -DDEBIAN -fno-strict-aliasing -pipe -I/usr/local/include -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -O3 -DVERSION=\"0.02\" -DXS_VERSION=\"0.02\" -fPIC "-I/usr/lib/perl/5.8/CORE" Numeric.c In file included from Numeric.xs:2: /usr/lib/perl/5.8/CORE/perl.h:420:24: error: sys/types.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:451:19: error: ctype.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:463:23: error: locale.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:480:20: error: setjmp.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:486:26: error: sys/param.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:491:23: error: stdlib.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:496:23: error: unistd.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:776:23: error: string.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:925:27: error: netinet/in.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:929:26: error: arpa/inet.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:939:25: error: sys/stat.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:961:21: error: time.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:968:25: error: sys/time.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:975:27: error: sys/times.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:982:19: error: errno.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:997:25: error: sys/socket.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:1024:21: error: netdb.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:1127:24: error: sys/ioctl.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:1156:23: error: dirent.h: No such file or directory In file included from /usr/lib/gcc/i486-linux-gnu/4.2.3/include/syslimits.h:7, from /usr/lib/gcc/i486-linux-gnu/4.2.3/include/limits.h:11, from /usr/lib/perl/5.8/CORE/perl.h:1510, from Numeric.xs:2: /usr/lib/gcc/i486-linux-gnu/4.2.3/include/limits.h:122:61: error: limits.h: No such file or directory In file included from /usr/lib/perl/5.8/CORE/perl.h:2120, from Numeric.xs:2: /usr/lib/perl/5.8/CORE/handy.h:136:25: error: inttypes.h: No such file or directory In file included from /usr/lib/perl/5.8/CORE/perl.h:2284, from Numeric.xs:2: /usr/lib/perl/5.8/CORE/unixish.h:106:21: error: signal.h: No such file or directory In file included from Numeric.xs:2: /usr/lib/perl/5.8/CORE/perl.h:2421:33: error: pthread.h: No such file or directory In file included from Numeric.xs:2: /usr/lib/perl/5.8/CORE/perl.h:2423: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘perl_os_thread’ /usr/lib/perl/5.8/CORE/perl.h:2424: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘perl_mutex’ /usr/lib/perl/5.8/CORE/perl.h:2425: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘perl_cond’ /usr/lib/perl/5.8/CORE/perl.h:2426: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘perl_key’ In file included from /usr/lib/perl/5.8/CORE/iperlsys.h:51, from /usr/lib/perl/5.8/CORE/perl.h:2733, from Numeric.xs:2: /usr/lib/perl/5.8/CORE/perlio.h:65:19: error: stdio.h: No such file or directory In file included from /usr/lib/perl/5.8/CORE/iperlsys.h:51, from /usr/lib/perl/5.8/CORE/perl.h:2733, from Numeric.xs:2: /usr/lib/perl/5.8/CORE/perlio.h:259: error: expected ‘)’ before ‘*’ token /usr/lib/perl/5.8/CORE/perlio.h:262: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token /usr/lib/perl/5.8/CORE/perlio.h:265: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token /usr/lib/perl/5.8/CORE/perlio.h:268: error: expected declaration specifiers or ‘...’ before ‘FILE’ In file included from /usr/lib/perl/5.8/CORE/perl.h:2747, from Numeric.xs:2: /usr/lib/perl/5.8/CORE/sv.h:389: error: expected specifier-qualifier-list before ‘DIR’ In file included from /usr/lib/perl/5.8/CORE/op.h:497, from /usr/lib/perl/5.8/CORE/perl.h:2754, from Numeric.xs:2: /usr/lib/perl/5.8/CORE/reentr.h:72:20: error: pwd.h: No such file or directory /usr/lib/perl/5.8/CORE/reentr.h:75:20: error: grp.h: No such file or directory /usr/lib/perl/5.8/CORE/reentr.h:85:26: error: crypt.h: No such file or directory /usr/lib/perl/5.8/CORE/reentr.h:90:27: error: shadow.h: No such file or directory In file included from /usr/lib/perl/5.8/CORE/op.h:497, from /usr/lib/perl/5.8/CORE/perl.h:2754, from Numeric.xs:2: /usr/lib/perl/5.8/CORE/reentr.h:612: error: field ‘_crypt_struct’ has incomplete type /usr/lib/perl/5.8/CORE/reentr.h:620: error: field ‘_drand48_struct’ has incomplete type /usr/lib/perl/5.8/CORE/reentr.h:624: error: field ‘_grent_struct’ has incomplete type /usr/lib/perl/5.8/CORE/reentr.h:635: error: field ‘_hostent_struct’ has incomplete type /usr/lib/perl/5.8/CORE/reentr.h:654: error: field ‘_netent_struct’ has incomplete type /usr/lib/perl/5.8/CORE/reentr.h:669: error: field ‘_protoent_struct’ has incomplete type /usr/lib/perl/5.8/CORE/reentr.h:684: error: field ‘_pwent_struct’ has incomplete type /usr/lib/perl/5.8/CORE/reentr.h:695: error: field ‘_servent_struct’ has incomplete type /usr/lib/perl/5.8/CORE/reentr.h:710: error: field ‘_spent_struct’ has incomplete type /usr/lib/perl/5.8/CORE/reentr.h:721: error: field ‘_gmtime_struct’ has incomplete type /usr/lib/perl/5.8/CORE/reentr.h:724: error: field ‘_localtime_struct’ has incomplete type /usr/lib/perl/5.8/CORE/reentr.h:771: error: field ‘_random_struct’ has incomplete type /usr/lib/perl/5.8/CORE/reentr.h:772: error: expected specifier-qualifier-list before ‘int32_t’ In file included from /usr/lib/perl/5.8/CORE/perl.h:2756, from Numeric.xs:2: /usr/lib/perl/5.8/CORE/av.h:13: error: expected specifier-qualifier-list before ‘ssize_t’ In file included from /usr/lib/perl/5.8/CORE/perl.h:2759, from Numeric.xs:2: /usr/lib/perl/5.8/CORE/scope.h:232: error: expected specifier-qualifier-list before ‘sigjmp_buf’ In file included from Numeric.xs:2: /usr/lib/perl/5.8/CORE/perl.h:2931: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘getuid’ /usr/lib/perl/5.8/CORE/perl.h:2932: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘geteuid’ /usr/lib/perl/5.8/CORE/perl.h:2933: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘getgid’ /usr/lib/perl/5.8/CORE/perl.h:2934: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘getegid’ In file included from Numeric.xs:2: /usr/lib/perl/5.8/CORE/perl.h:3238:22: error: math.h: No such file or directory In file included from /usr/lib/perl/5.8/CORE/perl.h:3881, from Numeric.xs:2: /usr/lib/perl/5.8/CORE/thrdvar.h:85: error: field ‘Tstatbuf’ has incomplete type /usr/lib/perl/5.8/CORE/thrdvar.h:86: error: field ‘Tstatcache’ has incomplete type /usr/lib/perl/5.8/CORE/thrdvar.h:91: error: field ‘Ttimesbuf’ has incomplete type In file included from /usr/lib/perl/5.8/CORE/perl.h:3883, from Numeric.xs:2: /usr/lib/perl/5.8/CORE/intrpvar.h:66: error: expected specifier-qualifier-list before ‘time_t’ In file included from /usr/lib/perl/5.8/CORE/perl.h:3950, from Numeric.xs:2: /usr/lib/perl/5.8/CORE/proto.h:128: error: expected declaration specifiers or ‘...’ before ‘mode_t’ /usr/lib/perl/5.8/CORE/proto.h:128: error: expected declaration specifiers or ‘...’ before ‘uid_t’ /usr/lib/perl/5.8/CORE/proto.h:297: error: expected declaration specifiers or ‘...’ before ‘off64_t’ /usr/lib/perl/5.8/CORE/proto.h:299: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘Perl_do_sysseek’ /usr/lib/perl/5.8/CORE/proto.h:300: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘Perl_do_tell’ /usr/lib/perl/5.8/CORE/proto.h:411: error: expected declaration specifiers or ‘...’ before ‘gid_t’ /usr/lib/perl/5.8/CORE/proto.h:411: error: expected declaration specifiers or ‘...’ before ‘uid_t’ /usr/lib/perl/5.8/CORE/proto.h:736: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘Perl_my_fork’ /usr/lib/perl/5.8/CORE/proto.h:1020: error: expected declaration specifiers or ‘...’ before ‘pid_t’ /usr/lib/perl/5.8/CORE/proto.h:1300: error: expected declaration specifiers or ‘...’ before ‘pid_t’ /usr/lib/perl/5.8/CORE/proto.h:1456: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token /usr/lib/perl/5.8/CORE/proto.h:2001: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘Perl_PerlIO_read’ /usr/lib/perl/5.8/CORE/proto.h:2002: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘Perl_PerlIO_write’ /usr/lib/perl/5.8/CORE/proto.h:2003: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘Perl_PerlIO_unread’ /usr/lib/perl/5.8/CORE/proto.h:2004: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘Perl_PerlIO_tell’ /usr/lib/perl/5.8/CORE/proto.h:2005: error: expected declaration specifiers or ‘...’ before ‘off64_t’ In file included from /usr/lib/perl/5.8/CORE/perl.h:3988, from Numeric.xs:2: /usr/lib/perl/5.8/CORE/perlvars.h:31: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘PL_thr_key’ /usr/lib/perl/5.8/CORE/perlvars.h:48: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘PL_op_mutex’ /usr/lib/perl/5.8/CORE/perlvars.h:52: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘PL_dollarzero_mutex’ /usr/lib/perl/5.8/CORE/perl.h:4485:24: error: sys/ipc.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:4486:24: error: sys/sem.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:4611:24: error: sys/file.h: No such file or directory In file included from /usr/lib/perl/5.8/CORE/perlapi.h:38, from /usr/lib/perl/5.8/CORE/XSUB.h:349, from Numeric.xs:3: /usr/lib/perl/5.8/CORE/intrpvar.h:66: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token /usr/lib/perl/5.8/CORE/intrpvar.h:237: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token /usr/lib/perl/5.8/CORE/intrpvar.h:238: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token /usr/lib/perl/5.8/CORE/intrpvar.h:239: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token /usr/lib/perl/5.8/CORE/intrpvar.h:240: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token In file included from /usr/lib/perl/5.8/CORE/perlapi.h:39, from /usr/lib/perl/5.8/CORE/XSUB.h:349, from Numeric.xs:3: /usr/lib/perl/5.8/CORE/perlvars.h:31: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token /usr/lib/perl/5.8/CORE/perlvars.h:48: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token /usr/lib/perl/5.8/CORE/perlvars.h:52: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token In file included from Numeric.xs:4: ppport.h:3042:1: warning: "PERL_UNUSED_DECL" redefined In file included from Numeric.xs:2: /usr/lib/perl/5.8/CORE/perl.h:163:1: warning: this is the location of the previous definition Numeric.c: In function ‘XS_Scalar__Util__Numeric_is_num’: Numeric.c:20: error: invalid type argument of ‘unary *’ Numeric.c:20: error: invalid type argument of ‘unary *’ Numeric.c:20: error: invalid type argument of ‘unary *’ Numeric.c:22: error: invalid type argument of ‘unary *’ Numeric.c:24: error: invalid type argument of ‘unary *’ Numeric.xs:16: error: invalid type argument of ‘unary *’ Numeric.xs:17: error: invalid type argument of ‘unary *’ Numeric.xs:20: error: invalid type argument of ‘unary *’ Numeric.xs:20: error: invalid type argument of ‘unary *’ Numeric.xs:20: error: invalid type argument of ‘unary *’ Numeric.xs:20: error: invalid type argument of ‘unary *’ Numeric.xs:20: error: invalid type argument of ‘unary *’ Numeric.c:36: error: invalid type argument of ‘unary *’ Numeric.c:36: error: invalid type argument of ‘unary *’ Numeric.c: In function ‘XS_Scalar__Util__Numeric_uvmax’: Numeric.c:43: error: invalid type argument of ‘unary *’ Numeric.c:43: error: invalid type argument of ‘unary *’ Numeric.c:43: error: invalid type argument of ‘unary *’ Numeric.c:45: error: invalid type argument of ‘unary *’ Numeric.xs:26: error: invalid type argument of ‘unary *’ Numeric.xs:26: error: invalid type argument of ‘unary *’ Numeric.xs:26: error: invalid type argument of ‘unary *’ Numeric.xs:26: error: invalid type argument of ‘unary *’ Numeric.xs:26: error: invalid type argument of ‘unary *’ Numeric.c:51: error: invalid type argument of ‘unary *’ Numeric.c:51: error: invalid type argument of ‘unary *’ Numeric.c: In function ‘boot_Scalar__Util__Numeric’: Numeric.c:60: error: invalid type argument of ‘unary *’ Numeric.c:60: error: invalid type argument of ‘unary *’ Numeric.c:60: error: invalid type argument of ‘unary *’ Numeric.c:63: error: invalid type argument of ‘unary *’ Numeric.c:63: error: invalid type argument of ‘unary *’ Numeric.c:63: error: invalid type argument of ‘unary *’ Numeric.c:63: error: invalid type argument of ‘unary *’ Numeric.c:63: error: invalid type argument of ‘unary *’ Numeric.c:63: error: invalid type argument of ‘unary *’ Numeric.c:63: error: invalid type argument of ‘unary *’ Numeric.c:63: error: invalid type argument of ‘unary *’ Numeric.c:63: error: invalid type argument of ‘unary *’ Numeric.c:63: error: invalid type argument of ‘unary *’ Numeric.c:63: error: invalid type argument of ‘unary *’ Numeric.c:65: error: invalid type argument of ‘unary *’ Numeric.c:65: error: invalid type argument of ‘unary *’ Numeric.c:66: error: invalid type argument of ‘unary *’ Numeric.c:66: error: invalid type argument of ‘unary *’ Numeric.c:67: error: invalid type argument of ‘unary *’ Numeric.c:67: error: invalid type argument of ‘unary *’ Numeric.c:67: error: invalid type argument of ‘unary *’ Numeric.c:67: error: invalid type argument of ‘unary *’ make: *** [Numeric.o] Error 1 /usr/bin/make -- NOT OK Running make test Can't test without successful make Running make install make had returned bad status, install seems impossible jmm@freekbox:~/bfwsandbox/sa/angel/astroportal/dtu8e/resources$ </pre>
[ { "answer_id": 75320, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 2, "selected": false, "text": "<p>It can't find basic system headers. Either your include path is seriously messed up, or the headers are not installed.</p>\n" }, { "answer_id": 75395, "author": "amoore", "author_id": 7573, "author_profile": "https://Stackoverflow.com/users/7573", "pm_score": 5, "selected": true, "text": "<p>You're missing your C library development headers. You should install a package that has them. These are necessary to install this module because it has to compile some non-perl C code and needs to know more about your system.</p>\n\n<p>I can't tell what kind of operating system you're on, but it looks like linux. If it's debian, you should be able to use apt-get to install the 'libc6-dev' package. That will contain the headers you need to compile this module. On other types of linux there will be a similarly named package.</p>\n" }, { "answer_id": 75399, "author": "Mark Grimes", "author_id": 13233, "author_profile": "https://Stackoverflow.com/users/13233", "pm_score": 2, "selected": false, "text": "<p>Awfully hard to read without line breaks, but it looks like you are missing <code>sys/types.h</code> on your system. Do you have a full build environment installed (gcc, make, etc.)? What OS and distribution are you using?</p>\n\n<p>In the future, you should bockquote output like this (select the text and click the quote button).</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/75261", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I got this output when running `sudo cpan Scalar::Util::Numeric` ``` jmm@freekbox:~/bfwsandbox/sa/angel/astroportal/dtu8e/resources$ sudo cpan Scalar::Util::Numeric [sudo] password for jmm: CPAN: Storable loaded ok Going to read /home/jmm/.cpan/Metadata Database was generated on Tue, 09 Sep 2008 16:02:51 GMT CPAN: LWP::UserAgent loaded ok Fetching with LWP: ftp://ftp.perl.org/pub/CPAN/authors/01mailrc.txt.gz Going to read /home/jmm/.cpan/sources/authors/01mailrc.txt.gz Fetching with LWP: ftp://ftp.perl.org/pub/CPAN/modules/02packages.details.txt.gz Going to read /home/jmm/.cpan/sources/modules/02packages.details.txt.gz Database was generated on Tue, 16 Sep 2008 16:02:50 GMT There's a new CPAN.pm version (v1.9205) available! [Current version is v1.7602] You might want to try install Bundle::CPAN reload cpan without quitting the current session. It should be a seamless upgrade while we are running... Fetching with LWP: ftp://ftp.perl.org/pub/CPAN/modules/03modlist.data.gz Going to read /home/jmm/.cpan/sources/modules/03modlist.data.gz Going to write /home/jmm/.cpan/Metadata Running install for module Scalar::Util::Numeric Running make for C/CH/CHOCOLATE/Scalar-Util-Numeric-0.02.tar.gz CPAN: Digest::MD5 loaded ok Checksum for /home/jmm/.cpan/sources/authors/id/C/CH/CHOCOLATE/Scalar-Util-Numeric-0.02.tar.gz ok Scanning cache /home/jmm/.cpan/build for sizes Scalar-Util-Numeric-0.02/ Scalar-Util-Numeric-0.02/Changes Scalar-Util-Numeric-0.02/lib/ Scalar-Util-Numeric-0.02/lib/Scalar/ Scalar-Util-Numeric-0.02/lib/Scalar/Util/ Scalar-Util-Numeric-0.02/lib/Scalar/Util/Numeric.pm Scalar-Util-Numeric-0.02/Makefile.PL Scalar-Util-Numeric-0.02/MANIFEST Scalar-Util-Numeric-0.02/META.yml Scalar-Util-Numeric-0.02/Numeric.xs Scalar-Util-Numeric-0.02/ppport.h Scalar-Util-Numeric-0.02/README Scalar-Util-Numeric-0.02/t/ Scalar-Util-Numeric-0.02/t/pod.t Scalar-Util-Numeric-0.02/t/Scalar-Util-Numeric.t Removing previously used /home/jmm/.cpan/build/Scalar-Util-Numeric-0.02 CPAN.pm: Going to build C/CH/CHOCOLATE/Scalar-Util-Numeric-0.02.tar.gz Checking if your kit is complete... Looks good Writing Makefile for Scalar::Util::Numeric cp lib/Scalar/Util/Numeric.pm blib/lib/Scalar/Util/Numeric.pm AutoSplitting blib/lib/Scalar/Util/Numeric.pm (blib/lib/auto/Scalar/Util/Numeric) /usr/bin/perl /usr/share/perl/5.8/ExtUtils/xsubpp -typemap /usr/share/perl/5.8/ExtUtils/typemap Numeric.xs > Numeric.xsc && mv Numeric.xsc Numeric.c cc -c -D_REENTRANT -D_GNU_SOURCE -DTHREADS_HAVE_PIDS -DDEBIAN -fno-strict-aliasing -pipe -I/usr/local/include -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -O3 -DVERSION=\"0.02\" -DXS_VERSION=\"0.02\" -fPIC "-I/usr/lib/perl/5.8/CORE" Numeric.c In file included from Numeric.xs:2: /usr/lib/perl/5.8/CORE/perl.h:420:24: error: sys/types.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:451:19: error: ctype.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:463:23: error: locale.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:480:20: error: setjmp.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:486:26: error: sys/param.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:491:23: error: stdlib.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:496:23: error: unistd.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:776:23: error: string.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:925:27: error: netinet/in.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:929:26: error: arpa/inet.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:939:25: error: sys/stat.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:961:21: error: time.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:968:25: error: sys/time.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:975:27: error: sys/times.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:982:19: error: errno.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:997:25: error: sys/socket.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:1024:21: error: netdb.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:1127:24: error: sys/ioctl.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:1156:23: error: dirent.h: No such file or directory In file included from /usr/lib/gcc/i486-linux-gnu/4.2.3/include/syslimits.h:7, from /usr/lib/gcc/i486-linux-gnu/4.2.3/include/limits.h:11, from /usr/lib/perl/5.8/CORE/perl.h:1510, from Numeric.xs:2: /usr/lib/gcc/i486-linux-gnu/4.2.3/include/limits.h:122:61: error: limits.h: No such file or directory In file included from /usr/lib/perl/5.8/CORE/perl.h:2120, from Numeric.xs:2: /usr/lib/perl/5.8/CORE/handy.h:136:25: error: inttypes.h: No such file or directory In file included from /usr/lib/perl/5.8/CORE/perl.h:2284, from Numeric.xs:2: /usr/lib/perl/5.8/CORE/unixish.h:106:21: error: signal.h: No such file or directory In file included from Numeric.xs:2: /usr/lib/perl/5.8/CORE/perl.h:2421:33: error: pthread.h: No such file or directory In file included from Numeric.xs:2: /usr/lib/perl/5.8/CORE/perl.h:2423: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘perl_os_thread’ /usr/lib/perl/5.8/CORE/perl.h:2424: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘perl_mutex’ /usr/lib/perl/5.8/CORE/perl.h:2425: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘perl_cond’ /usr/lib/perl/5.8/CORE/perl.h:2426: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘perl_key’ In file included from /usr/lib/perl/5.8/CORE/iperlsys.h:51, from /usr/lib/perl/5.8/CORE/perl.h:2733, from Numeric.xs:2: /usr/lib/perl/5.8/CORE/perlio.h:65:19: error: stdio.h: No such file or directory In file included from /usr/lib/perl/5.8/CORE/iperlsys.h:51, from /usr/lib/perl/5.8/CORE/perl.h:2733, from Numeric.xs:2: /usr/lib/perl/5.8/CORE/perlio.h:259: error: expected ‘)’ before ‘*’ token /usr/lib/perl/5.8/CORE/perlio.h:262: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token /usr/lib/perl/5.8/CORE/perlio.h:265: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token /usr/lib/perl/5.8/CORE/perlio.h:268: error: expected declaration specifiers or ‘...’ before ‘FILE’ In file included from /usr/lib/perl/5.8/CORE/perl.h:2747, from Numeric.xs:2: /usr/lib/perl/5.8/CORE/sv.h:389: error: expected specifier-qualifier-list before ‘DIR’ In file included from /usr/lib/perl/5.8/CORE/op.h:497, from /usr/lib/perl/5.8/CORE/perl.h:2754, from Numeric.xs:2: /usr/lib/perl/5.8/CORE/reentr.h:72:20: error: pwd.h: No such file or directory /usr/lib/perl/5.8/CORE/reentr.h:75:20: error: grp.h: No such file or directory /usr/lib/perl/5.8/CORE/reentr.h:85:26: error: crypt.h: No such file or directory /usr/lib/perl/5.8/CORE/reentr.h:90:27: error: shadow.h: No such file or directory In file included from /usr/lib/perl/5.8/CORE/op.h:497, from /usr/lib/perl/5.8/CORE/perl.h:2754, from Numeric.xs:2: /usr/lib/perl/5.8/CORE/reentr.h:612: error: field ‘_crypt_struct’ has incomplete type /usr/lib/perl/5.8/CORE/reentr.h:620: error: field ‘_drand48_struct’ has incomplete type /usr/lib/perl/5.8/CORE/reentr.h:624: error: field ‘_grent_struct’ has incomplete type /usr/lib/perl/5.8/CORE/reentr.h:635: error: field ‘_hostent_struct’ has incomplete type /usr/lib/perl/5.8/CORE/reentr.h:654: error: field ‘_netent_struct’ has incomplete type /usr/lib/perl/5.8/CORE/reentr.h:669: error: field ‘_protoent_struct’ has incomplete type /usr/lib/perl/5.8/CORE/reentr.h:684: error: field ‘_pwent_struct’ has incomplete type /usr/lib/perl/5.8/CORE/reentr.h:695: error: field ‘_servent_struct’ has incomplete type /usr/lib/perl/5.8/CORE/reentr.h:710: error: field ‘_spent_struct’ has incomplete type /usr/lib/perl/5.8/CORE/reentr.h:721: error: field ‘_gmtime_struct’ has incomplete type /usr/lib/perl/5.8/CORE/reentr.h:724: error: field ‘_localtime_struct’ has incomplete type /usr/lib/perl/5.8/CORE/reentr.h:771: error: field ‘_random_struct’ has incomplete type /usr/lib/perl/5.8/CORE/reentr.h:772: error: expected specifier-qualifier-list before ‘int32_t’ In file included from /usr/lib/perl/5.8/CORE/perl.h:2756, from Numeric.xs:2: /usr/lib/perl/5.8/CORE/av.h:13: error: expected specifier-qualifier-list before ‘ssize_t’ In file included from /usr/lib/perl/5.8/CORE/perl.h:2759, from Numeric.xs:2: /usr/lib/perl/5.8/CORE/scope.h:232: error: expected specifier-qualifier-list before ‘sigjmp_buf’ In file included from Numeric.xs:2: /usr/lib/perl/5.8/CORE/perl.h:2931: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘getuid’ /usr/lib/perl/5.8/CORE/perl.h:2932: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘geteuid’ /usr/lib/perl/5.8/CORE/perl.h:2933: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘getgid’ /usr/lib/perl/5.8/CORE/perl.h:2934: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘getegid’ In file included from Numeric.xs:2: /usr/lib/perl/5.8/CORE/perl.h:3238:22: error: math.h: No such file or directory In file included from /usr/lib/perl/5.8/CORE/perl.h:3881, from Numeric.xs:2: /usr/lib/perl/5.8/CORE/thrdvar.h:85: error: field ‘Tstatbuf’ has incomplete type /usr/lib/perl/5.8/CORE/thrdvar.h:86: error: field ‘Tstatcache’ has incomplete type /usr/lib/perl/5.8/CORE/thrdvar.h:91: error: field ‘Ttimesbuf’ has incomplete type In file included from /usr/lib/perl/5.8/CORE/perl.h:3883, from Numeric.xs:2: /usr/lib/perl/5.8/CORE/intrpvar.h:66: error: expected specifier-qualifier-list before ‘time_t’ In file included from /usr/lib/perl/5.8/CORE/perl.h:3950, from Numeric.xs:2: /usr/lib/perl/5.8/CORE/proto.h:128: error: expected declaration specifiers or ‘...’ before ‘mode_t’ /usr/lib/perl/5.8/CORE/proto.h:128: error: expected declaration specifiers or ‘...’ before ‘uid_t’ /usr/lib/perl/5.8/CORE/proto.h:297: error: expected declaration specifiers or ‘...’ before ‘off64_t’ /usr/lib/perl/5.8/CORE/proto.h:299: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘Perl_do_sysseek’ /usr/lib/perl/5.8/CORE/proto.h:300: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘Perl_do_tell’ /usr/lib/perl/5.8/CORE/proto.h:411: error: expected declaration specifiers or ‘...’ before ‘gid_t’ /usr/lib/perl/5.8/CORE/proto.h:411: error: expected declaration specifiers or ‘...’ before ‘uid_t’ /usr/lib/perl/5.8/CORE/proto.h:736: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘Perl_my_fork’ /usr/lib/perl/5.8/CORE/proto.h:1020: error: expected declaration specifiers or ‘...’ before ‘pid_t’ /usr/lib/perl/5.8/CORE/proto.h:1300: error: expected declaration specifiers or ‘...’ before ‘pid_t’ /usr/lib/perl/5.8/CORE/proto.h:1456: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token /usr/lib/perl/5.8/CORE/proto.h:2001: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘Perl_PerlIO_read’ /usr/lib/perl/5.8/CORE/proto.h:2002: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘Perl_PerlIO_write’ /usr/lib/perl/5.8/CORE/proto.h:2003: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘Perl_PerlIO_unread’ /usr/lib/perl/5.8/CORE/proto.h:2004: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘Perl_PerlIO_tell’ /usr/lib/perl/5.8/CORE/proto.h:2005: error: expected declaration specifiers or ‘...’ before ‘off64_t’ In file included from /usr/lib/perl/5.8/CORE/perl.h:3988, from Numeric.xs:2: /usr/lib/perl/5.8/CORE/perlvars.h:31: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘PL_thr_key’ /usr/lib/perl/5.8/CORE/perlvars.h:48: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘PL_op_mutex’ /usr/lib/perl/5.8/CORE/perlvars.h:52: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘PL_dollarzero_mutex’ /usr/lib/perl/5.8/CORE/perl.h:4485:24: error: sys/ipc.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:4486:24: error: sys/sem.h: No such file or directory /usr/lib/perl/5.8/CORE/perl.h:4611:24: error: sys/file.h: No such file or directory In file included from /usr/lib/perl/5.8/CORE/perlapi.h:38, from /usr/lib/perl/5.8/CORE/XSUB.h:349, from Numeric.xs:3: /usr/lib/perl/5.8/CORE/intrpvar.h:66: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token /usr/lib/perl/5.8/CORE/intrpvar.h:237: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token /usr/lib/perl/5.8/CORE/intrpvar.h:238: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token /usr/lib/perl/5.8/CORE/intrpvar.h:239: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token /usr/lib/perl/5.8/CORE/intrpvar.h:240: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token In file included from /usr/lib/perl/5.8/CORE/perlapi.h:39, from /usr/lib/perl/5.8/CORE/XSUB.h:349, from Numeric.xs:3: /usr/lib/perl/5.8/CORE/perlvars.h:31: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token /usr/lib/perl/5.8/CORE/perlvars.h:48: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token /usr/lib/perl/5.8/CORE/perlvars.h:52: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token In file included from Numeric.xs:4: ppport.h:3042:1: warning: "PERL_UNUSED_DECL" redefined In file included from Numeric.xs:2: /usr/lib/perl/5.8/CORE/perl.h:163:1: warning: this is the location of the previous definition Numeric.c: In function ‘XS_Scalar__Util__Numeric_is_num’: Numeric.c:20: error: invalid type argument of ‘unary *’ Numeric.c:20: error: invalid type argument of ‘unary *’ Numeric.c:20: error: invalid type argument of ‘unary *’ Numeric.c:22: error: invalid type argument of ‘unary *’ Numeric.c:24: error: invalid type argument of ‘unary *’ Numeric.xs:16: error: invalid type argument of ‘unary *’ Numeric.xs:17: error: invalid type argument of ‘unary *’ Numeric.xs:20: error: invalid type argument of ‘unary *’ Numeric.xs:20: error: invalid type argument of ‘unary *’ Numeric.xs:20: error: invalid type argument of ‘unary *’ Numeric.xs:20: error: invalid type argument of ‘unary *’ Numeric.xs:20: error: invalid type argument of ‘unary *’ Numeric.c:36: error: invalid type argument of ‘unary *’ Numeric.c:36: error: invalid type argument of ‘unary *’ Numeric.c: In function ‘XS_Scalar__Util__Numeric_uvmax’: Numeric.c:43: error: invalid type argument of ‘unary *’ Numeric.c:43: error: invalid type argument of ‘unary *’ Numeric.c:43: error: invalid type argument of ‘unary *’ Numeric.c:45: error: invalid type argument of ‘unary *’ Numeric.xs:26: error: invalid type argument of ‘unary *’ Numeric.xs:26: error: invalid type argument of ‘unary *’ Numeric.xs:26: error: invalid type argument of ‘unary *’ Numeric.xs:26: error: invalid type argument of ‘unary *’ Numeric.xs:26: error: invalid type argument of ‘unary *’ Numeric.c:51: error: invalid type argument of ‘unary *’ Numeric.c:51: error: invalid type argument of ‘unary *’ Numeric.c: In function ‘boot_Scalar__Util__Numeric’: Numeric.c:60: error: invalid type argument of ‘unary *’ Numeric.c:60: error: invalid type argument of ‘unary *’ Numeric.c:60: error: invalid type argument of ‘unary *’ Numeric.c:63: error: invalid type argument of ‘unary *’ Numeric.c:63: error: invalid type argument of ‘unary *’ Numeric.c:63: error: invalid type argument of ‘unary *’ Numeric.c:63: error: invalid type argument of ‘unary *’ Numeric.c:63: error: invalid type argument of ‘unary *’ Numeric.c:63: error: invalid type argument of ‘unary *’ Numeric.c:63: error: invalid type argument of ‘unary *’ Numeric.c:63: error: invalid type argument of ‘unary *’ Numeric.c:63: error: invalid type argument of ‘unary *’ Numeric.c:63: error: invalid type argument of ‘unary *’ Numeric.c:63: error: invalid type argument of ‘unary *’ Numeric.c:65: error: invalid type argument of ‘unary *’ Numeric.c:65: error: invalid type argument of ‘unary *’ Numeric.c:66: error: invalid type argument of ‘unary *’ Numeric.c:66: error: invalid type argument of ‘unary *’ Numeric.c:67: error: invalid type argument of ‘unary *’ Numeric.c:67: error: invalid type argument of ‘unary *’ Numeric.c:67: error: invalid type argument of ‘unary *’ Numeric.c:67: error: invalid type argument of ‘unary *’ make: *** [Numeric.o] Error 1 /usr/bin/make -- NOT OK Running make test Can't test without successful make Running make install make had returned bad status, install seems impossible jmm@freekbox:~/bfwsandbox/sa/angel/astroportal/dtu8e/resources$ ```
You're missing your C library development headers. You should install a package that has them. These are necessary to install this module because it has to compile some non-perl C code and needs to know more about your system. I can't tell what kind of operating system you're on, but it looks like linux. If it's debian, you should be able to use apt-get to install the 'libc6-dev' package. That will contain the headers you need to compile this module. On other types of linux there will be a similarly named package.
75,273
<p>I'm in an <strong>ASP.NET UserControl</strong>. When I type Control-K, Control-D to reformat all the markup, I get a series of messages from VS 2008:</p> <p>"Could not reformat the document. The original format was restored."</p> <p>"Could not complete the action."</p> <p>"The operation could not be completed. The parameter is incorrect."</p> <p>Anybody know what causes this?</p> <p><strong>Edit</strong>: OK, that is just...weird.</p> <p>The problem is here:</p> <pre><code>&lt;asp:TableCell&gt; &lt;asp:Button Text="Cancel" runat="server" ID="lnkCancel" CssClass="CellSingleItem" /&gt; &lt;/asp:TableCell&gt; </code></pre> <p>Somehow that asp:Button line is causing the problem. But if I delete any individual attribute, the formatting works. Or if I add a new attribute, the formatting works. Or if I change the tag to be non-self-closing, it works. But if I undo and leave it as-is, it doesn't work.</p> <p>All I can figure is that this is some sort of really obscure, bizarre bug.</p>
[ { "answer_id": 75283, "author": "John Sheehan", "author_id": 1786, "author_profile": "https://Stackoverflow.com/users/1786", "pm_score": 4, "selected": true, "text": "<p>There's probably some malformed markup somewhere in your document. Have you tried it on a fresh document?</p>\n" }, { "answer_id": 75305, "author": "Steve Morgan", "author_id": 5806, "author_profile": "https://Stackoverflow.com/users/5806", "pm_score": 1, "selected": false, "text": "<p>I encountered this for the first time a few weeks ago. I found it was down to invalid HTML. I had to cut out sections of content and paste it back in a little at a time to track down the problem.</p>\n" }, { "answer_id": 75308, "author": "palehorse", "author_id": 312, "author_profile": "https://Stackoverflow.com/users/312", "pm_score": 2, "selected": false, "text": "<p>Usually this sort of behavior is caused by invalid code. It may only be invalid HTML causing it which would still allow the program to be compiled.</p>\n\n<p>For example, if tags are mismatched like this the IDE cannot reformat it.</p>\n\n<pre><code>&lt;div&gt;&lt;h1&gt;My Title&lt;/div&gt;&lt;/h1\n</code></pre>\n\n<p>Check your warnings to see if there are any entries pointing towards mismatched or unclosed tags.</p>\n" }, { "answer_id": 1849607, "author": "Calvin", "author_id": 225079, "author_profile": "https://Stackoverflow.com/users/225079", "pm_score": 1, "selected": false, "text": "<p>For me, I had some bogus characters in my markup code. I only found this out by copy and pasting all my text into Notepad. After that, I saw the bogus characters (showed up as little squares). I just deleted those lines and retyped them and now everything is ok.</p>\n" }, { "answer_id": 2026362, "author": "Iman", "author_id": 184572, "author_profile": "https://Stackoverflow.com/users/184572", "pm_score": 2, "selected": false, "text": "<p>select the entire suspicious codes segments and use Ctrl+k,Ctrl+F to format only the selected segments instead of whole document .</p>\n\n<p>this way you can find the exact place of problems specially not closed or inappropriate closed tags and fix them .</p>\n\n<p>after all scanning segment by segment is done you can format the whole document for sure</p>\n" }, { "answer_id": 3549709, "author": "jordanbtucker", "author_id": 164430, "author_profile": "https://Stackoverflow.com/users/164430", "pm_score": 2, "selected": false, "text": "<p>For me, it's usually as issue with whitespace. To fix it, I open Find and Replace (CTRL+H), set <strong>Look in</strong> to \"Current Document\", check <strong>Use</strong> and select \"Regular expressions\". For <strong>Find what</strong> I enter \":b|\\n\" (minus quotes), and for <strong>Replace with</strong> I enter a single space. Then I click <strong>Replace All</strong>.</p>\n\n<p>The steps above will replace all whitespace—including line breaks—with a single space, and the next time you format the document, you shouldn't get any errors. That is assuming you don't have malformed HTML.</p>\n" }, { "answer_id": 7331909, "author": "Olle89", "author_id": 596847, "author_profile": "https://Stackoverflow.com/users/596847", "pm_score": 3, "selected": false, "text": "<p>Did get the problem today.</p>\n\n<p>My solution: Restart Visual Studio</p>\n" }, { "answer_id": 41345298, "author": "ViVi", "author_id": 5621607, "author_profile": "https://Stackoverflow.com/users/5621607", "pm_score": 0, "selected": false, "text": "<p>Just to add some more information. This issue is caused due to some invalid markup in <code>html</code>. \nIt won't cause any blocking while running the application. </p>\n\n<p>Unfortunately the solutions mentioned here did not work for me.\n1. Restarting visual studio\n2. Replacing spaces using regex etc</p>\n\n<p>The best solution to fix the issue is to go to the specific line where the issue is caused and check that line for any invalid symbols like <code>,</code> or <code>\"</code>. Just remove it and it will work fine.</p>\n" }, { "answer_id": 48592288, "author": "Sterling Diaz", "author_id": 1228807, "author_profile": "https://Stackoverflow.com/users/1228807", "pm_score": 2, "selected": false, "text": "<p>My problem was an extra <code>\"</code>. Look carefully the html.</p>\n" }, { "answer_id": 58850704, "author": "ydinesh", "author_id": 5891802, "author_profile": "https://Stackoverflow.com/users/5891802", "pm_score": 0, "selected": false, "text": "<p>My issue is extra \" in the value of html attribute, After removing this it is working fine for me.</p>\n" }, { "answer_id": 66116857, "author": "Prince Tyagi", "author_id": 14886434, "author_profile": "https://Stackoverflow.com/users/14886434", "pm_score": 1, "selected": false, "text": "<p>I had an unwanted semi-colon. But you may have quote ('), double quote (&quot;), semi-colon (;) or any special character.</p>\n<p>So, editing my answer with more details and a screenshot because it still very active.</p>\n<p><a href=\"https://i.stack.imgur.com/7jn4Z.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/7jn4Z.png\" alt=\"enter image description here\" /></a></p>\n<p>Go to that line by double clicking the error and search for the extra (unwanted) quote ('), double quote (&quot;), semi-colon (;) or any special character. Remove it because it is causing the error.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/75273", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5486/" ]
I'm in an **ASP.NET UserControl**. When I type Control-K, Control-D to reformat all the markup, I get a series of messages from VS 2008: "Could not reformat the document. The original format was restored." "Could not complete the action." "The operation could not be completed. The parameter is incorrect." Anybody know what causes this? **Edit**: OK, that is just...weird. The problem is here: ``` <asp:TableCell> <asp:Button Text="Cancel" runat="server" ID="lnkCancel" CssClass="CellSingleItem" /> </asp:TableCell> ``` Somehow that asp:Button line is causing the problem. But if I delete any individual attribute, the formatting works. Or if I add a new attribute, the formatting works. Or if I change the tag to be non-self-closing, it works. But if I undo and leave it as-is, it doesn't work. All I can figure is that this is some sort of really obscure, bizarre bug.
There's probably some malformed markup somewhere in your document. Have you tried it on a fresh document?
75,282
<p>I'm handling the <code>onSelectIndexChanged</code> event. An event is raised when the DropDownList selection changes. the problem is that the DropDownList still returns the old values for <code>SelectedValue</code> and <code>SelectedIndex</code>. What am I doing wrong?</p> <p>Here is the DropDownList definition from the aspx file:</p> <pre><code>&lt;div style="margin: 0px; padding: 0px 1em 0px 0px;"&gt; &lt;span style="margin: 0px; padding: 0px; vertical-align: top;"&gt;Route:&lt;/span&gt; &lt;asp:DropDownList id="Select1" runat="server" onselectedindexchanged="index_changed" AutoPostBack="true"&gt; &lt;/asp:DropDownList&gt; &lt;asp:Literal ID="Literal1" runat="server"&gt;&lt;/asp:Literal&gt; &lt;/div&gt; </code></pre> <p>Here is the DropDownList <code>OnSelectedIndexChanged</code> event handler:</p> <pre><code>protected void index_changed(object sender, EventArgs e) { decimal d = Convert.ToDecimal( Select1.SelectedValue ); Literal1.Text = d.ToString(); } </code></pre>
[ { "answer_id": 75306, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 5, "selected": true, "text": "<p>Do you have any code in page load that is by chance re-defaulting the value to the first value?</p>\n\n<p>When the page reloads do you see the new value?</p>\n" }, { "answer_id": 75383, "author": "Donn Felker", "author_id": 5210, "author_profile": "https://Stackoverflow.com/users/5210", "pm_score": 0, "selected": false, "text": "<p>Is it possible that you have items copied throughout your datasource for the drop down list? </p>\n" }, { "answer_id": 75389, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>add this:\nif page.isnotpostback {</p>\n\n<p>}\naround your code to bind the dropdownlist. </p>\n" }, { "answer_id": 75437, "author": "axk", "author_id": 578, "author_profile": "https://Stackoverflow.com/users/578", "pm_score": 2, "selected": false, "text": "<p>This may seem obvious, but anyway.\nDo you initialize this dropdown with an initial value in some other event handler like OnLoad ?\nIf so you should check if that event is risen by a postback or by the first load. So you should have something like</p>\n\n<pre><code>if(!IsPostback) d.SelectedValue = \"Default\"\n</code></pre>\n" }, { "answer_id": 75827, "author": "Jason Stevenson", "author_id": 13368, "author_profile": "https://Stackoverflow.com/users/13368", "pm_score": 2, "selected": false, "text": "<p>If you are using AJAX you may also be doing a callback, not a full postback. In that case you may want to use this in your page load method:</p>\n\n<pre><code> if (!IsCallback &amp;&amp; !IsPostBack)\n {\n // Do your page setup here\n }\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/75282", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4491/" ]
I'm handling the `onSelectIndexChanged` event. An event is raised when the DropDownList selection changes. the problem is that the DropDownList still returns the old values for `SelectedValue` and `SelectedIndex`. What am I doing wrong? Here is the DropDownList definition from the aspx file: ``` <div style="margin: 0px; padding: 0px 1em 0px 0px;"> <span style="margin: 0px; padding: 0px; vertical-align: top;">Route:</span> <asp:DropDownList id="Select1" runat="server" onselectedindexchanged="index_changed" AutoPostBack="true"> </asp:DropDownList> <asp:Literal ID="Literal1" runat="server"></asp:Literal> </div> ``` Here is the DropDownList `OnSelectedIndexChanged` event handler: ``` protected void index_changed(object sender, EventArgs e) { decimal d = Convert.ToDecimal( Select1.SelectedValue ); Literal1.Text = d.ToString(); } ```
Do you have any code in page load that is by chance re-defaulting the value to the first value? When the page reloads do you see the new value?
75,322
<p>I have an ASP.Net/AJAX control kit project that i am working on. 80% of the time there is no problem. The page runs as it should. If you refresh the page it will sometimes show a javascript error "Sys is undefined".</p> <p>It doesn't happen all the time, but it is reproducible. When it happens, the user has to shut down their browser and reopen the page.</p> <p>This leads me to believe that it could be an IIS setting.</p> <p>Another note. I looked at the page source both when I get the error, and when not. When the page throws errors the following code is missing:</p> <pre><code>&lt;script src="/ScriptResource.axd?d=EAvfjPfYejDh0Z2Zq5zTR_TXqL0DgVcj_h1wz8cst6uXazNiprV1LnAGq3uL8N2vRbpXu46VsAMFGSgpfovx9_cO8tpy2so6Qm_0HXVGg_Y1&amp;amp;t=baeb8cc" type="text/javascript"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; //&lt;![CDATA[ if (typeof(Sys) === 'undefined') throw new Error('ASP.NET Ajax client-side framework failed to load.'); //]]&gt; &lt;/script&gt; </code></pre>
[ { "answer_id": 75460, "author": "Compulsion", "author_id": 3675, "author_profile": "https://Stackoverflow.com/users/3675", "pm_score": 3, "selected": false, "text": "<p>Try setting your ScriptManager to this.</p>\n\n<pre><code>&lt;asp:ScriptManager ID=\"ScriptManager1\" runat=\"server\" EnablePartialRendering=\"true\" /&gt; \n</code></pre>\n" }, { "answer_id": 97842, "author": "Aaron Powell", "author_id": 11388, "author_profile": "https://Stackoverflow.com/users/11388", "pm_score": 2, "selected": false, "text": "<p>In addition to ensuring you have the ScriptManager on your page you need to ensure that your web.config is appropriately configured.</p>\n\n<p>When ASP.NET AJAX 1.0 was released (for .NET 2.0) there was a lot of custom web.config settings which added handlers, controls, etc.</p>\n\n<p>You'll find the config info here: <a href=\"http://www.asp.net/AJAX/documentation/live/ConfiguringASPNETAJAX.aspx\" rel=\"nofollow noreferrer\">http://www.asp.net/AJAX/documentation/live/ConfiguringASPNETAJAX.aspx</a></p>\n" }, { "answer_id": 200316, "author": "Tom Carter", "author_id": 2839, "author_profile": "https://Stackoverflow.com/users/2839", "pm_score": 2, "selected": false, "text": "<p>Make sure that any client scripts you have that interact with .NET AJAX have the following line at the end:</p>\n\n<pre><code>if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();\n</code></pre>\n\n<p>This tells the script manager that the whole script file has loaded and that it can begin to call client methods</p>\n" }, { "answer_id": 538200, "author": "MadMax1138", "author_id": 65187, "author_profile": "https://Stackoverflow.com/users/65187", "pm_score": 2, "selected": false, "text": "<p>I was having this same issue and after much wrangling I decided to try and isolate the problem and simply load the script manager in an empty page which still resulted in this same error. Having isolated the problem I discovered through a comparison of my site's web.config with a brand new (working) test site that changing <code>&lt;compilation debug=\"true\"&gt;</code> to <code>&lt;compilation debug=\"false\"&gt;</code> in the system.web section of my web.config fixes the problem. </p>\n\n<p>I also had to remove the <code>&lt;xhtmlConformance mode=\"Legacy\"/&gt;</code> entry from system.web to make the update panel work properly. <a href=\"http://weblogs.asp.net/scottgu/archive/2006/12/10/gotcha-don-t-use-xhtmlconformance-mode-legacy-with-asp-net-ajax.aspx\" rel=\"nofollow noreferrer\">Click here</a> for a description of this issue.</p>\n" }, { "answer_id": 678245, "author": "TygerKrash", "author_id": 7652, "author_profile": "https://Stackoverflow.com/users/7652", "pm_score": 0, "selected": false, "text": "<p>Was having a similar issue, except that my page was consistently generating the Sys is undefined error. </p>\n\n<p>For me the problem stems from the fact that I've just installed the AJAX 1.0 extension for .NET 2.0 but had already created my web project in Visual Studio.</p>\n\n<p>When tried to create AJAX controls I kept encountering this error, I spotted Slace's and MadMax1138s posts here. And figured it was my web.config, I created a new project using the new \"AJAX enabled web site\" project type, and sure enough the web.config has a large number of customizations necessary to use the AJAX controls. </p>\n\n<p>I just updated that web.config with the web.config updates I had already made myself and dropped it into my existing project and everything worked fine.</p>\n" }, { "answer_id": 1718513, "author": "Dean L", "author_id": 127887, "author_profile": "https://Stackoverflow.com/users/127887", "pm_score": 6, "selected": false, "text": "<p>I fixed my problem by moving the <code>&lt;script type=\"text/javascript\"&gt;&lt;/script&gt;</code> block containing the Sys.* calls lower down (to the last item before the close of the body's <code>&lt;asp:Content/&gt;</code> section) in the HTML on the page. I originally had my the script block in the HEAD <code>&lt;asp:Content/&gt;</code> section of my page. I was working inside a page that had a MasterPageFile. Hope this helps someone out.</p>\n" }, { "answer_id": 2563888, "author": "Ray", "author_id": 4872, "author_profile": "https://Stackoverflow.com/users/4872", "pm_score": 4, "selected": false, "text": "<p>When I experienced the errors </p>\n\n<ul>\n<li>Sys is undefined</li>\n<li>ASP.NET Ajax client-side framework failed to load</li>\n</ul>\n\n<p>in IE when using ASP.NET Ajax controls in .NET 2.0, I needed to add the following to the web.config file within the <code>&lt;system.web&gt;</code> tags:</p>\n\n<pre><code>&lt;httpHandlers&gt;\n &lt;remove verb=\"*\" path=\"*.asmx\"/&gt;\n &lt;add verb=\"*\" path=\"*.asmx\" validate=\"false\" type=\"System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\"/&gt;\n &lt;add verb=\"GET\" path=\"ScriptResource.axd\" type=\"System.Web.Handlers.ScriptResourceHandler\" validate=\"false\"/&gt;\n&lt;/httpHandlers&gt;\n</code></pre>\n" }, { "answer_id": 2789879, "author": "Arsalan", "author_id": 335611, "author_profile": "https://Stackoverflow.com/users/335611", "pm_score": -1, "selected": false, "text": "<p>Please please please do check that the Server has the correct time and date set...</p>\n\n<p>After about wasting 6 hours, i read it somewhere...</p>\n\n<p>The date and time for the server must be updated to work correctly...</p>\n\n<p>otherwise you will get 'Sys' is undefined error.</p>\n" }, { "answer_id": 2856354, "author": "kaash", "author_id": 343901, "author_profile": "https://Stackoverflow.com/users/343901", "pm_score": -1, "selected": false, "text": "<p>Just create blank .axd files in your solutions root foder problem will be resolved. (2 file: scriptresouce.asx, webresource.asxd)</p>\n" }, { "answer_id": 3511184, "author": "g9ncom", "author_id": 341062, "author_profile": "https://Stackoverflow.com/users/341062", "pm_score": 0, "selected": false, "text": "<p>I have been seeing the exact same error today, but it was not a config or direct JavaScript issue.</p>\n\n<p>An external .net project had been updated but the changes not picked up properly in the compilation of the web site. My presumption is that ASP.NET ajax was not able to construct the client representations of the .NET objects properly and so was failing to load correctly.</p>\n\n<p>To resolve, I rebuilt the external project(s), and rebuilt my solution that was experiencing issues. The problem went away. </p>\n" }, { "answer_id": 3757770, "author": "Anish", "author_id": 453539, "author_profile": "https://Stackoverflow.com/users/453539", "pm_score": -1, "selected": false, "text": "<p>Hi thanx a lot it solved my issue ,</p>\n\n<p>By default vs 2008 will add </p>\n\n<pre><code> &lt;!--&lt;add verb=\"*\" path=\"*.asmx\" validate=\"false\" type=\"Microsoft.Web.Script.Services.ScriptHandlerFactory, Microsoft.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\" /&gt;\n &lt;add verb=\"GET\" path=\"ScriptResource.axd\" type=\"Microsoft.Web.Handlers.ScriptResourceHandler\" validate=\"false\" /&gt;--&gt;\n</code></pre>\n\n<p>Need to correct Default config(Above) to below code\n<strong>FIX</strong></p>\n\n<pre><code> &lt;add verb=\"*\" path=\"*.asmx\" validate=\"false\" type=\"System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\"/&gt;\n &lt;add verb=\"GET\" path=\"ScriptResource.axd\" type=\"System.Web.Handlers.ScriptResourceHandler\" validate=\"false\"/&gt;\n</code></pre>\n" }, { "answer_id": 4260550, "author": "Alcides Martínez", "author_id": 518003, "author_profile": "https://Stackoverflow.com/users/518003", "pm_score": 3, "selected": false, "text": "<p>You must add these lines in the web.config</p>\n\n<p>\n \n \n \n \n \n \n \n \n \n \n </p>\n\n<pre><code>&lt;httpHandlers&gt;\n &lt;remove verb=\"*\" path=\"*.asmx\"/&gt;\n &lt;add verb=\"*\" path=\"*.asmx\" validate=\"false\" type=\"System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\"/&gt;\n &lt;add verb=\"*\" path=\"*_AppService.axd\" validate=\"false\" type=\"System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\"/&gt;\n &lt;add verb=\"GET,HEAD\" path=\"ScriptResource.axd\" type=\"System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\" validate=\"false\"/&gt;\n&lt;/httpHandlers&gt;\n&lt;httpModules&gt;\n &lt;add name=\"ScriptModule\" type=\"System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\"/&gt;\n&lt;/httpModules&gt;\n&lt;/system.web&gt;\n</code></pre>\n\n<p>\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n </p>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 6020313, "author": "JonK", "author_id": 755955, "author_profile": "https://Stackoverflow.com/users/755955", "pm_score": 0, "selected": false, "text": "<p>I found the error when using a combination of the Ajax Control Toolkit ToolkitScriptManager and URL Write 2.0.</p>\n\n<p>In my <code>&lt;rewrite&gt; &lt;outboundRules&gt;</code> I had a precondition:</p>\n\n<pre><code>&lt;preConditions&gt;\n &lt;preCondition name=\"IsHTML\"&gt;\n &lt;add input=\"{RESPONSE_CONTENT_TYPE}\" pattern=\"^text/html\"/&gt;\n &lt;/preCondition&gt;\n&lt;/preConditions&gt;\n</code></pre>\n\n<p>But apparently some of my outbound rules weren't set to use the precondition. </p>\n\n<p>Once I had that preCondition set on all my outbound rules:</p>\n\n<pre><code>&lt;rule preCondition=\"IsHTML\" name=\"MyOutboundRule\"&gt;\n</code></pre>\n\n<p>No more problem. </p>\n" }, { "answer_id": 6291807, "author": "Zara_me", "author_id": 121336, "author_profile": "https://Stackoverflow.com/users/121336", "pm_score": 1, "selected": false, "text": "<p>I solved this problem by creating separate asp.net ajax solution and copy and paste all ajax configuration from web.config to working project.</p>\n\n<p>here are the must configuration you should set in web.config</p>\n\n<pre><code> &lt;configuration&gt;\n&lt;configSections&gt;\n &lt;sectionGroup name=\"system.web.extensions\" type=\"System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\"&gt;\n &lt;sectionGroup name=\"scripting\" type=\"System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\"&gt;\n &lt;section name=\"scriptResourceHandler\" type=\"System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\" requirePermission=\"false\" allowDefinition=\"MachineToApplication\"/&gt;\n&lt;/sectionGroup&gt;\n\n &lt;/sectionGroup&gt;\n&lt;/configSections&gt;\n</code></pre>\n\n<p></p>\n\n<pre><code> &lt;assemblies&gt;\n\n &lt;add assembly=\"System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\"/&gt;\n\n &lt;/assemblies&gt;\n &lt;/compilation&gt;\n &lt;httpHandlers&gt;\n &lt;remove verb=\"*\" path=\"*.asmx\"/&gt;\n &lt;add verb=\"*\" path=\"*.asmx\" validate=\"false\" type=\"System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\"/&gt;\n &lt;add verb=\"*\" path=\"*_AppService.axd\" validate=\"false\" type=\"System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\"/&gt;\n &lt;add verb=\"GET,HEAD\" path=\"ScriptResource.axd\" type=\"System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\" validate=\"false\"/&gt;\n &lt;/httpHandlers&gt;\n &lt;httpModules&gt;\n &lt;add name=\"ScriptModule\" type=\"System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\"/&gt;\n &lt;/httpModules&gt;\n&lt;/system.web&gt;\n &lt;system.webServer&gt;\n &lt;validation validateIntegratedModeConfiguration=\"false\"/&gt;\n &lt;modules&gt;\n &lt;add name=\"ScriptModule\" preCondition=\"integratedMode\" type=\"System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\"/&gt;\n &lt;/modules&gt;\n &lt;handlers&gt;\n &lt;remove name=\"WebServiceHandlerFactory-Integrated\"/&gt;\n &lt;add name=\"ScriptHandlerFactory\" verb=\"*\" path=\"*.asmx\" preCondition=\"integratedMode\" type=\"System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\"/&gt;\n &lt;add name=\"ScriptHandlerFactoryAppServices\" verb=\"*\" path=\"*_AppService.axd\" preCondition=\"integratedMode\" type=\"System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\"/&gt;\n &lt;add name=\"ScriptResource\" preCondition=\"integratedMode\" verb=\"GET,HEAD\" path=\"ScriptResource.axd\" type=\"System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\"/&gt;\n &lt;/handlers&gt;\n&lt;/system.webServer&gt;\n</code></pre>\n" }, { "answer_id": 6870078, "author": "Max", "author_id": 260093, "author_profile": "https://Stackoverflow.com/users/260093", "pm_score": 0, "selected": false, "text": "<p>Make sure you don't have any Rewrite rules that change your url.</p>\n\n<p>In my case the application thought it was only level deeper then the url reached.</p>\n\n<p>Example: <a href=\"http://mysite.com/app/page.aspx\" rel=\"nofollow\">http://mysite.com/app/page.aspx</a> was the real url.\nBut i cut off /app/ this worked fine for ASP.net and WCF, but clearly not for Ajax.</p>\n" }, { "answer_id": 9350258, "author": "Zviadi", "author_id": 299203, "author_profile": "https://Stackoverflow.com/users/299203", "pm_score": 3, "selected": false, "text": "<p>I was using telerik and had exactly same problem.</p>\n\n<p>adding this to web.config resolved my issue :)</p>\n\n<pre><code>&lt;location path=\"Telerik.Web.UI.WebResource.axd\"&gt; \n &lt;system.web&gt; \n &lt;authorization&gt; \n &lt;allow users=\"*\"/&gt; \n &lt;/authorization&gt; \n &lt;/system.web&gt; \n&lt;/location&gt;\n</code></pre>\n\n<p>maybe it will help you too. it was Authentication problem.</p>\n\n<p><a href=\"http://blogs.telerik.com/blogs/posts/10-03-16/common-reasons-for-the-lsquo-sys-is-undefined-rsquo-error-in-asp-net-ajax-applications.aspx\" rel=\"nofollow\">Source</a></p>\n" }, { "answer_id": 9442728, "author": "v s", "author_id": 1023156, "author_profile": "https://Stackoverflow.com/users/1023156", "pm_score": 0, "selected": false, "text": "<p>I had similar problems and to my surprise what I found that one of my developer had saved web.config in the same folder/solution as <strong>web123.config</strong> and by mistake both of these files were uploaded.</p>\n\n<p>As soon as I deleted the <strong>web123.config</strong> file, this error disappeared and ajax framework was loading correctly. even though I have </p>\n\n<pre><code>&lt;compilation debug=\"true\"&gt;\n</code></pre>\n\n<p>In my case I also have following segment. My project is using framework 3.5</p>\n\n<pre><code> &lt;httpHandlers&gt;\n &lt;remove verb=\"*\" path=\"*.asmx\"/&gt;\n &lt;add verb=\"*\" path=\"*.asmx\" validate=\"false\" type=\"System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\"/&gt;\n &lt;add verb=\"*\" path=\"*_AppService.axd\" validate=\"false\" type=\"System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\"/&gt;\n &lt;add verb=\"GET,HEAD\" path=\"ScriptResource.axd\" type=\"System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\" validate=\"false\"/&gt;\n&lt;/httpHandlers&gt;\n&lt;httpModules&gt;\n &lt;add name=\"ScriptModule\" type=\"System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\"/&gt;\n&lt;/httpModules&gt;\n&lt;/system.web&gt;\n</code></pre>\n" }, { "answer_id": 11031391, "author": "Carl Onager", "author_id": 1400368, "author_profile": "https://Stackoverflow.com/users/1400368", "pm_score": 0, "selected": false, "text": "<p>This is going to sound stupid but I had a similar problem with a site being developed in VS2010 and hosted in the VS Dev Server. The page in question had a scriptmanager to create the connection to a wcf service. I added an extra method to the service and this error started appearing. </p>\n\n<p>What fixed it for me was changing from 'Auto-assign Port' to 'Specific port' with a different port number in the oroject Web settings.</p>\n\n<p>I wish I knew why...</p>\n" }, { "answer_id": 13631823, "author": "GoldBishop", "author_id": 659246, "author_profile": "https://Stackoverflow.com/users/659246", "pm_score": 0, "selected": false, "text": "Development Environment:\n<ul>\n<li>Dev-Env: VS 2012</li>\n<li>FX: 4.0/4.5</li>\n<li>Implementations: Master(ScriptManager + UpdatePanel/Timer) + Content (UpdatePanel)</li>\n<li>Patterns: PageRouting.</li>\n</ul>\n<h2>Disclaimer:</h2>\n<p>If all the <code>web.config</code> solutions do not work for you and you have implemented PageRouting (IIS 7+), then the code snippet below will solve your problems.</p>\n<h2>Background:</h2>\n<p>Dont mean to Highjack this question but had the same problem as everyone else and implemented 100% of the suggestions here, with minor modifications for .Net 4.0/4.5, and none of them worked for me.</p>\n<p>In my situation i had implemented <a href=\"http://msdn.microsoft.com/en-us/library/cc668201.aspx\" rel=\"nofollow noreferrer\">Page Routing</a> which was ghosting my problem. Basically it would work for about 20, or so, debug runs and then BAM would error out with the <code>Sys is undefined</code> error.</p>\n<p>After reviewing a couple other posts, that got to talking about the Clean-URL logic, i remembered that i had done PageRouting setup's.</p>\n<p>Here is the resource i used to build my patterns: <a href=\"http://msdn.microsoft.com/en-us/library/cc668201.aspx\" rel=\"nofollow noreferrer\">Page Routing</a></p>\n<p>My one-liner code fixed my VS2012 Debugging problem:</p>\n<pre><code>rts.Ignore(&quot;{resource}.axd/{*pathInfo}&quot;) 'Ignores any Resource cache references, used heavily in AJAX interactions.\n</code></pre>\n" }, { "answer_id": 14865444, "author": "Mahesh", "author_id": 446154, "author_profile": "https://Stackoverflow.com/users/446154", "pm_score": 0, "selected": false, "text": "<p>Even after adding the correct entry for web config still getting this error ? most common reason for this error is JavaScript that references the Sys namespace too early.\nThen most obvious fix would be move the java script block below the ScriptManager control:</p>\n" }, { "answer_id": 16109767, "author": "RacerNerd", "author_id": 1634605, "author_profile": "https://Stackoverflow.com/users/1634605", "pm_score": 0, "selected": false, "text": "<p>I don't think this point has been added and since I just spent some time hunting this down I hope it can help.<br/><br/>\nI am working with IIS 7 and using the ASP.NET v4 Framework.<br/>\nIn my case it was <strong>important that an entry be added to both the and section of the entry in the web.config file.</strong><br/><br/>\nMy web.config file has a lot of handlers and in my case it was easiest to add the ScriptResources entry to the top of the handlers section. <strong>Most importantly, it needs to be placed before any entry that will act as a wildcard and capture the request.</strong> Adding it after a wildcard entry will cause it to be ignored and the error will still appear.<br/><br/>The module can be added to the top or bottom of the section.<br/><br/>\nWeb.config Sample:</p>\n\n<pre><code>&lt;system.webServer&gt;\n &lt;handlers&gt;\n &lt;clear /&gt;\n &lt;add name=\"ScriptResource\" preCondition=\"integratedMode\" verb=\"GET,HEAD\" path=\"ScriptResource.axd\" type=\"System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\" /&gt;\n &lt;!-- Make sure wildcard rules are below the ScriptResource tag --&gt;\n &lt;/handlers&gt;\n &lt;modules&gt;\n &lt;add name=\"ScriptModule\" type=\"System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\"/&gt;\n &lt;!-- Other modules are added here --&gt;\n &lt;/modules&gt;\n &lt;/system.webServer&gt;\n</code></pre>\n" }, { "answer_id": 16822213, "author": "David Glass", "author_id": 1521279, "author_profile": "https://Stackoverflow.com/users/1521279", "pm_score": 1, "selected": false, "text": "<p>In case none of the above works for you, and you happen to be overriding OnPreRenderComplete, make sure you call base.OnPreRenderComplete. My therapist is going to be happy to see me back</p>\n" }, { "answer_id": 17256975, "author": "goodeye", "author_id": 292060, "author_profile": "https://Stackoverflow.com/users/292060", "pm_score": 3, "selected": false, "text": "<p>Dean L's answer, <a href=\"https://stackoverflow.com/a/1718513/292060\">https://stackoverflow.com/a/1718513/292060</a> worked for me, since my call to Sys was also too early. Since I'm using jQuery, instead of moving it down, I put the script inside a document.ready call:</p>\n\n<pre><code>$(document).ready(function () {\n Sys. calls here\n});\n</code></pre>\n\n<p>This seems to be late enough that Sys is available.</p>\n" }, { "answer_id": 18301056, "author": "Farschidus", "author_id": 1379217, "author_profile": "https://Stackoverflow.com/users/1379217", "pm_score": 1, "selected": false, "text": "<p>I had the same problem after updating my AjaxControlToolkit.dll to the latest version 4.1.7.725 from 4.1.60623.0. \nI've searched and came up to this page, but none of the answers help me.\nAfter looking to the sample website of the Ajax Control Toolkit that is in the CodePlex zip file, I have realized that the <code>&lt;asp:ScriptManager&gt;</code> replaced by the new <code>&lt;ajaxtoolkit:ToolkitScriptManager&gt;</code>. I did so and there is no <em>Sys.Extended is undefined</em> any more.</p>\n" }, { "answer_id": 28965519, "author": "onlyme", "author_id": 3954673, "author_profile": "https://Stackoverflow.com/users/3954673", "pm_score": 0, "selected": false, "text": "<p>I had same probleme but i fixed it by: </p>\n\n<p>When putting a script file into a page, make sure it is </p>\n\n<pre><code>&lt;script&gt;&lt;/script&gt; and not &lt;script /&gt;.\n</code></pre>\n\n<p>I have followed this:\n<a href=\"http://forums.asp.net/t/1742435.aspx?An+element+with+id+form1+could+not+be+found+Script+error+on+page+load\" rel=\"nofollow\">http://forums.asp.net/t/1742435.aspx?An+element+with+id+form1+could+not+be+found+Script+error+on+page+load</a></p>\n\n<p>Hope this will help</p>\n" }, { "answer_id": 30093900, "author": "Jawad Siddiqui", "author_id": 1085016, "author_profile": "https://Stackoverflow.com/users/1085016", "pm_score": 0, "selected": false, "text": "<p>Add</p>\n\n<pre><code>if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded(); \n</code></pre>\n\n<p>Please check <a href=\"https://msdn.microsoft.com/en-us/library/vstudio/bb310952(v=vs.100).aspx\" rel=\"nofollow\">enter link description here</a></p>\n" }, { "answer_id": 32057625, "author": "Alexandre N.", "author_id": 1398758, "author_profile": "https://Stackoverflow.com/users/1398758", "pm_score": 3, "selected": false, "text": "<p>Try one of this solutions: </p>\n\n<p><strong>1. The browser fails to load the compressed script</strong></p>\n\n<p>This is usually the case if you get the error on IE6, but not on other browsers.</p>\n\n<p>The Script Resource Handler – ScriptResource.axd compresses the scripts before returning them to the browser. In pre-RTM releases, the handler did it all the time for all browsers, and it wasn’t configurable. There is an issue in one of the components of IE6 that prevents it from loading compressed scripts correctly. See KB article <a href=\"http://support.microsoft.com/default.aspx?scid=kb;en-us;Q312496\" rel=\"noreferrer\">here</a>. In RTM builds, we’ve made two fixes for this. One, we don’t compress if IE6 is the browser client. Two, we’ve now made compression configurable. Here’s how you can toggle the web.config.</p>\n\n<p>How do you fix it? First, make sure you are using the AJAX Extensions 1.0 RTM release. That alone should be enough. You can also try turning off compression by editing your web.config to have the following:</p>\n\n<pre><code>&lt;system.web.extensions&gt;\n&lt;scripting&gt;\n&lt;scriptResourceHandler enableCompression=\"false\" enableCaching=\"true\" /&gt;\n&lt;/scripting&gt;\n&lt;/system.web.extensions&gt;\n</code></pre>\n\n<p><strong>2. The required configuration for ScriptResourceHandler doesn’t exist for the web.config for your application</strong></p>\n\n<p>Make sure your web.config contains the entries from the default web.config file provided with the extensions install. (default location: C:\\Program Files\\Microsoft ASP.NET\\ASP.NET 2.0 AJAX Extensions\\v1.0.61025)</p>\n\n<p><strong>3. The virtual directory you are using for your web, isn’t correctly marked as an application (thus the configuration isn’t getting loaded) - This would happen for IIS webs.</strong></p>\n\n<p>Make sure that you are using a Web Application, and not just a Virtual Directory </p>\n\n<p><strong>4. ScriptResource.axd requests return 404</strong></p>\n\n<p>This usually points to a mis-configuration of ASP.NET as a whole. On a default installation of ASP.NET, any web request to a resource ending in .axd is passed from IIS to ASP.NET via an isapi mapping. Additionally the mapping is configured to not check if the file exists. If that mapping does not exist, or the check if file exists isn't disabled, then IIS will attempt to find the physical file ScriptResource.axd, won't find it, and return 404.</p>\n\n<p>You can check to see if this is the problem by coipy/pasting the full url to ScriptResource.axd from here, and seeing what it returns</p>\n\n<pre><code>&lt;script src=\"/MyWebApp/ScriptResource.axd?[snip - long query string]\" type=\"text/javascript\"&gt;&lt;/script&gt;\n</code></pre>\n\n<p>How do you fix this? If ASP.NET isn't properly installed at all, you can run the \"aspnet_regiis.exe\" command line tool to fix it up. It's located in C:\\WINDOWS\\Microsoft.Net\\Framework\\v2.0.50727. You can run \"aspnet_regiis -i -enable\", which does the full registration of ASP.NET with IIS and makes sure the ISAPI is enabled in IIS6. You can also run \"aspnet_regiis -s w3svc/1/root/MyWebApp\" to only fix up the registration for your web application.</p>\n\n<p><strong>5. Resolving the \"Sys is undefined\" error in ASP.NET AJAX RTM under IIS 7</strong></p>\n\n<p>Put this entry under <code>&lt;system.webServer/&gt;&lt;handlers/&gt;</code>:</p>\n\n<pre><code>&lt;add name=\"ScriptResource\" preCondition=\"integratedMode\" verb=\"GET,HEAD\" path=\"ScriptResource.axd\" type=\"System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\" /&gt;\n</code></pre>\n\n<p>and remove the one under <code>&lt;system.web/&gt;&lt;httpHandlers/&gt;</code>.</p>\n\n<p>References: \n<a href=\"http://weblogs.asp.net/chrisri/demystifying-sys-is-undefined\" rel=\"noreferrer\">http://weblogs.asp.net/chrisri/demystifying-sys-is-undefined</a>\n<a href=\"http://geekswithblogs.net/lorint/archive/2007/03/28/110161.aspx\" rel=\"noreferrer\">http://geekswithblogs.net/lorint/archive/2007/03/28/110161.aspx</a></p>\n" }, { "answer_id": 37473809, "author": "hsobhy", "author_id": 1030977, "author_profile": "https://Stackoverflow.com/users/1030977", "pm_score": 0, "selected": false, "text": "<p>In my case, I've found a very hidden reason ... There was this page route with in <strong>Global.ascx.cs</strong> which doesn't appear in my tests in sub-folders but returns the question error all the time .. another day with strange issues.</p>\n\n<pre><code>routes.MapPageRoute(\"siteDefault\", \"{culture}/\", \"~/default.aspx\", false, new RouteValueDictionary(new { culture = \"(\\\\w{2})|(\\\\w{2}-\\\\w{2})\" }));\n</code></pre>\n" }, { "answer_id": 39619160, "author": "Fernando Meneses Gomes", "author_id": 1291937, "author_profile": "https://Stackoverflow.com/users/1291937", "pm_score": 1, "selected": false, "text": "<p>In my case the problem was that I had putted the following code to keep the gridview tableheader after partial postback:</p>\n\n<pre><code> protected override void OnPreRenderComplete(EventArgs e)\n {\n if (grv.Rows.Count &gt; 0)\n {\n grv.HeaderRow.TableSection = TableRowSection.TableHeader;\n }\n }\n</code></pre>\n\n<p>Removing this code stopped the issue.</p>\n" }, { "answer_id": 46821137, "author": "Hawkeye", "author_id": 4036454, "author_profile": "https://Stackoverflow.com/users/4036454", "pm_score": 3, "selected": false, "text": "<p>I hate adding to such a huge topic and so much later, but I've think I have a solution that works in VS2015 at the very least.</p>\n<p>I was on a hunt to find a reason for the sys error, and the only solution that worked for me was to add <code>EnableCdn=&quot;true&quot;</code> in a <code>ScriptManager</code> like this:</p>\n<pre><code>&lt;asp:ScriptManager ID=&quot;ScriptManager1&quot; runat=&quot;server&quot; EnableCdn=&quot;true&quot; /&gt;\n</code></pre>\n<p>See the <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.web.ui.scriptmanager.enablecdn?view=netframework-4.8\" rel=\"nofollow noreferrer\">MSDN</a> for more information.</p>\n<p><strong>Why do we need to do this?</strong></p>\n<p>When working on a asp.net web application, you have to enable CDN so that Microsoft can download the <code>Sys.</code> library.</p>\n<p>There was probably a script in your page that was using the <code>Sys</code> function. Setting <code>EnableCdn=&quot;true&quot;</code> would ensure that the <code>Sys</code> library is downloaded before it is used.</p>\n<p><strong>What's CDN?</strong></p>\n<p>It stands for &quot;Content Delivery Network&quot; and enabling it allows certain resources to download with simple references.</p>\n<p>A quote from <a href=\"https://www.sitepoint.com/7-reasons-to-use-a-cdn/\" rel=\"nofollow noreferrer\">https://www.sitepoint.com/7-reasons-to-use-a-cdn/</a></p>\n<blockquote>\n<p>Most CDNs are used to host static resources such as images, videos,\naudio clips, CSS files and JavaScript. You’ll find common JavaScript\nlibraries, HTML5 shims, CSS resets, fonts and other assets available\non a variety of public and private CDN systems.</p>\n</blockquote>\n<p>Both Google and Microsoft have CDNs. All you have to do is add a reference. Usually CDNs are added via a script resource:</p>\n<pre><code>&lt;script src=&quot;https://ajax.aspnetcdn.com/ajax/4.5.1/1/MicrosoftAjax.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;\n</code></pre>\n<p>Once you set <code>EnableCdn=&quot;true&quot;</code> and Microsoft will add it's little CDN reference (like the one above) in the page which downloads the <code>Sys</code> library.</p>\n<p>I hope that helps anybody that ran into the same issue.</p>\n" }, { "answer_id": 64142737, "author": "Bm Z", "author_id": 1542087, "author_profile": "https://Stackoverflow.com/users/1542087", "pm_score": 0, "selected": false, "text": "<p>I know this is an old thread but I found a somewhat unique solution. In my case I was getting the error because I am using both Webforms and MVC in the same ASP.NET web application. After mapping routes the issue showed up. I fixed it by adding the following code to ignore routes for both &quot;{resource}.aspx/{*pathInfo}&quot; and &quot;{resource}.axd/{*pathInfo}&quot;</p>\n<pre><code> private void RegisterRoutes(RouteCollection routes)\n {\n routes.IgnoreRoute(&quot;{resource}.aspx/{*pathInfo}&quot;);\n routes.IgnoreRoute(&quot;{resource}.axd/{*pathInfo}&quot;);\n\n routes.MapRoute(\n &quot;Default&quot;, \n &quot;{controller}/{action}/{id}&quot;, \n new { controller = &quot;Test&quot;, action = &quot;Index&quot;, id = UrlParameter.Optional }\n );\n }\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/75322", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have an ASP.Net/AJAX control kit project that i am working on. 80% of the time there is no problem. The page runs as it should. If you refresh the page it will sometimes show a javascript error "Sys is undefined". It doesn't happen all the time, but it is reproducible. When it happens, the user has to shut down their browser and reopen the page. This leads me to believe that it could be an IIS setting. Another note. I looked at the page source both when I get the error, and when not. When the page throws errors the following code is missing: ``` <script src="/ScriptResource.axd?d=EAvfjPfYejDh0Z2Zq5zTR_TXqL0DgVcj_h1wz8cst6uXazNiprV1LnAGq3uL8N2vRbpXu46VsAMFGSgpfovx9_cO8tpy2so6Qm_0HXVGg_Y1&amp;t=baeb8cc" type="text/javascript"></script> <script type="text/javascript"> //<![CDATA[ if (typeof(Sys) === 'undefined') throw new Error('ASP.NET Ajax client-side framework failed to load.'); //]]> </script> ```
I fixed my problem by moving the `<script type="text/javascript"></script>` block containing the Sys.\* calls lower down (to the last item before the close of the body's `<asp:Content/>` section) in the HTML on the page. I originally had my the script block in the HEAD `<asp:Content/>` section of my page. I was working inside a page that had a MasterPageFile. Hope this helps someone out.
75,361
<p>I have a column containing the strings 'Operator (1)' and so on until 'Operator (600)' so far.</p> <p>I want to get them numerically ordered and I've come up with</p> <pre><code>select colname from table order by cast(replace(replace(colname,'Operator (',''),')','') as int) </code></pre> <p>which is very very ugly.</p> <p>Better suggestions?</p>
[ { "answer_id": 75398, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 3, "selected": true, "text": "<p>It's that, InStr()/SubString(), changing Operator(1) to Operator(001), storing the n in Operator(n) separately, or creating a computed column that hides the ugly string manipulation. What you have seems fine.</p>\n" }, { "answer_id": 75474, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>My answer would be to change the problem. I would add an operatorNumber field to the table if that is possible. Change the update/insert routines to extract the number and store it. That way the string conversion hit is only once per record.</p>\n\n<p>The ordering logic would require the string conversion every time the query is run.</p>\n" }, { "answer_id": 76471, "author": "Ricardo C", "author_id": 232589, "author_profile": "https://Stackoverflow.com/users/232589", "pm_score": 0, "selected": false, "text": "<p>Well, first define the meaning of that column. Is operator a name so you can justify using chars? Or is it a number? </p>\n\n<p>If the field is a name then you will use chars, and then you would want to determine the fixed length. Pad all operator names with zeros on the left. Define naming rules for operators (I.E. No leters. Or the codes you would use in a series like \"A001\")</p>\n\n<p>An index will sort the physical data in the server. And a properly define text naming will sort them on a query. You would want both.</p>\n\n<p>If the operator is a number, then you got the data type for that column wrong and needs to be changed.</p>\n" }, { "answer_id": 76618, "author": "Cruachan", "author_id": 7315, "author_profile": "https://Stackoverflow.com/users/7315", "pm_score": 1, "selected": false, "text": "<p>If you really <em>have</em> to leave the data in the format you have - and adding a numeric sort order column is the better solution - then consider wrapping the text manipulation up in a user defined function. </p>\n\n<p>select colname from table order by dbo.udfSortOperator(colname)</p>\n\n<p>It's less ugly and gives you some abstraction. There's an additional overhead of the function call but on a table containing low thousands of rows in a not-too-heavily hit database server it's not a major concern. Make notes in the function to optomise later as required.</p>\n" }, { "answer_id": 150106, "author": "Constantin", "author_id": 20310, "author_profile": "https://Stackoverflow.com/users/20310", "pm_score": 0, "selected": false, "text": "<p><strong>Indexed computed column</strong></p>\n\n<p>If you find yourself ordering on or otherwise querying <code>operator</code> column often, consider creating a computed column for its numeric value and adding an index for it. This will give you a computed/persistent column (which sounds like oxymoron, but isn't).</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/75361", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5190/" ]
I have a column containing the strings 'Operator (1)' and so on until 'Operator (600)' so far. I want to get them numerically ordered and I've come up with ``` select colname from table order by cast(replace(replace(colname,'Operator (',''),')','') as int) ``` which is very very ugly. Better suggestions?
It's that, InStr()/SubString(), changing Operator(1) to Operator(001), storing the n in Operator(n) separately, or creating a computed column that hides the ugly string manipulation. What you have seems fine.
75,379
<p>The problem is simple, but I'm struggling a bit already.</p> <pre><code>Server server = new Server(8080); Context context = new Context(server, "/", Context.NO_SESSIONS); context.addServlet(MainPageView.class, "/"); context.addServlet(UserView.class, "/signup"); server.start(); </code></pre> <p>That's a pretty standard piece of code that you can find anywhere in Jetty world. I have an application that embeds Jetty as a servlet engine and has some servlets. </p> <p>Instantiation of some of these servlets requires heavy work on startup. Say &ndash; reading additional config files, connecting to the database, etc. How can I make the servlet engine instantiate all servlets eagerly, so that I can do all the hard work upfront and not on the first user request?</p>
[ { "answer_id": 75424, "author": "Justin Rudd", "author_id": 12968, "author_profile": "https://Stackoverflow.com/users/12968", "pm_score": 0, "selected": false, "text": "<p>Use the <code>Context.addServlet</code> overload that takes a <code>ServletHolder</code>. <code>ServletHolder</code> is a class that accepts either a Class or a Servlet instance.</p>\n\n<pre><code>Servlet myServlet = new MyServlet();\nServletHolder holder = new ServletHolder(myServlet);\ncontext.addServlet(holder, \"/\");\n</code></pre>\n\n<p>This assumes Jetty 6. I think it will work for Jetty 7 as well.</p>\n" }, { "answer_id": 75760, "author": "delux247", "author_id": 5569, "author_profile": "https://Stackoverflow.com/users/5569", "pm_score": 3, "selected": true, "text": "<p>I'm not sure why using Guice make's Justin's option not work for you. What exactly is getting injected in? I'm not sure if this would help you at all because it is very similar to what Justin wrote above but if you do it this way, Jetty will do the actually instantiating.</p>\n\n<pre><code>Context context = new Context(server, \"/\", Context.NO_SESSIONS);\nServletHolder mainPageViewHolder = new ServletHolder(MainPageView.class);\n// Do this to force Jetty to instantiate the servlet\nmainPageViewHolder.getServlet(); \ncontext.addServlet(mainPageViewHolder, \"/\");\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/75379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3105/" ]
The problem is simple, but I'm struggling a bit already. ``` Server server = new Server(8080); Context context = new Context(server, "/", Context.NO_SESSIONS); context.addServlet(MainPageView.class, "/"); context.addServlet(UserView.class, "/signup"); server.start(); ``` That's a pretty standard piece of code that you can find anywhere in Jetty world. I have an application that embeds Jetty as a servlet engine and has some servlets. Instantiation of some of these servlets requires heavy work on startup. Say – reading additional config files, connecting to the database, etc. How can I make the servlet engine instantiate all servlets eagerly, so that I can do all the hard work upfront and not on the first user request?
I'm not sure why using Guice make's Justin's option not work for you. What exactly is getting injected in? I'm not sure if this would help you at all because it is very similar to what Justin wrote above but if you do it this way, Jetty will do the actually instantiating. ``` Context context = new Context(server, "/", Context.NO_SESSIONS); ServletHolder mainPageViewHolder = new ServletHolder(MainPageView.class); // Do this to force Jetty to instantiate the servlet mainPageViewHolder.getServlet(); context.addServlet(mainPageViewHolder, "/"); ```
75,385
<p>The Visual Studio compiler does not seem to warn on signed/unsigned assignments, only on comparisons. For example the code below will generate a warning on the if statement but not the initial assignments.</p> <p>Is there anyway to make it catch these? I'm already at W4 but thought (hoped) there may be another setting somewhere.</p> <p>Thanks,</p> <pre><code>int foo(void) { unsigned int fooUnsigned = 0xffffffff; int fooSigned = fooUnsigned; // no warning if (fooSigned &lt; fooUnsigned) // warning { return 0; } return fooSigned; } </code></pre> <p>Update:</p> <p>Quamrana is right, this is controlled by warning 4365 which appears to be off by default, even at W4. However you can explicitly enable it for a given warning level like so;</p> <pre><code>#pragma warning (4 : 4365) </code></pre> <p>Which results in;</p> <pre><code>warning C4365: 'initializing' : conversion from 'unsigned int' to 'int', signed/unsigned mismatch </code></pre>
[ { "answer_id": 75596, "author": "quamrana", "author_id": 4834, "author_profile": "https://Stackoverflow.com/users/4834", "pm_score": 4, "selected": true, "text": "<p>You need to enable warning 4365 to catch the assignment.</p>\n\n<p>That might be tricky - you need to enable ALL warnings - use /Wall which enables lots of warnings, so you may have some trouble seeing the warning occur, but it does.</p>\n" }, { "answer_id": 75711, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 0, "selected": false, "text": "<p>@quamrana:</p>\n\n<p>There must be something beyond the /Wall option to enable warning 4365:</p>\n\n<pre><code>C:\\Temp&gt;cl /Wall /c foo.c\nMicrosoft (R) 32-bit C/C++ Optimizing Compiler Version 15.00.21022.08 for 80x86\nCopyright (C) Microsoft Corporation. All rights reserved.\n\nfoo.c\nfoo.c(6) : warning C4018: '&lt;' : signed/unsigned mismatch\n</code></pre>\n\n<p>I see that Andrew got it to work, but does anyone have an idea why it's not working here?</p>\n\n<p>The Visual Studio docs indicate that it should, but I can't even get the example program in the docs to give the C4365 warning (though it does give the related C4245 warning - but that occurs with just a /W4 option anyway).</p>\n" }, { "answer_id": 4883323, "author": "ottibus", "author_id": 601104, "author_profile": "https://Stackoverflow.com/users/601104", "pm_score": 2, "selected": false, "text": "<p>You can change the level of any specific warning by using /W[level][code]. So in this case /W34365 will make warning 4365 into a level 3 warning. If you do this a lot you might find it useful to put these options in a text file and use the @[file] option to simplify the command line.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/75385", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1043/" ]
The Visual Studio compiler does not seem to warn on signed/unsigned assignments, only on comparisons. For example the code below will generate a warning on the if statement but not the initial assignments. Is there anyway to make it catch these? I'm already at W4 but thought (hoped) there may be another setting somewhere. Thanks, ``` int foo(void) { unsigned int fooUnsigned = 0xffffffff; int fooSigned = fooUnsigned; // no warning if (fooSigned < fooUnsigned) // warning { return 0; } return fooSigned; } ``` Update: Quamrana is right, this is controlled by warning 4365 which appears to be off by default, even at W4. However you can explicitly enable it for a given warning level like so; ``` #pragma warning (4 : 4365) ``` Which results in; ``` warning C4365: 'initializing' : conversion from 'unsigned int' to 'int', signed/unsigned mismatch ```
You need to enable warning 4365 to catch the assignment. That might be tricky - you need to enable ALL warnings - use /Wall which enables lots of warnings, so you may have some trouble seeing the warning occur, but it does.
75,401
<p>User <a href="https://stackoverflow.com/users/1065/kokos">kokos</a> answered the wonderful <em><a href="https://stackoverflow.com/questions/9033/hidden-features-of-c">Hidden Features of C#</a></em> question by mentioning the <code>using</code> keyword. Can you elaborate on that? What are the uses of <code>using</code>?</p>
[ { "answer_id": 75419, "author": "Joseph Daigle", "author_id": 507, "author_profile": "https://Stackoverflow.com/users/507", "pm_score": 2, "selected": false, "text": "<p>When using ADO.NET you can use the keywork for things like your connection object or reader object. That way when the code block completes it will automatically dispose of your connection.</p>\n" }, { "answer_id": 75426, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 7, "selected": false, "text": "<p>Things like this:</p>\n\n<pre><code>using (var conn = new SqlConnection(\"connection string\"))\n{\n conn.Open();\n\n // Execute SQL statement here on the connection you created\n}\n</code></pre>\n\n<p>This <code>SqlConnection</code> will be closed without needing to explicitly call the <code>.Close()</code> function, and this will happen <em>even if an exception is thrown</em>, without the need for a <code>try</code>/<code>catch</code>/<code>finally</code>.</p>\n" }, { "answer_id": 75435, "author": "Gilligan", "author_id": 12356, "author_profile": "https://Stackoverflow.com/users/12356", "pm_score": 0, "selected": false, "text": "<p>The <a href=\"http://web.archive.org/web/20080809044303/http://www.ayende.com:80/Wiki/Rhino%20Mocks%20Record-playback%20Syntax.ashx\" rel=\"nofollow noreferrer\">Rhino Mocks Record-playback Syntax</a> makes an interesting use of <code>using</code>.</p>\n" }, { "answer_id": 75443, "author": "Grank", "author_id": 12975, "author_profile": "https://Stackoverflow.com/users/12975", "pm_score": 1, "selected": false, "text": "<p>When you use <em>using</em>, it will call the Dispose() method on the object at the end of the using's scope. So you can have quite a bit of great cleanup code in your Dispose() method.</p>\n<p>A bullet point:</p>\n<p>If you implement IDisposable, make sure you call GC.SuppressFinalize() in your Dispose() implementation, as otherwise automatic garbage collection will try to come along and Finalize it at some point, which at the least would be a waste of resources if you've already Dispose()d of it.</p>\n" }, { "answer_id": 75444, "author": "MagicKat", "author_id": 8505, "author_profile": "https://Stackoverflow.com/users/8505", "pm_score": 5, "selected": false, "text": "<p><em>using</em> can be used to call IDisposable. It can also be used to alias types.</p>\n<pre><code>using (SqlConnection cnn = new SqlConnection()) { /* Code */}\nusing f1 = System.Windows.Forms.Form;\n</code></pre>\n" }, { "answer_id": 75451, "author": "David Arno", "author_id": 7122, "author_profile": "https://Stackoverflow.com/users/7122", "pm_score": 2, "selected": false, "text": "<p>&quot;using&quot; can also be used to resolve namespace conflicts.</p>\n<p>See <em><a href=\"http://www.davidarno.org/c-howtos/aliases-overcoming-name-conflicts/\" rel=\"nofollow noreferrer\">http://www.davidarno.org/c-howtos/aliases-overcoming-name-conflicts/</a></em> for a short tutorial I wrote on the subject.</p>\n" }, { "answer_id": 75461, "author": "David Basarab", "author_id": 2469, "author_profile": "https://Stackoverflow.com/users/2469", "pm_score": 1, "selected": false, "text": "<p>The <em>using</em> keyword defines the scope for the object and then disposes of the object when the scope is complete. For example.</p>\n<pre><code>using (Font font2 = new Font(&quot;Arial&quot;, 10.0f))\n{\n // Use font2\n}\n</code></pre>\n<p>See <a href=\"http://msdn.microsoft.com/en-us/library/yh598w02(VS.80).aspx\" rel=\"nofollow noreferrer\">here</a> for the MSDN article on the C# <em>using</em> keyword.</p>\n" }, { "answer_id": 75480, "author": "Bob Wintemberg", "author_id": 12999, "author_profile": "https://Stackoverflow.com/users/12999", "pm_score": 2, "selected": false, "text": "<p><strong>using</strong> is used when you have a resource that you want disposed after it's been used.</p>\n<p>For instance if you allocate a File resource and only need to use it in one section of code for a little reading or writing, using is helpful for disposing of the File resource as soon as your done.</p>\n<p>The resource being used needs to implement IDisposable to work properly.</p>\n<p>Example:</p>\n<pre><code>using (File file = new File (parameters))\n{\n // Code to do stuff with the file\n}\n</code></pre>\n" }, { "answer_id": 75483, "author": "paulwhit", "author_id": 7301, "author_profile": "https://Stackoverflow.com/users/7301", "pm_score": 10, "selected": true, "text": "<p>The reason for the <code>using</code> statement is to ensure that the object is disposed as soon as it goes out of scope, and it doesn't require explicit code to ensure that this happens.</p>\n\n<p>As in <em><a href=\"https://www.codeproject.com/Articles/6564/Understanding-the-using-statement-in-C\" rel=\"noreferrer\">Understanding the 'using' statement in C# (codeproject)</a></em> and <em><a href=\"https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/using-objects\" rel=\"noreferrer\">Using objects that implement IDisposable (microsoft)</a></em>, the C# compiler converts</p>\n\n<pre><code>using (MyResource myRes = new MyResource())\n{\n myRes.DoSomething();\n}\n</code></pre>\n\n<p>to</p>\n\n<pre><code>{ // Limits scope of myRes\n MyResource myRes= new MyResource();\n try\n {\n myRes.DoSomething();\n }\n finally\n {\n // Check for a null resource.\n if (myRes != null)\n // Call the object's Dispose method.\n ((IDisposable)myRes).Dispose();\n }\n}\n</code></pre>\n\n<p>C# 8 introduces a new syntax, named \"<a href=\"https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#using-declarations\" rel=\"noreferrer\">using declarations</a>\":</p>\n\n<blockquote>\n <p>A using declaration is a variable declaration preceded by the using keyword. It tells the compiler that the variable being declared should be disposed at the end of the enclosing scope.</p>\n</blockquote>\n\n<p>So the equivalent code of above would be:</p>\n\n<pre><code>using var myRes = new MyResource();\nmyRes.DoSomething();\n</code></pre>\n\n<p>And when control leaves the containing scope (usually a method, but it can also be a code block), <code>myRes</code> will be disposed.</p>\n" }, { "answer_id": 75497, "author": "Joel Martinez", "author_id": 5416, "author_profile": "https://Stackoverflow.com/users/5416", "pm_score": 2, "selected": false, "text": "<p>Interestingly, you can also use the using/IDisposable pattern for other interesting things (such as the other point of the way that Rhino Mocks uses it). Basically, you can take advantage of the fact that the compiler will <strong>always</strong> call .Dispose on the \"used\" object. If you have something that needs to happen after a certain operation ... something that has a definite start and end ... then you can simply make an IDisposable class that starts the operation in the constructor, and then finishes in the Dispose method.</p>\n\n<p>This allows you to use the really nice using syntax to denote the explicit start and end of said operation. This is also how the System.Transactions stuff works.</p>\n" }, { "answer_id": 75516, "author": "Sam Schutte", "author_id": 146, "author_profile": "https://Stackoverflow.com/users/146", "pm_score": 3, "selected": false, "text": "<p>I've used it a lot in the past to work with input and output streams. You can nest them nicely and it takes away a lot of the potential problems you usually run into (by automatically calling dispose). For example:</p>\n\n<pre><code> using (FileStream fs = new FileStream(\"c:\\file.txt\", FileMode.Open))\n {\n using (BufferedStream bs = new BufferedStream(fs))\n {\n using (System.IO.StreamReader sr = new StreamReader(bs))\n {\n string output = sr.ReadToEnd();\n }\n }\n }\n</code></pre>\n" }, { "answer_id": 75640, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Not that it is ultra important, but <em>using</em> can also be used to change resources on the fly.</p>\n<p>Yes, disposable as mentioned earlier, but perhaps specifically you don't want the resources they mismatch with other resources during the rest of your execution. So you want to dispose of it so it doesn't interfere elsewhere.</p>\n" }, { "answer_id": 75867, "author": "BlackTigerX", "author_id": 8411, "author_profile": "https://Stackoverflow.com/users/8411", "pm_score": 7, "selected": false, "text": "<p>Since a lot of people still do:</p>\n\n<pre><code>using (System.IO.StreamReader r = new System.IO.StreamReader(\"\"))\nusing (System.IO.StreamReader r2 = new System.IO.StreamReader(\"\")) {\n //code\n}\n</code></pre>\n\n<p>I guess a lot of people still don't know that you can do:</p>\n\n<pre><code>using (System.IO.StreamReader r = new System.IO.StreamReader(\"\"), r2 = new System.IO.StreamReader(\"\")) {\n //code\n}\n</code></pre>\n" }, { "answer_id": 76192, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 2, "selected": false, "text": "<p>In conclusion, when you use a local variable of a type that implements <code>IDisposable</code>, <em>always</em>, without exception, use <code>using</code><sup>1</sup>.</p>\n\n<p>If you use nonlocal <code>IDisposable</code> variables, then <em>always</em> implement the <a href=\"http://www.codeproject.com/KB/cs/idisposable.aspx\" rel=\"noreferrer\"><code>IDisposable</code> pattern</a>.</p>\n\n<p>Two simple rules, no exception<sup>1</sup>. Preventing resource leaks otherwise is a real pain in the *ss.</p>\n\n<hr>\n\n<p><sup>1)</sup>: The only exception is – when you're handling exceptions. It might then be less code to call <code>Dispose</code> explicitly in the <code>finally</code> block.</p>\n" }, { "answer_id": 76232, "author": "Brendan Kendrick", "author_id": 13473, "author_profile": "https://Stackoverflow.com/users/13473", "pm_score": 1, "selected": false, "text": "<p>Another example of a reasonable use in which the object is immediately disposed:</p>\n\n<pre><code>using (IDataReader myReader = DataFunctions.ExecuteReader(CommandType.Text, sql.ToString(), dp.Parameters, myConnectionString)) \n{\n while (myReader.Read()) \n {\n MyObject theObject = new MyObject();\n theObject.PublicProperty = myReader.GetString(0);\n myCollection.Add(theObject);\n }\n}\n</code></pre>\n" }, { "answer_id": 76278, "author": "Lucas", "author_id": 5966, "author_profile": "https://Stackoverflow.com/users/5966", "pm_score": 3, "selected": false, "text": "<p>Another great use of <em>using</em> is when instantiating a modal dialog.</p>\n<pre class=\"lang-vbnet prettyprint-override\"><code>Using frm as new Form1\n\n Form1.ShowDialog\n\n ' Do stuff here\n\nEnd Using\n</code></pre>\n" }, { "answer_id": 204957, "author": "Amanda Mitchell", "author_id": 26628, "author_profile": "https://Stackoverflow.com/users/26628", "pm_score": 4, "selected": false, "text": "<p><em>using</em>, in the sense of</p>\n<pre><code>using (var foo = new Bar())\n{\n Baz();\n}\n</code></pre>\n<p>Is actually shorthand for a try/finally block. It is equivalent to the code:</p>\n<pre><code>var foo = new Bar();\ntry\n{\n Baz();\n}\nfinally\n{\n foo.Dispose();\n}\n</code></pre>\n<p>You'll note, of course, that the first snippet is much more concise than the second and also that there are many kinds of things that you might want to do as cleanup even if an exception is thrown. Because of this, we've come up with a class that we call <em>Scope</em> that allows you to execute arbitrary code in the Dispose method. So, for example, if you had a property called IsWorking that you always wanted to set to false after trying to perform an operation, you'd do it like this:</p>\n<pre><code>using (new Scope(() =&gt; IsWorking = false))\n{\n IsWorking = true;\n MundaneYetDangerousWork();\n}\n</code></pre>\n<p>You can read more about our solution and how we derived it <a href=\"https://faithlife.codes/blog/2008/08/leverage_using_blocks_with_scope/\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 204987, "author": "milot", "author_id": 22637, "author_profile": "https://Stackoverflow.com/users/22637", "pm_score": 1, "selected": false, "text": "<p>Everything outside the curly brackets is disposed, so it is great to dispose your objects if you are not using them. This is so because if you have a SqlDataAdapter object and you are using it only once in the application life cycle and you are filling just one dataset and you don't need it anymore, you can use the code:</p>\n\n<pre><code>using(SqlDataAdapter adapter_object = new SqlDataAdapter(sql_command_parameter))\n{\n // do stuff\n} // here adapter_object is disposed automatically\n</code></pre>\n" }, { "answer_id": 13175552, "author": "Shiraj Momin", "author_id": 1787655, "author_profile": "https://Stackoverflow.com/users/1787655", "pm_score": 2, "selected": false, "text": "<pre><code>public class ClassA:IDisposable\n{\n #region IDisposable Members\n public void Dispose()\n {\n GC.SuppressFinalize(this);\n }\n #endregion\n}\n</code></pre>\n<hr />\n<pre><code>public void fn_Data()\n{\n using (ClassA ObjectName = new ClassA())\n {\n // Use objectName\n }\n}\n</code></pre>\n" }, { "answer_id": 20271484, "author": "Riya Patil", "author_id": 2191381, "author_profile": "https://Stackoverflow.com/users/2191381", "pm_score": -1, "selected": false, "text": "<p>The <em>using</em> clause is used to define the scope for the particular variable.</p>\n<p>For example:</p>\n<pre><code>Using(SqlConnection conn = new SqlConnection(ConnectionString)\n{\n Conn.Open()\n\n // Execute SQL statements here.\n // You do not have to close the connection explicitly\n // here as &quot;USING&quot; will close the connection once the\n // object Conn goes out of the defined scope.\n}\n</code></pre>\n" }, { "answer_id": 22994945, "author": "VictorySaber", "author_id": 2878135, "author_profile": "https://Stackoverflow.com/users/2878135", "pm_score": 3, "selected": false, "text": "<p>You can make use of the alias namespace by way of the following example:</p>\n\n<pre><code>using LegacyEntities = CompanyFoo.CoreLib.x86.VBComponents.CompanyObjects;\n</code></pre>\n\n<p>This is called a <em>using alias directive</em> as as you can see, it can be used to hide long-winded references should you want to make it obvious in your code what you are referring to\ne.g.</p>\n\n<pre><code>LegacyEntities.Account\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>CompanyFoo.CoreLib.x86.VBComponents.CompanyObjects.Account\n</code></pre>\n\n<p>or simply</p>\n\n<pre><code>Account // It is not obvious this is a legacy entity\n</code></pre>\n" }, { "answer_id": 29407147, "author": "snowell", "author_id": 3720990, "author_profile": "https://Stackoverflow.com/users/3720990", "pm_score": 1, "selected": false, "text": "<p>The <em>using</em> statement provides a convenience mechanism to correctly use IDisposable objects. As a rule, when you use an IDisposable object, you should declare and instantiate it in a using statement.</p>\n<p>The <em>using</em> statement calls the Dispose method on the object in the correct way, and (when you use it as shown earlier) it also causes the object itself to go out of scope as soon as Dispose is called. Within the <em>using</em> block, the object is read-only and cannot be modified or reassigned.</p>\n<p>This comes from <a href=\"https://social.msdn.microsoft.com/Search/en-US?query=using&amp;emptyWatermark=true&amp;ac=4\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 29897282, "author": "Seb", "author_id": 4693156, "author_profile": "https://Stackoverflow.com/users/4693156", "pm_score": 1, "selected": false, "text": "<p>For me the name \"using\" is a little bit confusing, because is can be a directive to import a Namespace or a statement (like the one discussed here) for error handling.</p>\n\n<p>A different name for error handling would've been nice, and maybe a somehow more obvious one.</p>\n" }, { "answer_id": 29897576, "author": "Pluc", "author_id": 1338607, "author_profile": "https://Stackoverflow.com/users/1338607", "pm_score": 3, "selected": false, "text": "<p>Just adding a little something that I was surprised did not come up. The most interesting feature of <em>using</em> (in my opinion) is that no matter how you exit the <em>using</em> block, it will always dispose the object. This includes returns and exceptions.</p>\n<pre><code>using (var db = new DbContext())\n{\n if(db.State == State.Closed)\n throw new Exception(&quot;Database connection is closed.&quot;);\n return db.Something.ToList();\n}\n</code></pre>\n<p>It doesn't matter if the exception is thrown or the list is returned. The DbContext object will always be disposed.</p>\n" }, { "answer_id": 34465332, "author": "Aureliano Buendia", "author_id": 738587, "author_profile": "https://Stackoverflow.com/users/738587", "pm_score": 4, "selected": false, "text": "<p>Microsoft documentation states that <strong>using</strong> has a double function (<a href=\"https://msdn.microsoft.com/en-us/library/zhdeatwt.aspx\" rel=\"noreferrer\">https://msdn.microsoft.com/en-us/library/zhdeatwt.aspx</a>), both as a <em>directive</em> and in <em>statements</em>. As a <em>statement</em>, as it was pointed out here in other answers, the keyword is basically syntactic sugar to determine a scope to dispose an <strong>IDisposable</strong> object. As a <em>directive</em>, it is routinely used to import namespaces and types. Also as a directive, you can create <em>aliases</em> for namespaces and types, as pointed out in the book \"C# 5.0 In a Nutshell: The Definitive Guide\" (<a href=\"https://rads.stackoverflow.com/amzn/click/com/B008E6I1K8\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">http://www.amazon.com/5-0-Nutshell-The-Definitive-Reference-ebook/dp/B008E6I1K8</a>), by Joseph and Ben Albahari. One example:</p>\n\n<pre><code>namespace HelloWorld\n{\n using AppFunc = Func&lt;IDictionary&lt;DateTime, string&gt;, List&lt;string&gt;&gt;;\n public class Startup\n {\n public static AppFunc OrderEvents() \n {\n AppFunc appFunc = (IDictionary&lt;DateTime, string&gt; events) =&gt;\n {\n if ((events != null) &amp;&amp; (events.Count &gt; 0))\n {\n List&lt;string&gt; result = events.OrderBy(ev =&gt; ev.Key)\n .Select(ev =&gt; ev.Value)\n .ToList();\n return result;\n }\n throw new ArgumentException(\"Event dictionary is null or empty.\");\n };\n return appFunc;\n }\n }\n}\n</code></pre>\n\n<p>This is something to adopt wisely, since the abuse of this practice can hurt the clarity of one's code. There is a nice explanation on C# aliases, also mentioning pros and cons, in DotNetPearls (<a href=\"http://www.dotnetperls.com/using-alias\" rel=\"noreferrer\">http://www.dotnetperls.com/using-alias</a>).</p>\n" }, { "answer_id": 41463137, "author": "Siamand", "author_id": 2276651, "author_profile": "https://Stackoverflow.com/users/2276651", "pm_score": 1, "selected": false, "text": "<p>It also can be used for creating scopes for Example:</p>\n\n<pre><code>class LoggerScope:IDisposable {\n static ThreadLocal&lt;LoggerScope&gt; threadScope = \n new ThreadLocal&lt;LoggerScope&gt;();\n private LoggerScope previous;\n\n public static LoggerScope Current=&gt; threadScope.Value;\n\n public bool WithTime{get;}\n\n public LoggerScope(bool withTime){\n previous = threadScope.Value;\n threadScope.Value = this;\n WithTime=withTime;\n }\n\n public void Dispose(){\n threadScope.Value = previous;\n }\n}\n\n\nclass Program {\n public static void Main(params string[] args){\n new Program().Run();\n }\n\n public void Run(){\n log(\"something happend!\");\n using(new LoggerScope(false)){\n log(\"the quick brown fox jumps over the lazy dog!\");\n using(new LoggerScope(true)){\n log(\"nested scope!\");\n }\n }\n }\n\n void log(string message){\n if(LoggerScope.Current!=null){\n Console.WriteLine(message);\n if(LoggerScope.Current.WithTime){\n Console.WriteLine(DateTime.Now);\n }\n }\n }\n\n}\n</code></pre>\n" }, { "answer_id": 49166602, "author": "deepak samantaray", "author_id": 4661703, "author_profile": "https://Stackoverflow.com/users/4661703", "pm_score": 1, "selected": false, "text": "<p>The <em>using</em> statement tells .NET to release the object specified in the <em>using</em> block once it is no longer needed.</p>\n<p>So you should use the 'using' block for classes that require cleaning up after them, like <em>System.IO</em> types.</p>\n" }, { "answer_id": 50293207, "author": "Vazgen Torosyan", "author_id": 3541666, "author_profile": "https://Stackoverflow.com/users/3541666", "pm_score": 0, "selected": false, "text": "<blockquote>\n<p>using as a statement automatically calls the dispose on the specified\nobject. The object must implement the IDisposable interface. It is\npossible to use several objects in one statement as long as they are\nof the same type.</p>\n</blockquote>\n<p>The <a href=\"https://en.wikipedia.org/wiki/Common_Language_Runtime\" rel=\"nofollow noreferrer\">CLR</a> converts your code into <a href=\"https://en.wikipedia.org/wiki/Common_Intermediate_Language\" rel=\"nofollow noreferrer\">CIL</a>. And the <em>using</em> statement gets translated into a try and finally block. This is how the <em>using</em> statement is represented in CIL. A <em>using</em> statement is translated into three parts: acquisition, usage, and disposal. The resource is first acquired, then the usage is enclosed in a <em>try</em> statement with a <em>finally</em> clause. The object then gets disposed in the <em>finally</em> clause.</p>\n" }, { "answer_id": 51590168, "author": "Chamila Maddumage", "author_id": 8194089, "author_profile": "https://Stackoverflow.com/users/8194089", "pm_score": 2, "selected": false, "text": "<p>There are two usages of the <code>using</code> keyword in C# as follows.</p>\n<ol>\n<li><p>As a directive</p>\n<p>Generally we use the <code>using</code> keyword to add namespaces in code-behind and class files. Then it makes available all the classes, interfaces and abstract classes and their methods and properties in the current page.</p>\n<p>Example:</p>\n<pre><code>using System.IO;\n</code></pre>\n</li>\n<li><p>As a statement</p>\n<p>This is another way to use the <code>using</code> keyword in C#. It plays a vital role in improving performance in garbage collection.</p>\n<p>The <code>using</code> statement ensures that Dispose() is called even if an exception occurs when you are creating objects and calling methods, properties and so on. Dispose() is a method that is present in the IDisposable interface that helps to implement custom garbage collection. In other words if I am doing some database operation (Insert, Update, Delete) but somehow an exception occurs then here the using statement closes the connection automatically. No need to call the connection Close() method explicitly.</p>\n<p>Another important factor is that it helps in Connection Pooling. Connection Pooling in .NET helps to eliminate the closing of a database connection multiple times. It sends the connection object to a pool for future use (next database call). The next time a database connection is called from your application the connection pool fetches the objects available in the pool. So it helps to improve the performance of the application. So when we use the using statement the controller sends the object to the connection pool automatically, there is no need to call the Close() and Dispose() methods explicitly.</p>\n<p>You can do the same as what the using statement is doing by using try-catch block and call the Dispose() inside the finally block explicitly. But the using statement does the calls automatically to make the code cleaner and more elegant. Within the using block, the object is read-only and cannot be modified or reassigned.</p>\n<p>Example:</p>\n<pre><code>string connString = &quot;Data Source=localhost;Integrated Security=SSPI;Initial Catalog=Northwind;&quot;;\n\nusing (SqlConnection conn = new SqlConnection(connString))\n{\n SqlCommand cmd = conn.CreateCommand();\n cmd.CommandText = &quot;SELECT CustomerId, CompanyName FROM Customers&quot;;\n conn.Open();\n using (SqlDataReader dr = cmd.ExecuteReader())\n {\n while (dr.Read())\n Console.WriteLine(&quot;{0}\\t{1}&quot;, dr.GetString(0), dr.GetString(1));\n }\n}\n</code></pre>\n</li>\n</ol>\n<p>In the preceding code I am not closing any connection; it will close automatically. The <code>using</code> statement will call conn.Close() automatically due to the <code>using</code> statement (<code>using (SqlConnection conn = new SqlConnection(connString)</code>) and the same for a SqlDataReader object. And also if any exception occurs it will close the connection automatically.</p>\n<p>For more information, see <em><a href=\"https://www.c-sharpcorner.com/UploadFile/manas1/usage-and-importance-of-using-in-C-Sharp472/\" rel=\"nofollow noreferrer\">Usage and Importance of Using in C#</a></em>.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/75401", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13332/" ]
User [kokos](https://stackoverflow.com/users/1065/kokos) answered the wonderful *[Hidden Features of C#](https://stackoverflow.com/questions/9033/hidden-features-of-c)* question by mentioning the `using` keyword. Can you elaborate on that? What are the uses of `using`?
The reason for the `using` statement is to ensure that the object is disposed as soon as it goes out of scope, and it doesn't require explicit code to ensure that this happens. As in *[Understanding the 'using' statement in C# (codeproject)](https://www.codeproject.com/Articles/6564/Understanding-the-using-statement-in-C)* and *[Using objects that implement IDisposable (microsoft)](https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/using-objects)*, the C# compiler converts ``` using (MyResource myRes = new MyResource()) { myRes.DoSomething(); } ``` to ``` { // Limits scope of myRes MyResource myRes= new MyResource(); try { myRes.DoSomething(); } finally { // Check for a null resource. if (myRes != null) // Call the object's Dispose method. ((IDisposable)myRes).Dispose(); } } ``` C# 8 introduces a new syntax, named "[using declarations](https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#using-declarations)": > > A using declaration is a variable declaration preceded by the using keyword. It tells the compiler that the variable being declared should be disposed at the end of the enclosing scope. > > > So the equivalent code of above would be: ``` using var myRes = new MyResource(); myRes.DoSomething(); ``` And when control leaves the containing scope (usually a method, but it can also be a code block), `myRes` will be disposed.
75,440
<p>What method do I call to get the name of a class?</p>
[ { "answer_id": 75456, "author": "clahey", "author_id": 8453, "author_profile": "https://Stackoverflow.com/users/8453", "pm_score": 5, "selected": false, "text": "<p>It's not a method, it's a field. The field is called <code>__name__</code>. <code>class.__name__</code> will give the name of the class as a string. <code>object.__class__.__name__</code> will give the name of the class of an object.</p>\n" }, { "answer_id": 75467, "author": "Mr Shark", "author_id": 6093, "author_profile": "https://Stackoverflow.com/users/6093", "pm_score": 7, "selected": true, "text": "<pre><code>In [1]: class Test:\n ...: pass\n ...: \n\nIn [2]: Test.__name__\nOut[2]: 'Test'\n</code></pre>\n" }, { "answer_id": 77222, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>In [8]: <code>str('2'.__class__)</code><br />\nOut[8]: <code>\"&lt;type 'str'&gt;\"</code><br /></p>\n\n<p>In [9]: <code>str(len.__class__)</code><br />\nOut[9]: <code>\"&lt;type 'builtin_function_or_method'&gt;\"</code><br /></p>\n\n<p>In [10]: <code>str(4.6.__class__)</code><br />\nOut[10]: <code>\"&lt;type 'float'&gt;\"</code><br /></p>\n\n<p>Or, as was pointed out before,<br /></p>\n\n<p>In [11]: <code>4.6.__class__.__name__</code><br />\nOut[11]: <code>'float'</code></p>\n" }, { "answer_id": 83155, "author": "Jon Cage", "author_id": 15369, "author_profile": "https://Stackoverflow.com/users/15369", "pm_score": 4, "selected": false, "text": "<p>I agree with Mr.Shark, but if you have an instance of a class, you'll need to use its <code>__class__</code> member:</p>\n\n<pre><code>&gt;&gt;&gt; class test():\n... pass\n...\n&gt;&gt;&gt; a_test = test()\n&gt;&gt;&gt;\n&gt;&gt;&gt; a_test.__name__\nTraceback (most recent call last):\n File \"&lt;stdin&gt;\", line 1, in &lt;module&gt;\nAttributeError: test instance has no attribute '__name__'\n&gt;&gt;&gt;\n&gt;&gt;&gt; a_test.__class__\n&lt;class __main__.test at 0x009EEDE0&gt;\n</code></pre>\n" }, { "answer_id": 53653620, "author": "Azat Ibrakov", "author_id": 5997596, "author_profile": "https://Stackoverflow.com/users/5997596", "pm_score": 2, "selected": false, "text": "<p>From <a href=\"https://docs.python.org/whatsnew/3.3.html#pep-3155-qualified-name-for-classes-and-functions\" rel=\"nofollow noreferrer\"><strong>Python 3.3</strong></a> and onwards we can use <a href=\"https://docs.python.org/library/stdtypes.html#definition.__qualname__\" rel=\"nofollow noreferrer\"><code>__qualname__</code> field</a> for both classes &amp; functions.</p>\n<p>It differs from <a href=\"https://docs.python.org/library/stdtypes.html#definition.__name__\" rel=\"nofollow noreferrer\"><code>__name__</code> field</a> for nested objects like class defined in other class</p>\n<pre><code>&gt;&gt;&gt; class A:\n class B:\n pass\n&gt;&gt;&gt; A.B.__name__\n'B'\n&gt;&gt;&gt; A.B.__qualname__\n'A.B'\n</code></pre>\n<p>which may be quite useful.</p>\n<h1>Further reading</h1>\n<ul>\n<li><a href=\"https://www.python.org/dev/peps/pep-3155/\" rel=\"nofollow noreferrer\">PEP 3155 -- Qualified name for classes and functions</a>.</li>\n</ul>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/75440", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8453/" ]
What method do I call to get the name of a class?
``` In [1]: class Test: ...: pass ...: In [2]: Test.__name__ Out[2]: 'Test' ```
75,441
<p>As part of the Nant copy task, I would like to change the properties of the files in the target location. For instance make the files "read-write" from "read-only". How would I do this?</p>
[ { "answer_id": 75481, "author": "Phillip Wells", "author_id": 3012, "author_profile": "https://Stackoverflow.com/users/3012", "pm_score": 4, "selected": true, "text": "<p>Use the &lt;<a href=\"http://nant.sourceforge.net/release/0.85-rc1/help/tasks/attrib.html\" rel=\"noreferrer\">attrib</a>&gt; task. For example, to make the file \"test.txt\" read/write, you would use</p>\n\n<pre><code>&lt;attrib file=\"test.txt\" readonly=\"false\"/&gt;\n</code></pre>\n" }, { "answer_id": 76863, "author": "LordHits", "author_id": 8088, "author_profile": "https://Stackoverflow.com/users/8088", "pm_score": 3, "selected": false, "text": "<p>Also, for a list of files, the command is:</p>\n\n<pre><code>&lt;attrib readonly=\"false\"&gt;\n &lt;fileset basedir=\"mydirectory\"&gt;\n &lt;include name=\"**\"/&gt;\n &lt;/fileset&gt;\n&lt;/attrib&gt;\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/75441", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8088/" ]
As part of the Nant copy task, I would like to change the properties of the files in the target location. For instance make the files "read-write" from "read-only". How would I do this?
Use the <[attrib](http://nant.sourceforge.net/release/0.85-rc1/help/tasks/attrib.html)> task. For example, to make the file "test.txt" read/write, you would use ``` <attrib file="test.txt" readonly="false"/> ```
75,489
<p>I am pulling a long timestamp from a database, but want to present it as a Date using Tags only, no embedded java in the JSP.<br><br> I've created my own tag to do this because I was unable to get the parseDate and formatDate tags to work, but that's not to say they don't work.<br> <br> Any advice?</p> <p>Thanks.</p>
[ { "answer_id": 75674, "author": "ScArcher2", "author_id": 1310, "author_profile": "https://Stackoverflow.com/users/1310", "pm_score": 4, "selected": true, "text": "<p>The parseDate and formatDate tags work, but they work with Date objects.\nYou can call new java.util.Date(longvalue) to get a date object, then pass that to the standard tag.</p>\n\n<p>somewhere other than the jsp create your date object.</p>\n\n<pre><code>long longvalue = ...;//from database.\njava.util.Date dateValue = new java.util.Date(longvalue);\nrequest.setAttribute(\"dateValue\", dateValue);\n</code></pre>\n\n<p>put it on the request and then you can access it in your tag like this.</p>\n\n<pre><code>&lt;fmt:formatDate value=\"${dateValue}\" pattern=\"MM/dd/yyyy HH:mm\"/&gt;\n</code></pre>\n" }, { "answer_id": 2628641, "author": "BenM", "author_id": 43850, "author_profile": "https://Stackoverflow.com/users/43850", "pm_score": 6, "selected": false, "text": "<p>You can avoid having to make any changes to your Servlet by creating a date object within the JSP using the <code>jsp:useBean</code> and <code>jsp:setProperty</code> tags to set the time of newly created date object to that of the time stamp. For example:</p>\n\n<pre><code>&lt;%@ taglib uri=\"http://java.sun.com/jsp/jstl/fmt\" prefix=\"fmt\" %&gt;\n&lt;jsp:useBean id=\"dateValue\" class=\"java.util.Date\"/&gt;\n&lt;jsp:setProperty name=\"dateValue\" property=\"time\" value=\"${timestampValue}\"/&gt;\n&lt;fmt:formatDate value=\"${dateValue}\" pattern=\"MM/dd/yyyy HH:mm\"/&gt;\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/75489", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9450/" ]
I am pulling a long timestamp from a database, but want to present it as a Date using Tags only, no embedded java in the JSP. I've created my own tag to do this because I was unable to get the parseDate and formatDate tags to work, but that's not to say they don't work. Any advice? Thanks.
The parseDate and formatDate tags work, but they work with Date objects. You can call new java.util.Date(longvalue) to get a date object, then pass that to the standard tag. somewhere other than the jsp create your date object. ``` long longvalue = ...;//from database. java.util.Date dateValue = new java.util.Date(longvalue); request.setAttribute("dateValue", dateValue); ``` put it on the request and then you can access it in your tag like this. ``` <fmt:formatDate value="${dateValue}" pattern="MM/dd/yyyy HH:mm"/> ```
75,495
<p>When creating a UserControl in WPF, I find it convenient to give it some arbitrary Height and Width values so that I can view my changes in the Visual Studio designer. When I run the control, however, I want the Height and Width to be undefined, so that the control will expand to fill whatever container I place it in. How can I acheive this same functionality without having to remove the Height and Width values before building my control? (Or without using DockPanel in the parent container.)</p> <p>The following code demonstrates the problem:</p> <pre><code>&lt;Window x:Class="ExampleApplication3.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:loc="clr-namespace:ExampleApplication3" Title="Example" Height="600" Width="600"&gt; &lt;Grid Background="LightGray"&gt; &lt;loc:UserControl1 /&gt; &lt;/Grid&gt; &lt;/Window&gt; </code></pre> <p>The following definition of <code>UserControl1</code> displays reasonably at design time but displays as a fixed size at run time:</p> <pre><code>&lt;UserControl x:Class="ExampleApplication3.UserControl1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Height="300" Width="300"&gt; &lt;Grid Background="LightCyan" /&gt; &lt;/UserControl&gt; </code></pre> <p>The following definition of <code>UserControl1</code> displays as a dot at design time but expands to fill the parent <code>Window1</code> at run time:</p> <pre><code>&lt;UserControl x:Class="ExampleApplication3.UserControl1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&gt; &lt;Grid Background="LightCyan" /&gt; &lt;/UserControl&gt; </code></pre>
[ { "answer_id": 75527, "author": "Brian Leahy", "author_id": 580, "author_profile": "https://Stackoverflow.com/users/580", "pm_score": 6, "selected": false, "text": "<p>For Blend, a little known trick is to add these attributes to your usercontrol or window:</p>\n\n<pre><code> xmlns:d=\"http://schemas.microsoft.com/expression/blend/2008\" \n xmlns:mc=\"http://schemas.openxmlformats.org/markup-compatibility/2006\" \nmc:Ignorable=\"d\"\n d:DesignHeight=\"500\" d:DesignWidth=\"600\"\n</code></pre>\n\n<p>This will set the design height and width to 500 and 600 respectively. However this will only work for the blend designer. Not the Visual Studio Designer. </p>\n\n<p>As far as the Visual Studio Designer your technique is all that works. Which is why I don't use the Visual Studio Designer. ;)</p>\n" }, { "answer_id": 75606, "author": "Alex Duggleby", "author_id": 5790, "author_profile": "https://Stackoverflow.com/users/5790", "pm_score": 6, "selected": true, "text": "<p>In Visual Studio add the Width and Height attribute to your UserControl XAML, but in the code-behind insert this</p>\n\n<pre><code>public UserControl1()\n{\n InitializeComponent();\n if (LicenseManager.UsageMode != LicenseUsageMode.Designtime)\n {\n this.Width = double.NaN; ;\n this.Height = double.NaN; ;\n }\n}\n</code></pre>\n\n<p>This checks to see if the control is running in Design-mode. If not (i.e. runtime) it will set the Width and Height to NaN (Not a number) which is the value you set it to if you remove the Width and Height attributes in XAML.</p>\n\n<p>So at design-time you will have the preset width and height (including if you put the user control in a form) and at runtime it will dock depending on its parent container.</p>\n\n<p>Hope that helps.</p>\n" }, { "answer_id": 79134, "author": "AndyL", "author_id": 9944, "author_profile": "https://Stackoverflow.com/users/9944", "pm_score": 3, "selected": false, "text": "<p>I do this all the time. Simply set the width and height values to \"auto\" where you instantiate your control, and this will override the design-time values for that UserControl.</p>\n\n<p>ie: <code>&lt;loc:UserControl1 Width=\"auto\" Height=\"auto\" /&gt;</code></p>\n\n<p>Another option is to set a combination of MinWidth and MinHeight to a size that allows design-time work, while Width and Height remain \"auto\". Obviously, this only works if you don't need the UserControl to size smaller than the min values at runtime.</p>\n" }, { "answer_id": 311897, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I do it similar, but my solution assures that if you add your control to an container in design mode, it will appear reasonably.</p>\n\n<pre><code>protected override void OnVisualParentChanged(DependencyObject oldParent)\n{\n if (this.Parent != null)\n {\n this.Width = double.NaN;\n this.Height = double.NaN;\n }\n}\n</code></pre>\n\n<p>what do you think?</p>\n" }, { "answer_id": 421841, "author": "Paul", "author_id": 44636, "author_profile": "https://Stackoverflow.com/users/44636", "pm_score": 0, "selected": false, "text": "<p>Thanks to the original answerer for this solution! For those that are interested, here it is in VB:</p>\n\n<pre><code>If LicenseManager.UsageMode &lt;&gt; LicenseUsageMode.Designtime Then\n Me.Width = Double.NaN\n Me.Height = Double.NaN\nEnd If\n</code></pre>\n" }, { "answer_id": 1208106, "author": "jpierson", "author_id": 83658, "author_profile": "https://Stackoverflow.com/users/83658", "pm_score": 0, "selected": false, "text": "<p>Some have suggested using the LicenseManager.UsageMode property which I've never seen before but I have used the following code.</p>\n\n<pre><code>if(!DesignerProperties.GetIsInDesignMode(this))\n{\n this.Width = double.NaN;\n this.Height = double.NaN;\n}\n</code></pre>\n\n<p>esskar,</p>\n\n<p>I just want to add that you should generally always call the method of the base when overriding an \"On\" method.</p>\n\n<pre><code>protected override void OnVisualParentChanged(DependencyObject oldParent)\n{\n base.OnVisualParentChanged(oldParent);\n\n ...\n}\n</code></pre>\n\n<p>Great workaround by the way, I'm using it myself now too.</p>\n" }, { "answer_id": 5526765, "author": "CLaRGe", "author_id": 20507, "author_profile": "https://Stackoverflow.com/users/20507", "pm_score": 3, "selected": false, "text": "<p>Here are a list of <a href=\"http://msdn.microsoft.com/en-us/library/ff602277%28v=vs.95%29.aspx\" rel=\"nofollow noreferrer\">Design-Time Attributes in the Silverlight Designer</a>. They are the same for the WPF designer.</p>\n\n<p>It lists all of the <code>d:</code> values available in the Designer such as <code>d:DesignHeight</code>, <code>d:DesignWidth</code>, <code>d:IsDesignTimeCreatable</code>, <code>d:CreateList</code> and several others.</p>\n" }, { "answer_id": 5909295, "author": "Ondrej", "author_id": 741414, "author_profile": "https://Stackoverflow.com/users/741414", "pm_score": 2, "selected": false, "text": "<p>I was looking for similar solution like the one used in Blend and with your mentions I created simple behavior class with two attached properties Width &amp; Height that are applied only in DesinTime</p>\n\n<pre>\npublic static class DesignBehavior \n{\n private static readonly Type OwnerType = typeof (DesignBehavior);\n\n #region Width\n\n public static readonly DependencyProperty WidthProperty =\n DependencyProperty.RegisterAttached(\n \"Width\",\n typeof (double),\n OwnerType,\n new FrameworkPropertyMetadata(double.NaN, new PropertyChangedCallback(WidthChangedCallback)));\n\n public static double GetWidth(DependencyObject depObj)\n {\n return (double)depObj.GetValue(WidthProperty);\n }\n\n public static void SetWidth(DependencyObject depObj, double value)\n {\n depObj.SetValue(WidthProperty, value);\n }\n\n private static void WidthChangedCallback(DependencyObject depObj, DependencyPropertyChangedEventArgs e)\n {\n if (DesignerProperties.GetIsInDesignMode(depObj)) {\n depObj.SetValue(FrameworkElement.WidthProperty, e.NewValue);\n }\n }\n\n #endregion\n\n #region Height\n\n public static readonly DependencyProperty HeightProperty =\n DependencyProperty.RegisterAttached(\n \"Height\",\n typeof (double),\n OwnerType,\n new FrameworkPropertyMetadata(double.NaN, new PropertyChangedCallback(HeightChangedCallback)));\n\n public static double GetHeight(DependencyObject depObj)\n {\n return (double)depObj.GetValue(HeightProperty);\n }\n\n public static void SetHeight(DependencyObject depObj, double value)\n {\n depObj.SetValue(HeightProperty, value);\n }\n\n\n private static void HeightChangedCallback(DependencyObject depObj, DependencyPropertyChangedEventArgs e)\n {\n if (DesignerProperties.GetIsInDesignMode(depObj)) {\n depObj.SetValue(FrameworkElement.HeightProperty, e.NewValue);\n }\n }\n\n #endregion\n\n}\n</pre>\n\n<p>Then in your UserControl you just set these properties in Xaml</p>\n\n<pre>\n&lt;UserControl x:Class=\"ExtendedDataGrid.Views.PersonOverviewView\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:tool=\"http://schemas.microsoft.com/wpf/2008/toolkit\"\n xmlns:b=\"clr-namespace:ExtendedDataGrid.Behaviors\"\n b:DesignBehavior.Width=\"600\" b:DesignBehavior.Height=\"200\"&gt;\n &lt;Grid&gt;\n ...\n &lt;/Grid&gt;\n&lt;/UserControl&gt;\n</pre>\n" }, { "answer_id": 12169914, "author": "Roger Dufresne", "author_id": 1631841, "author_profile": "https://Stackoverflow.com/users/1631841", "pm_score": 1, "selected": false, "text": "<p>Use MinWidth and MinHeight on the control. That way, you'll see it in the designer, and at runtime it will size the way you want.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/75495", "https://Stackoverflow.com", "https://Stackoverflow.com/users/317/" ]
When creating a UserControl in WPF, I find it convenient to give it some arbitrary Height and Width values so that I can view my changes in the Visual Studio designer. When I run the control, however, I want the Height and Width to be undefined, so that the control will expand to fill whatever container I place it in. How can I acheive this same functionality without having to remove the Height and Width values before building my control? (Or without using DockPanel in the parent container.) The following code demonstrates the problem: ``` <Window x:Class="ExampleApplication3.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:loc="clr-namespace:ExampleApplication3" Title="Example" Height="600" Width="600"> <Grid Background="LightGray"> <loc:UserControl1 /> </Grid> </Window> ``` The following definition of `UserControl1` displays reasonably at design time but displays as a fixed size at run time: ``` <UserControl x:Class="ExampleApplication3.UserControl1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Height="300" Width="300"> <Grid Background="LightCyan" /> </UserControl> ``` The following definition of `UserControl1` displays as a dot at design time but expands to fill the parent `Window1` at run time: ``` <UserControl x:Class="ExampleApplication3.UserControl1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <Grid Background="LightCyan" /> </UserControl> ```
In Visual Studio add the Width and Height attribute to your UserControl XAML, but in the code-behind insert this ``` public UserControl1() { InitializeComponent(); if (LicenseManager.UsageMode != LicenseUsageMode.Designtime) { this.Width = double.NaN; ; this.Height = double.NaN; ; } } ``` This checks to see if the control is running in Design-mode. If not (i.e. runtime) it will set the Width and Height to NaN (Not a number) which is the value you set it to if you remove the Width and Height attributes in XAML. So at design-time you will have the preset width and height (including if you put the user control in a form) and at runtime it will dock depending on its parent container. Hope that helps.
75,500
<p>I have around 1000 pdf filesand I need to convert them to 300 dpi tiff files. What is the best way to do this? If there is an SDK or something or a tool that can be scripted that would be ideal. </p>
[ { "answer_id": 75524, "author": "JBB", "author_id": 12332, "author_profile": "https://Stackoverflow.com/users/12332", "pm_score": 2, "selected": false, "text": "<p>How about pdf2tiff? <a href=\"http://python.net/~gherman/pdf2tiff.html\" rel=\"nofollow noreferrer\">http://python.net/~gherman/pdf2tiff.html</a></p>\n" }, { "answer_id": 75567, "author": "Aeon", "author_id": 13289, "author_profile": "https://Stackoverflow.com/users/13289", "pm_score": 7, "selected": true, "text": "<p>Use Imagemagick, or better yet, Ghostscript.</p>\n\n<p><a href=\"http://www.ibm.com/developerworks/library/l-graf2/#N101C2\" rel=\"noreferrer\">http://www.ibm.com/developerworks/library/l-graf2/#N101C2</a> has an example for imagemagick:</p>\n\n<pre><code>convert foo.pdf pages-%03d.tiff\n</code></pre>\n\n<p><a href=\"http://www.asmail.be/msg0055376363.html\" rel=\"noreferrer\">http://www.asmail.be/msg0055376363.html</a> has an example for ghostscript:</p>\n\n<pre><code>gs -q -dNOPAUSE -sDEVICE=tiffg4 -sOutputFile=a.tif foo.pdf -c quit\n</code></pre>\n\n<p>I would install ghostscript and read the man page for gs to see what exact options are needed and experiment.</p>\n" }, { "answer_id": 75590, "author": "INS", "author_id": 13136, "author_profile": "https://Stackoverflow.com/users/13136", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://pypi.org/project/pdf2tiff/\" rel=\"nofollow noreferrer\">https://pypi.org/project/pdf2tiff/</a></p>\n\n<p>You could also use pdf2ps, ps2image and then convert from the resulting image to tiff with other utilities (I remember 'paul' [paul - Yet another image viewer (displays PNG, TIFF, GIF, JPG, etc.])</p>\n" }, { "answer_id": 75593, "author": "Danimal", "author_id": 2757, "author_profile": "https://Stackoverflow.com/users/2757", "pm_score": 2, "selected": false, "text": "<p>ABCPDF can do so as well -- check out <a href=\"http://www.websupergoo.com/helppdf6net/default.html\" rel=\"nofollow noreferrer\"><a href=\"http://www.websupergoo.com/helppdf6net/default.html\" rel=\"nofollow noreferrer\">http://www.websupergoo.com/helppdf6net/default.html</a></a></p>\n" }, { "answer_id": 98191, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 2, "selected": false, "text": "<p>Disclaimer: work for product I am recommending</p>\n\n<p>Atalasoft has a .NET library that can <a href=\"http://www.atalasoft.com/products/dotimage/net-tiff-pdf-sdk.aspx\" rel=\"nofollow noreferrer\">convert PDF to TIFF</a> -- we are a partner of FOXIT, so the PDF rendering is very good.</p>\n" }, { "answer_id": 113276, "author": "tomasso", "author_id": 15043, "author_profile": "https://Stackoverflow.com/users/15043", "pm_score": 6, "selected": false, "text": "<p>Using GhostScript from the command line, I've used the following in the past:</p>\n\n<p>on Windows:</p>\n\n<p><code>gswin32c -dNOPAUSE -q -g300x300 -sDEVICE=tiffg4 -dBATCH -sOutputFile=output_file_name.tif input_file_name.pdf</code></p>\n\n<p>on *nix:</p>\n\n<p><code>gs -dNOPAUSE -q -g300x300 -sDEVICE=tiffg4 -dBATCH -sOutputFile=output_file_name.tif input_file_name.pdf</code></p>\n\n<p>For a large number of files, a simple batch/shell script could be used to convert an arbitrary number of files...</p>\n" }, { "answer_id": 120316, "author": "gyurisc", "author_id": 260, "author_profile": "https://Stackoverflow.com/users/260", "pm_score": 4, "selected": false, "text": "<p>I wrote a little powershell script to go through a directory structure and convert all pdf files to tiff files using ghostscript. Here is my script: </p>\n\n<pre><code>$tool = 'C:\\Program Files\\gs\\gs8.63\\bin\\gswin32c.exe'\n$pdfs = get-childitem . -recurse | where {$_.Extension -match \"pdf\"}\n\nforeach($pdf in $pdfs)\n{\n\n $tiff = $pdf.FullName.split('.')[0] + '.tiff'\n if(test-path $tiff)\n {\n \"tiff file already exists \" + $tiff\n }\n else \n { \n 'Processing ' + $pdf.Name \n $param = \"-sOutputFile=$tiff\"\n &amp; $tool -q -dNOPAUSE -sDEVICE=tiffg4 $param -r300 $pdf.FullName -c quit\n }\n}\n</code></pre>\n" }, { "answer_id": 221341, "author": "Setori", "author_id": 21537, "author_profile": "https://Stackoverflow.com/users/21537", "pm_score": 3, "selected": false, "text": "<p>using python this is what I ended up with</p>\n<pre class=\"lang-py prettyprint-override\"><code>import os\nos.popen(' '.join([\n self._ghostscriptPath + 'gswin32c.exe', \n '-q',\n '-dNOPAUSE',\n '-dBATCH',\n '-r300',\n '-sDEVICE=tiff12nc',\n '-sPAPERSIZE=a4',\n '-sOutputFile=%s %s' % (tifDest, pdfSource),\n ]))\n</code></pre>\n" }, { "answer_id": 2428473, "author": "John", "author_id": 291872, "author_profile": "https://Stackoverflow.com/users/291872", "pm_score": 1, "selected": false, "text": "<p>I like PDFTIFF.com to <a href=\"http://www.pdftiff.com\" rel=\"nofollow noreferrer\">convert PDF to TIFF</a>, it can handle unlimited pages</p>\n" }, { "answer_id": 3790112, "author": "Tyler", "author_id": 457635, "author_profile": "https://Stackoverflow.com/users/457635", "pm_score": 3, "selected": false, "text": "<p>1) Install GhostScript</p>\n\n<p>2) Install ImageMagick</p>\n\n<p>3) Create \"Convert-to-TIFF.bat\" (Windows XP, Vista, 7) and use the following line:</p>\n\n<pre><code>for %%f in (%*) DO \"C:\\Program Files\\ImageMagick-6.6.4-Q16\\convert.exe\" -density 300 -compress lzw %%f %%f.tiff\n</code></pre>\n\n<p>Dragging any number of single-page PDF files onto this file will convert them to compressed TIFFs, at 300 DPI. </p>\n" }, { "answer_id": 7511450, "author": "Russell Wong", "author_id": 360257, "author_profile": "https://Stackoverflow.com/users/360257", "pm_score": 2, "selected": false, "text": "<p>Required ghostscript &amp; tiffcp\nTested in Ubuntu</p>\n\n<pre><code>import os\n\ndef pdf2tiff(source, destination):\n idx = destination.rindex('.')\n destination = destination[:idx]\n args = [\n '-q', '-dNOPAUSE', '-dBATCH',\n '-sDEVICE=tiffg4',\n '-r600', '-sPAPERSIZE=a4',\n '-sOutputFile=' + destination + '__%03d.tiff'\n ]\n gs_cmd = 'gs ' + ' '.join(args) +' '+ source\n os.system(gs_cmd)\n args = [destination + '__*.tiff', destination + '.tiff' ]\n tiffcp_cmd = 'tiffcp ' + ' '.join(args)\n os.system(tiffcp_cmd)\n args = [destination + '__*.tiff']\n rm_cmd = 'rm ' + ' '.join(args)\n os.system(rm_cmd) \npdf2tiff('abc.pdf', 'abc.tiff')\n</code></pre>\n" }, { "answer_id": 8065301, "author": "Sally", "author_id": 1037695, "author_profile": "https://Stackoverflow.com/users/1037695", "pm_score": 2, "selected": false, "text": "<p>Maybe also try this? <a href=\"http://www.sautinsoft.com/products/pdf-focus/index.php\" rel=\"nofollow\">PDF Focus</a></p>\n\n<p>This .Net library allows you to solve the problem :)</p>\n\n<p>This code will help (Convert 1000 PDF files to 300-dpi TIFF files in C#):</p>\n\n<pre><code> SautinSoft.PdfFocus f = new SautinSoft.PdfFocus();\n\n string[] pdfFiles = Directory.GetFiles(@\"d:\\Folder with 1000 pdfs\\\", \"*.pdf\");\n string folderWithTiffs = @\"d:\\Folder with TIFFs\\\";\n\n foreach (string pdffile in pdfFiles)\n {\n f.OpenPdf(pdffile);\n\n if (f.PageCount &gt; 0)\n {\n //save all pages to tiff files with 300 dpi\n f.ToImage(folderWithTiffs, Path.GetFileNameWithoutExtension(pdffile), System.Drawing.Imaging.ImageFormat.Tiff, 300);\n }\n f.ClosePdf();\n }\n</code></pre>\n" }, { "answer_id": 8353467, "author": "k venkat", "author_id": 1076963, "author_profile": "https://Stackoverflow.com/users/1076963", "pm_score": 2, "selected": false, "text": "<p>The PDF Focus .Net can do it in such way:</p>\n\n<p><strong>1.</strong> <em><strong>PDF to TIFF</em></strong></p>\n\n<pre><code>SautinSoft.PdfFocus f = new SautinSoft.PdfFocus(); \n\nstring pdfPath = @\"c:\\My.pdf\";\n\nstring imageFolder = @\"c:\\images\\\";\n\nf.OpenPdf(pdfPath);\n\nif (f.PageCount &gt; 0)\n{\n //Save all PDF pages to image folder as tiff images, 200 dpi\n int result = f.ToImage(imageFolder, \"page\",System.Drawing.Imaging.ImageFormat.Tiff, 200);\n}\n</code></pre>\n\n<p><strong>2.</strong> <em><strong>PDF to Multipage-TIFF</em></strong></p>\n\n<pre><code>//Convert PDF file to Multipage TIFF file\n\nSautinSoft.PdfFocus f = new SautinSoft.PdfFocus();\n\nstring pdfPath = @\"c:\\Document.pdf\";\nstring tiffPath = @\"c:\\Result.tiff\";\n\nf.OpenPdf(pdfPath);\n\nif (f.PageCount &gt; 0)\n{\n f.ToMultipageTiff(tiffPath, 120) == 0)\n {\n System.Diagnostics.Process.Start(tiffPath);\n }\n} \n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/75500", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260/" ]
I have around 1000 pdf filesand I need to convert them to 300 dpi tiff files. What is the best way to do this? If there is an SDK or something or a tool that can be scripted that would be ideal.
Use Imagemagick, or better yet, Ghostscript. <http://www.ibm.com/developerworks/library/l-graf2/#N101C2> has an example for imagemagick: ``` convert foo.pdf pages-%03d.tiff ``` <http://www.asmail.be/msg0055376363.html> has an example for ghostscript: ``` gs -q -dNOPAUSE -sDEVICE=tiffg4 -sOutputFile=a.tif foo.pdf -c quit ``` I would install ghostscript and read the man page for gs to see what exact options are needed and experiment.
75,508
<p>I have 28,000 images I need to convert into a movie. I tried </p> <pre><code>mencoder mf://*.jpg -mf w=640:h=480:fps=30:type=jpg -ovc lavc -lavcopts vcodec=msmpeg4v2 -nosound -o ../output-msmpeg4v2.avi </code></pre> <p>But it seems to crap out at 7500 frames.</p> <p>The files are named webcam_2007-04-16_070804.jpg webcam_2007-04-16_071004.jpg webcam_2007-04-16_071204.jpg webcam_2007-04-16_071404.jpg Up to march 2008 or so.</p> <p>Is there another way I can pass the filenames to mencoder so it doesn't stop part way?</p> <pre><code>MEncoder 2:1.0~rc2-0ubuntu13 (C) 2000-2007 MPlayer Team CPU: Intel(R) Pentium(R) 4 CPU 2.40GHz (Family: 15, Model: 2, Stepping: 7) CPUflags: Type: 15 MMX: 1 MMX2: 1 3DNow: 0 3DNow2: 0 SSE: 1 SSE2: 1 Compiled with runtime CPU detection. success: format: 16 data: 0x0 - 0x0 MF file format detected. [mf] search expr: *.jpg [mf] number of files: 28617 (114468) VIDEO: [IJPG] 640x480 24bpp 30.000 fps 0.0 kbps ( 0.0 kbyte/s) [V] filefmt:16 fourcc:0x47504A49 size:640x480 fps:30.00 ftime:=0.0333 Opening video filter: [expand osd=1] Expand: -1 x -1, -1 ; -1, osd: 1, aspect: 0.000000, round: 1 ========================================================================== Opening video decoder: [ffmpeg] FFmpeg's libavcodec codec family Selected video codec: [ffmjpeg] vfm: ffmpeg (FFmpeg MJPEG decoder) ========================================================================== VDec: vo config request - 640 x 480 (preferred colorspace: Planar YV12) VDec: using Planar YV12 as output csp (no 3) Movie-Aspect is 1.33:1 - prescaling to correct movie aspect. videocodec: libavcodec (640x480 fourcc=3234504d [MP42]) Writing header... ODML: Aspect information not (yet?) available or unspecified, not writing vprp header. Writing header... ODML: Aspect information not (yet?) available or unspecified, not writing vprp header. Pos: 251.3s 7539f ( 0%) 47.56fps Trem: 0min 0mb A-V:0.000 [1202:0] Flushing video frames. Writing index... Writing header... ODML: Aspect information not (yet?) available or unspecified, not writing vprp header. Video stream: 1202.480 kbit/s (150310 B/s) size: 37772908 bytes 251.300 secs 7539 frames </code></pre>
[ { "answer_id": 75566, "author": "Grank", "author_id": 12975, "author_profile": "https://Stackoverflow.com/users/12975", "pm_score": 0, "selected": false, "text": "<p>another alternative is to bypass mencoder and use ffmpeg directly</p>\n" }, { "answer_id": 75616, "author": "Dark Shikari", "author_id": 11206, "author_profile": "https://Stackoverflow.com/users/11206", "pm_score": 1, "selected": false, "text": "<p>You might be better off going to #mplayer or #ffmpeg on Freenode IRC for specific help with those programs.</p>\n" }, { "answer_id": 75635, "author": "metadave", "author_id": 7237, "author_profile": "https://Stackoverflow.com/users/7237", "pm_score": 0, "selected": false, "text": "<p>Kinda of an odd answer... but I thought that Blender could construct videos from sequences of images. Just a thought.</p>\n" }, { "answer_id": 75668, "author": "moonshadow", "author_id": 11834, "author_profile": "https://Stackoverflow.com/users/11834", "pm_score": 3, "selected": true, "text": "<p>Shove the list of images in a file, one per line. Then use <code>mf://@filename</code></p>\n" }, { "answer_id": 83658, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>You can create a video from a sequence of images using LiVES:\n<a href=\"http://lives.sourceforge.net\" rel=\"nofollow noreferrer\">http://lives.sourceforge.net</a></p>\n\n<p>Simply place all of the images in a directory, and make sure they are in alphanumeric order.\nThen in LiVES, just go to File/Open File or Directory, and double-click on the image directory.</p>\n\n<p>Once the images have loaded you can edit the clip and save it in a variety of formats.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/75508", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11950/" ]
I have 28,000 images I need to convert into a movie. I tried ``` mencoder mf://*.jpg -mf w=640:h=480:fps=30:type=jpg -ovc lavc -lavcopts vcodec=msmpeg4v2 -nosound -o ../output-msmpeg4v2.avi ``` But it seems to crap out at 7500 frames. The files are named webcam\_2007-04-16\_070804.jpg webcam\_2007-04-16\_071004.jpg webcam\_2007-04-16\_071204.jpg webcam\_2007-04-16\_071404.jpg Up to march 2008 or so. Is there another way I can pass the filenames to mencoder so it doesn't stop part way? ``` MEncoder 2:1.0~rc2-0ubuntu13 (C) 2000-2007 MPlayer Team CPU: Intel(R) Pentium(R) 4 CPU 2.40GHz (Family: 15, Model: 2, Stepping: 7) CPUflags: Type: 15 MMX: 1 MMX2: 1 3DNow: 0 3DNow2: 0 SSE: 1 SSE2: 1 Compiled with runtime CPU detection. success: format: 16 data: 0x0 - 0x0 MF file format detected. [mf] search expr: *.jpg [mf] number of files: 28617 (114468) VIDEO: [IJPG] 640x480 24bpp 30.000 fps 0.0 kbps ( 0.0 kbyte/s) [V] filefmt:16 fourcc:0x47504A49 size:640x480 fps:30.00 ftime:=0.0333 Opening video filter: [expand osd=1] Expand: -1 x -1, -1 ; -1, osd: 1, aspect: 0.000000, round: 1 ========================================================================== Opening video decoder: [ffmpeg] FFmpeg's libavcodec codec family Selected video codec: [ffmjpeg] vfm: ffmpeg (FFmpeg MJPEG decoder) ========================================================================== VDec: vo config request - 640 x 480 (preferred colorspace: Planar YV12) VDec: using Planar YV12 as output csp (no 3) Movie-Aspect is 1.33:1 - prescaling to correct movie aspect. videocodec: libavcodec (640x480 fourcc=3234504d [MP42]) Writing header... ODML: Aspect information not (yet?) available or unspecified, not writing vprp header. Writing header... ODML: Aspect information not (yet?) available or unspecified, not writing vprp header. Pos: 251.3s 7539f ( 0%) 47.56fps Trem: 0min 0mb A-V:0.000 [1202:0] Flushing video frames. Writing index... Writing header... ODML: Aspect information not (yet?) available or unspecified, not writing vprp header. Video stream: 1202.480 kbit/s (150310 B/s) size: 37772908 bytes 251.300 secs 7539 frames ```
Shove the list of images in a file, one per line. Then use `mf://@filename`
75,538
<p>No C++ love when it comes to the "hidden features of" line of questions? Figured I would throw it out there. What are some of the hidden features of C++?</p>
[ { "answer_id": 75581, "author": "neuroguy123", "author_id": 12529, "author_profile": "https://Stackoverflow.com/users/12529", "pm_score": 2, "selected": false, "text": "<p>I'm not sure about hidden, but there are some <a href=\"http://en.wikipedia.org/wiki/Duff%27s_device\" rel=\"nofollow noreferrer\">interesting</a> <a href=\"http://en.wikipedia.org/wiki/Template_metaprogramming\" rel=\"nofollow noreferrer\">'tricks'</a> that probably aren't obvious from just reading the spec.</p>\n" }, { "answer_id": 75627, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 6, "selected": false, "text": "<blockquote>\n <p>C++ is a standard, there shouldn't be any hidden features...</p>\n</blockquote>\n\n<p>C++ is a multi-paradigm language, you can bet your last money on there being hidden features. One example out of many: <a href=\"http://en.wikipedia.org/wiki/Template_metaprogramming\" rel=\"nofollow noreferrer\">template metaprogramming</a>. Nobody in the standards committee intended there to be a Turing-complete sublanguage that gets executed at compile-time.</p>\n" }, { "answer_id": 75709, "author": "Drealmer", "author_id": 12291, "author_profile": "https://Stackoverflow.com/users/12291", "pm_score": 3, "selected": false, "text": "<p>I found this blog to be an amazing resource about the arcanes of C++ : <a href=\"http://cpptruths.blogspot.com/\" rel=\"nofollow noreferrer\">C++ Truths</a>.</p>\n" }, { "answer_id": 75818, "author": "sergtk", "author_id": 13441, "author_profile": "https://Stackoverflow.com/users/13441", "pm_score": 3, "selected": false, "text": "<p>There is no hidden features, but the language C++ is very powerful and frequently even developers of standard couldn't imagine what C++ can be used for. </p>\n\n<p>Actually from simple enough language construction you can write something very powerful.\nA lot of such things are available at www.boost.org as an examples (and <a href=\"http://www.boost.org/doc/libs/1_36_0/doc/html/lambda.html\" rel=\"noreferrer\">http://www.boost.org/doc/libs/1_36_0/doc/html/lambda.html</a> among them).</p>\n\n<p>To understand the way how simple language constuction can be combined to something powerful it is good to read <a href=\"https://rads.stackoverflow.com/amzn/click/com/0201734842\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">\"C++ Templates: The Complete Guide\" by David Vandevoorde, Nicolai M. Josuttis</a> and really magic book <a href=\"https://rads.stackoverflow.com/amzn/click/com/0201704315\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">\"Modern C++ Design ... \" by Andrei Alexandrescu</a>.</p>\n\n<p>And finally, it is difficult to learn C++, you should try to fill it ;)</p>\n" }, { "answer_id": 75849, "author": "ugasoft", "author_id": 10120, "author_profile": "https://Stackoverflow.com/users/10120", "pm_score": 2, "selected": false, "text": "<p>There are a lot of \"undefined behavior\". You can learn how to avoid them reading good books and reading the standards.</p>\n" }, { "answer_id": 75917, "author": "Amir", "author_id": 13480, "author_profile": "https://Stackoverflow.com/users/13480", "pm_score": 1, "selected": false, "text": "<p>There are tons of \"tricky\" constructs in C++.\nThey go from \"simple\" implementions of <a href=\"http://www.gamedev.net/reference/programming/features/cppseal/\" rel=\"nofollow noreferrer\">sealed/final classes</a> using virtual inheritance.\nAnd get to pretty \"complex\" meta programming constructs such as Boost's <a href=\"http://www.boost.org/doc/libs/1_36_0/libs/mpl/doc/index.html\" rel=\"nofollow noreferrer\">MPL</a> (<a href=\"http://ubiety.uwaterloo.ca/~tveldhui/papers/Template-Metaprograms/meta-art.html\" rel=\"nofollow noreferrer\">tutorial</a>). The possibilities for shooting yourself in the foot are endless, but if kept in check (i.e. seasoned programmers), provide some of the best flexibility in terms of maintainability and performance.</p>\n" }, { "answer_id": 76058, "author": "Markowitch", "author_id": 11964, "author_profile": "https://Stackoverflow.com/users/11964", "pm_score": 3, "selected": false, "text": "<blockquote>\n <p>One example out of many: template\n metaprogramming. Nobody in the\n standards committee intended there to\n be a Turing-complete sublanguage that\n gets executed at compile-time.</p>\n</blockquote>\n\n<p>Template metaprogramming is hardly a hidden feature. It's even in the boost library. See <a href=\"http://www.boost.org/doc/libs/release/libs/mpl/doc/index.html\" rel=\"nofollow noreferrer\">MPL</a>. But if \"almost hidden\" is good enough, then take a look at the <a href=\"http://www.boost.org/doc/libs\" rel=\"nofollow noreferrer\">boost libraries</a>. It contain many goodies which are not easy accesible without the backing of a strong library.</p>\n\n<p>One example is <a href=\"http://www.boost.org/doc/libs/release/doc/html/lambda.html\" rel=\"nofollow noreferrer\">boost.lambda</a> library, which is interesting since C++ does not have lambda functions in the current standard.</p>\n\n<p>Another example is <a href=\"http://loki-lib.sourceforge.net/index.php?n=Main.HomePage\" rel=\"nofollow noreferrer\">Loki</a>, which \"makes extensive use of C++ template metaprogramming and implements several commonly used tools: typelist, functor, singleton, smart pointer, object factory, visitor and multimethods.\" [<a href=\"http://en.wikipedia.org/wiki/Loki_%28C%2B%2B%29\" rel=\"nofollow noreferrer\">Wikipedia</a>]</p>\n" }, { "answer_id": 76606, "author": "MSN", "author_id": 6210, "author_profile": "https://Stackoverflow.com/users/6210", "pm_score": 6, "selected": false, "text": "<p>Lifetime of temporaries bound to const references is one that few people know about. Or at least it's my favorite piece of C++ knowledge that most people don't know about.</p>\n\n<pre><code>const MyClass&amp; x = MyClass(); // temporary exists as long as x is in scope\n</code></pre>\n" }, { "answer_id": 76801, "author": "Colin Jensen", "author_id": 9884, "author_profile": "https://Stackoverflow.com/users/9884", "pm_score": 6, "selected": false, "text": "<p>The array operator is associative.</p>\n\n<p>A[8] is a synonym for *(A + 8). Since addition is associative, that can be rewritten as *(8 + A), which is a synonym for..... 8[A]</p>\n\n<p>You didn't say useful... :-) </p>\n" }, { "answer_id": 77169, "author": "Sridhar Iyer", "author_id": 13820, "author_profile": "https://Stackoverflow.com/users/13820", "pm_score": 2, "selected": false, "text": "<p>Most C++ developers ignore the power of template metaprogramming. Check out <a href=\"http://loki-lib.sourceforge.net/index.php?n=Main.HomePage\" rel=\"nofollow noreferrer\">Loki Libary</a>. It implements several advanced tools like typelist, functor, singleton, smart pointer, object factory, visitor and multimethods using template metaprogramming extensively (from <a href=\"http://en.wikipedia.org/wiki/Loki_(C%2B%2B)\" rel=\"nofollow noreferrer\">wikipedia</a>). \nFor most part you could consider these as \"hidden\" c++ feature.</p>\n" }, { "answer_id": 78128, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 7, "selected": false, "text": "<p>I agree with most posts there: C++ is a multi-paradigm language, so the \"hidden\" features you'll find (other than \"undefined behaviours\" that you should avoid at all cost) are clever uses of facilities.</p>\n\n<p>Most of those facilities are not build-in features of the language, but library-based ones.</p>\n\n<p>The most important is the <strong>RAII</strong>, often ignored for years by C++ developers coming from the C world. <strong>Operator overloading</strong> is often a misunderstood feature that enable both array-like behaviour (subscript operator), pointer like operations (smart pointers) and build-in-like operations (multiplying matrices.</p>\n\n<p>The use of <strong>exception</strong> is often difficult, but with some work, can produce really robust code through <strong>exception safety</strong> specifications (including code that won't fail, or that will have a commit-like features that is that will succeed, or revert back to its original state).</p>\n\n<p>The most famous of \"hidden\" feature of C++ is <strong>template metaprogramming</strong>, as it enables you to have your program partially (or totally) executed at compile-time instead of runtime. This is difficult, though, and you must have a solid grasp on templates before trying it.</p>\n\n<p>Other make uses of the multiple paradigm to produce \"ways of programming\" outside of C++'s ancestor, that is, C.</p>\n\n<p>By using <strong>functors</strong>, you can simulate functions, with the additional type-safety and being stateful. Using the <strong>command</strong> pattern, you can delay code execution. Most other <strong>design patterns</strong> can be easily and efficiently implemented in C++ to produce alternative coding styles not supposed to be inside the list of \"official C++ paradigms\".</p>\n\n<p>By using <strong>templates</strong>, you can produce code that will work on most types, including not the one you thought at first. You can increase type safety,too (like an automated typesafe malloc/realloc/free). C++ object features are really powerful (and thus, dangerous if used carelessly), but even the <strong>dynamic polymorphism</strong> have its static version in C++: the <strong>CRTP</strong>.</p>\n\n<p>I have found that most \"<em>Effective C++</em>\"-type books from Scott Meyers or \"<em>Exceptional C++</em>\"-type books from Herb Sutter to be both easy to read, and quite treasures of info on known and less known features of C++.</p>\n\n<p>Among my preferred is one that should make the hair of any Java programmer rise from horror: In C++, <strong>the most object-oriented way to add a feature to an object is through a non-member non-friend function, instead of a member-function</strong> (i.e. class method), because:</p>\n\n<ul>\n<li><p>In C++, a class' interface is both its member-functions and the non-member functions in the same namespace</p></li>\n<li><p>non-friend non-member functions have no privileged access to the class internal. As such, using a member function over a non-member non-friend one will weaken the class' encapsulation.</p></li>\n</ul>\n\n<p>This never fails to surprise even experienced developers.</p>\n\n<p>(Source: Among others, Herb Sutter's online Guru of the Week #84: <a href=\"http://www.gotw.ca/gotw/084.htm\" rel=\"nofollow noreferrer\">http://www.gotw.ca/gotw/084.htm</a> )</p>\n" }, { "answer_id": 78436, "author": "Robert", "author_id": 14364, "author_profile": "https://Stackoverflow.com/users/14364", "pm_score": 5, "selected": false, "text": "<p>Oooh, I can come up with a list of pet hates instead:</p>\n\n<ul>\n<li>Destructors need to be virtual if you intend use polymorphically</li>\n<li>Sometimes members are initialized by default, sometimes they aren't</li>\n<li>Local clases can't be used as template parameters (makes them less useful)</li>\n<li>exception specifiers: look useful, but aren't</li>\n<li>function overloads hide base class functions with different signatures.</li>\n<li>no useful standardisation on internationalisation (portable standard wide charset, anyone? We'll have to wait until C++0x)</li>\n</ul>\n\n<p>On the plus side</p>\n\n<ul>\n<li>hidden feature: function try blocks. Unfortunately I haven't found a use for it. Yes I know why they added it, but you have to rethrow in a constructor which makes it pointless.</li>\n<li>It's worth looking carefully at the STL guarantees about iterator validity after container modification, which can let you make some slightly nicer loops.</li>\n<li>Boost - it's hardly a secret but it's worth using.</li>\n<li>Return value optimisation (not obvious, but it's specifically allowed by the standard)</li>\n<li>Functors aka function objects aka operator(). This is used extensively by the STL. not really a secret, but is a nifty side effect of operator overloading and templates.</li>\n</ul>\n" }, { "answer_id": 78484, "author": "Jason Mock", "author_id": 13630, "author_profile": "https://Stackoverflow.com/users/13630", "pm_score": 7, "selected": false, "text": "<p>One language feature that I consider to be somewhat hidden, because I had never heard about it throughout my entire time in school, is the namespace alias. It wasn't brought to my attention until I ran into examples of it in the boost documentation. Of course, now that I know about it you can find it in any standard C++ reference.</p>\n\n<pre><code>namespace fs = boost::filesystem;\n\nfs::path myPath( strPath, fs::native );\n</code></pre>\n" }, { "answer_id": 78557, "author": "shoosh", "author_id": 9611, "author_profile": "https://Stackoverflow.com/users/9611", "pm_score": 2, "selected": false, "text": "<ul>\n<li>pointers to class methods </li>\n<li>The \"typename\" keyword</li>\n</ul>\n" }, { "answer_id": 78840, "author": "Ben", "author_id": 13950, "author_profile": "https://Stackoverflow.com/users/13950", "pm_score": 8, "selected": false, "text": "<p>You can put URIs into C++ source without error. For example:</p>\n\n<pre><code>void foo() {\n http://stackoverflow.com/\n int bar = 4;\n\n ...\n}\n</code></pre>\n" }, { "answer_id": 132174, "author": "bernardn", "author_id": 21548, "author_profile": "https://Stackoverflow.com/users/21548", "pm_score": -1, "selected": false, "text": "<p>Pointer arithmetics.</p>\n\n<p>It's actually a C feature, but I noticed that few people that use C/C++ are really aware it even exists. I consider this feature of the C language truly shows the genius and vision of its inventor.</p>\n\n<p>To make a long story short, pointer arithmetics allows the compiler to perform a[n] as *(a+n) for any type of a. As a side note, as '+' is commutative a[n] is of course equivalent to n[a].</p>\n" }, { "answer_id": 132815, "author": "AareP", "author_id": 11741, "author_profile": "https://Stackoverflow.com/users/11741", "pm_score": 4, "selected": false, "text": "<p>Getting rid of forward declarations:</p>\n\n<pre><code>struct global\n{\n void main()\n {\n a = 1;\n b();\n }\n int a;\n void b(){}\n}\nsingleton;\n</code></pre>\n\n<p>Writing switch-statements with ?: operators:</p>\n\n<pre><code>string result = \n a==0 ? \"zero\" :\n a==1 ? \"one\" :\n a==2 ? \"two\" :\n 0;\n</code></pre>\n\n<p>Doing everything on a single line:</p>\n\n<pre><code>void a();\nint b();\nfloat c = (a(),b(),1.0f);\n</code></pre>\n\n<p>Zeroing structs without memset: </p>\n\n<pre><code>FStruct s = {0};\n</code></pre>\n\n<p>Normalizing/wrapping angle- and time-values:</p>\n\n<pre><code>int angle = (short)((+180+30)*65536/360) * 360/65536; //==-150\n</code></pre>\n\n<p>Assigning references:</p>\n\n<pre><code>struct ref\n{\n int&amp; r;\n ref(int&amp; r):r(r){}\n};\nint b;\nref a(b);\nint c;\n*(int**)&amp;a = &amp;c;\n</code></pre>\n" }, { "answer_id": 152659, "author": "vividos", "author_id": 23740, "author_profile": "https://Stackoverflow.com/users/23740", "pm_score": 6, "selected": false, "text": "<p>A nice feature that isn't used often is the function-wide try-catch block:</p>\n\n<pre><code>int Function()\ntry\n{\n // do something here\n return 42;\n}\ncatch(...)\n{\n return -1;\n}\n</code></pre>\n\n<p>Main usage would be to translate exception to other exception class and rethrow, or to translate between exceptions and return-based error code handling.</p>\n" }, { "answer_id": 169114, "author": "Sumant", "author_id": 25014, "author_profile": "https://Stackoverflow.com/users/25014", "pm_score": 5, "selected": false, "text": "<p>Hidden features:</p>\n\n<ol>\n<li>Pure virtual functions can have implementation. Common example, pure virtual destructor.</li>\n<li><p>If a function throws an exception not listed in its exception specifications, but the function has <code>std::bad_exception</code> in its exception specification, the exception is converted into <code>std::bad_exception</code> and thrown automatically. That way you will at least know that a <code>bad_exception</code> was thrown. Read more <a href=\"http://cpptruths.blogspot.com/2007/05/use-of-stdbadexception.html\" rel=\"nofollow noreferrer\">here</a>.</p></li>\n<li><p>function try blocks</p></li>\n<li><p>The template keyword in disambiguating typedefs in a class template. If the name of a member template specialization appears after a <code>.</code>, <code>-&gt;</code>, or <code>::</code> operator, and that name has explicitly qualified template parameters, prefix the member template name with the keyword template. Read more <a href=\"http://en.wikibooks.org/wiki/More_C++_Idioms/Policy_Clone\" rel=\"nofollow noreferrer\">here</a>.</p></li>\n<li><p>function parameter defaults can be changed at runtime. Read more <a href=\"http://cpptruths.blogspot.com/2005/07/changing-c-function-default-arguments.html\" rel=\"nofollow noreferrer\">here</a>.</p></li>\n<li><p><code>A[i]</code> works as good as <code>i[A]</code></p></li>\n<li><p>Temporary instances of a class can be modified! A non-const member function can be invoked on a temporary object. For example:</p>\n\n<pre><code>struct Bar {\n void modify() {}\n}\nint main (void) {\n Bar().modify(); /* non-const function invoked on a temporary. */\n}\n</code></pre>\n\n<p>Read more <a href=\"http://cpptruths.blogspot.com/2009/08/modifying-temporaries.html\" rel=\"nofollow noreferrer\">here</a>.</p></li>\n<li><p>If two different types are present before and after the <code>:</code> in the ternary (<code>?:</code>) operator expression, then the resulting type of the expression is the one that is the most general of the two. For example:</p>\n\n<pre><code>void foo (int) {}\nvoid foo (double) {}\nstruct X {\n X (double d = 0.0) {}\n};\nvoid foo (X) {} \n\nint main(void) {\n int i = 1;\n foo(i ? 0 : 0.0); // calls foo(double)\n X x;\n foo(i ? 0.0 : x); // calls foo(X)\n}\n</code></pre></li>\n</ol>\n" }, { "answer_id": 170597, "author": "Sirish", "author_id": 7965, "author_profile": "https://Stackoverflow.com/users/7965", "pm_score": 5, "selected": false, "text": "<p>Array initialization in constructor.\nFor example in a class if we have a array of <code>int</code> as:</p>\n\n<pre><code>class clName\n{\n clName();\n int a[10];\n};\n</code></pre>\n\n<p>We can initialize all elements in the array to its default (here all elements of array to zero) in the constructor as:</p>\n\n<pre><code>clName::clName() : a()\n{\n}\n</code></pre>\n" }, { "answer_id": 172357, "author": "Constantin", "author_id": 20310, "author_profile": "https://Stackoverflow.com/users/20310", "pm_score": 5, "selected": false, "text": "<p><code>map::operator[]</code> creates entry if key is missing and returns reference to default-constructed entry value. So you can write:</p>\n\n<pre><code>map&lt;int, string&gt; m;\nstring&amp; s = m[42]; // no need for map::find()\nif (s.empty()) { // assuming we never store empty values in m\n s.assign(...);\n}\ncout &lt;&lt; s;\n</code></pre>\n\n<p>I'm amazed at how many C++ programmers don't know this.</p>\n" }, { "answer_id": 218306, "author": "Jim Hunziker", "author_id": 6160, "author_profile": "https://Stackoverflow.com/users/6160", "pm_score": 4, "selected": false, "text": "<p>Putting functions or variables in a nameless namespace deprecates the use of <code>static</code> to restrict them to file scope.</p>\n" }, { "answer_id": 302563, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 8, "selected": false, "text": "<p>Most C++ programmers are familiar with the ternary operator:</p>\n\n<pre><code>x = (y &lt; 0) ? 10 : 20;\n</code></pre>\n\n<p>However, they don't realize that it can be used as an lvalue:</p>\n\n<pre><code>(a == 0 ? a : b) = 1;\n</code></pre>\n\n<p>which is shorthand for</p>\n\n<pre><code>if (a == 0)\n a = 1;\nelse\n b = 1;\n</code></pre>\n\n<p>Use with caution :-)</p>\n" }, { "answer_id": 304187, "author": "Jason Baker", "author_id": 2147, "author_profile": "https://Stackoverflow.com/users/2147", "pm_score": 4, "selected": false, "text": "<p>Read a file into a vector of strings:</p>\n\n<pre><code> vector&lt;string&gt; V;\n copy(istream_iterator&lt;string&gt;(cin), istream_iterator&lt;string&gt;(),\n back_inserter(V));\n</code></pre>\n\n<p><a href=\"http://www.sgi.com/tech/stl/istream_iterator.html\" rel=\"nofollow noreferrer\">istream_iterator</a></p>\n" }, { "answer_id": 312426, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 7, "selected": false, "text": "<blockquote>\n <p>Pointer arithmetics.</p>\n</blockquote>\n\n<p>C++ programmers prefer to avoid pointers because of the bugs that can be introduced.</p>\n\n<p>The coolest C++ I've ever seen though? <a href=\"http://web.archive.org/web/20120110153227/http://weegen.home.xs4all.nl/eelis/analogliterals.xhtml\" rel=\"nofollow noreferrer\" title=\"Analog literals.\">Analog literals.</a></p>\n" }, { "answer_id": 312449, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 5, "selected": false, "text": "<p>A quite hidden feature is that you can define variables within an if condition, and its scope will span only over the if, and its else blocks:</p>\n\n<pre><code>if(int * p = getPointer()) {\n // do something\n}\n</code></pre>\n\n<p>Some macros use that, for example to provide some \"locked\" scope like this:</p>\n\n<pre><code>struct MutexLocker { \n MutexLocker(Mutex&amp;);\n ~MutexLocker(); \n operator bool() const { return false; } \nprivate:\n Mutex &amp;m;\n};\n\n#define locked(mutex) if(MutexLocker const&amp; lock = MutexLocker(mutex)) {} else \n\nvoid someCriticalPath() {\n locked(myLocker) { /* ... */ }\n}\n</code></pre>\n\n<p>Also BOOST_FOREACH uses it under the hood. To complete this, it's not only possible in an if, but also in a switch:</p>\n\n<pre><code>switch(int value = getIt()) {\n // ...\n}\n</code></pre>\n\n<p>and in a while loop:</p>\n\n<pre><code>while(SomeThing t = getSomeThing()) {\n // ...\n}\n</code></pre>\n\n<p>(and also in a for condition). But i'm not too sure whether these are all that useful :)</p>\n" }, { "answer_id": 409233, "author": "Özgür", "author_id": 12652, "author_profile": "https://Stackoverflow.com/users/12652", "pm_score": 2, "selected": false, "text": "<p>From <a href=\"http://cpptruths.blogspot.com/2008/01/function-template-overload-resolution.html\" rel=\"nofollow noreferrer\">C++ Truths</a>.</p>\n\n<p>Defining functions having identical signatures in the same scope, so this is legal:</p>\n\n<pre><code>template&lt;class T&gt; // (a) a base template\nvoid f(T) {\n std::cout &lt;&lt; \"f(T)\\n\";\n}\n\ntemplate&lt;&gt;\nvoid f&lt;&gt;(int*) { // (b) an explicit specialization\n std::cout &lt;&lt; \"f(int *) specilization\\n\";\n}\n\ntemplate&lt;class T&gt; // (c) another, overloads (a)\nvoid f(T*) {\n std::cout &lt;&lt; \"f(T *)\\n\";\n}\n\ntemplate&lt;&gt;\nvoid f&lt;&gt;(int*) { // (d) another identical explicit specialization\n std::cout &lt;&lt; \"f(int *) another specilization\\n\";\n}\n</code></pre>\n" }, { "answer_id": 421854, "author": "Özgür", "author_id": 12652, "author_profile": "https://Stackoverflow.com/users/12652", "pm_score": 1, "selected": false, "text": "<p>If operator delete() takes size argument in addition to *void, that means it will, highly, be a base class. That size argument render possible checking the size of the types in order to destroy the correct one. Here what <a href=\"http://semantics.org/commonknowledge/index.html\" rel=\"nofollow noreferrer\">Stephen Dewhurst</a> tells about this:</p>\n\n<blockquote>\n <p>Notice also that we've employed a\n two-argument version of operator\n delete rather than the usual\n one-argument version. This\n two-argument version is another\n \"usual\" version of member operator\n delete often employed by base classes\n that expect derived classes to inherit\n their operator delete implementation.\n The second argument will contain the\n size of the object being\n deleted—information that is often\n useful in implementing custom memory\n management.</p>\n</blockquote>\n" }, { "answer_id": 421896, "author": "Eclipse", "author_id": 8701, "author_profile": "https://Stackoverflow.com/users/8701", "pm_score": 4, "selected": false, "text": "<p>One of the most interesting grammars of any programming languages.</p>\n\n<p>Three of these things belong together, and two are something altogether different...</p>\n\n<pre><code>SomeType t = u;\nSomeType t(u);\nSomeType t();\nSomeType t;\nSomeType t(SomeType(u));\n</code></pre>\n\n<p>All but the third and fifth define a <code>SomeType</code> object on the stack and initialize it (with <code>u</code> in the first two case, and the default constructor in the fourth. The third is declaring a function that takes no parameters and returns a <code>SomeType</code>. The fifth is similarly declaring a function that takes one parameter by value of type <code>SomeType</code> named <code>u</code>.</p>\n" }, { "answer_id": 432333, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 6, "selected": false, "text": "<p>One thing that's little known is that unions can be templates too:</p>\n\n<pre><code>template&lt;typename From, typename To&gt;\nunion union_cast {\n From from;\n To to;\n\n union_cast(From from)\n :from(from) { }\n\n To getTo() const { return to; }\n};\n</code></pre>\n\n<p>And they can have constructors and member functions too. Just nothing that has to do with inheritance (including virtual functions). </p>\n" }, { "answer_id": 456773, "author": "Özgür", "author_id": 12652, "author_profile": "https://Stackoverflow.com/users/12652", "pm_score": 4, "selected": false, "text": "<p>Defining ordinary friend functions in class templates needs special attention:</p>\n\n<pre><code>template &lt;typename T&gt; \nclass Creator { \n friend void appear() { // a new function ::appear(), but it doesn't \n … // exist until Creator is instantiated \n } \n};\nCreator&lt;void&gt; miracle; // ::appear() is created at this point \nCreator&lt;double&gt; oops; // ERROR: ::appear() is created a second time! \n</code></pre>\n\n<p>In this example, two different instantiations create two identical definitions—a direct violation of the <a href=\"http://en.wikipedia.org/wiki/One_Definition_Rule\" rel=\"noreferrer\">ODR</a> </p>\n\n<p>We must therefore make sure the template parameters of the class template appear in the type of any friend function defined in that template (unless we want to prevent more than one instantiation of a class template in a particular file, but this is rather unlikely). Let's apply this to a variation of our previous example:</p>\n\n<pre><code>template &lt;typename T&gt; \nclass Creator { \n friend void feed(Creator&lt;T&gt;*){ // every T generates a different \n … // function ::feed() \n } \n}; \n\nCreator&lt;void&gt; one; // generates ::feed(Creator&lt;void&gt;*) \nCreator&lt;double&gt; two; // generates ::feed(Creator&lt;double&gt;*) \n</code></pre>\n\n<p>Disclaimer: I have pasted this section from <a href=\"https://rads.stackoverflow.com/amzn/click/com/0201734842\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">C++ Templates: The Complete Guide</a> / Section 8.4</p>\n" }, { "answer_id": 456787, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>A dangerous secret is</p>\n\n<pre><code>Fred* f = new(ram) Fred(); http://www.parashift.com/c++-faq-lite/dtors.html#faq-11.10\nf-&gt;~Fred();\n</code></pre>\n\n<p>My favorite secret I rarely see used:</p>\n\n<pre><code>class A\n{\n};\n\nstruct B\n{\n A a;\n operator A&amp;() { return a; }\n};\n\nvoid func(A a) { }\n\nint main()\n{\n A a, c;\n B b;\n a=c;\n func(b); //yeah baby\n a=b; //gotta love this\n}\n</code></pre>\n" }, { "answer_id": 572900, "author": "dirkgently", "author_id": 66692, "author_profile": "https://Stackoverflow.com/users/66692", "pm_score": 0, "selected": false, "text": "<pre><code>class Empty {};\n\nnamespace std {\n // #1 specializing from std namespace is okay under certain circumstances\n template&lt;&gt;\n void swap&lt;Empty&gt;(Empty&amp;, Empty&amp;) {} \n}\n\n/* #2 The following function has no arguments. \n There is no 'unknown argument list' as we do\n in C.\n*/\nvoid my_function() { \n cout &lt;&lt; \"whoa! an error\\n\"; // #3 using can be scoped, as it is in main below\n // and this doesn't affect things outside of that scope\n}\n\nint main() {\n using namespace std; /* #4 you can use using in function scopes */\n cout &lt;&lt; sizeof(Empty) &lt;&lt; \"\\n\"; /* #5 sizeof(Empty) is never 0 */\n /* #6 falling off of main without an explicit return means \"return 0;\" */\n}\n</code></pre>\n" }, { "answer_id": 674995, "author": "Özgür", "author_id": 12652, "author_profile": "https://Stackoverflow.com/users/12652", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://www.devx.com/cplus/10MinuteSolution/32145/0/page/1\" rel=\"nofollow noreferrer\">Indirect Conversion Idiom</a>:</p>\n\n<blockquote>\n <p>Suppose you're designing a smart\n pointer class. In addition to\n overloading the operators * and ->, a\n smart pointer class usually defines a\n conversion operator to bool:</p>\n</blockquote>\n\n<pre><code>template &lt;class T&gt;\nclass Ptr\n{\npublic:\n operator bool() const\n {\n return (rawptr ? true: false);\n }\n//..more stuff\nprivate:\n T * rawptr;\n};\n</code></pre>\n\n<blockquote>\n <p>The conversion to bool enables clients\n to use smart pointers in expressions\n that require bool operands:</p>\n</blockquote>\n\n<pre><code>Ptr&lt;int&gt; ptr(new int);\nif(ptr ) //calls operator bool()\n cout&lt;&lt;\"int value is: \"&lt;&lt;*ptr &lt;&lt;endl;\nelse\n cout&lt;&lt;\"empty\"&lt;&lt;endl;\n</code></pre>\n\n<blockquote>\n <p>Furthermore, the implicit conversion\n to bool is required in conditional\n declarations such as:</p>\n</blockquote>\n\n<pre><code>if (shared_ptr&lt;X&gt; px = dynamic_pointer_cast&lt;X&gt;(py))\n{\n //we get here only of px isn't empty\n} \n</code></pre>\n\n<blockquote>\n <p>Alas, this automatic conversion opens\n the gate to unwelcome surprises:</p>\n</blockquote>\n\n<pre><code>Ptr &lt;int&gt; p1;\nPtr &lt;double&gt; p2;\n\n//surprise #1\ncout&lt;&lt;\"p1 + p2 = \"&lt;&lt; p1+p2 &lt;&lt;endl; \n//prints 0, 1, or 2, although there isn't an overloaded operator+()\n\nPtr &lt;File&gt; pf;\nPtr &lt;Query&gt; pq; // Query and File are unrelated \n\n//surprise #2\nif(pf==pq) //compares bool values, not pointers! \n</code></pre>\n\n<p>Solution: Use the \"indirect conversion\" idiom, by a conversion from pointer to data member[pMember] to bool so that there will be only 1 implicit conversion, which will prevent aforementioned unexpected behaviour: pMember->bool rather that bool->something else.</p>\n" }, { "answer_id": 691496, "author": "Özgür", "author_id": 12652, "author_profile": "https://Stackoverflow.com/users/12652", "pm_score": 2, "selected": false, "text": "<p>Pay attention to difference between free function pointer and member function pointer initializations:</p>\n\n<p>member function:</p>\n\n<pre><code>struct S\n{\n void func(){};\n};\nint main(){\nvoid (S::*pmf)()=&amp;S::func;// &amp; is mandatory\n}\n</code></pre>\n\n<p>and free function:</p>\n\n<pre><code>void func(int){}\nint main(){\nvoid (*pf)(int)=func; // &amp; is unnecessary it can be &amp;func as well; \n}\n</code></pre>\n\n<p>Thanks to this redundant &amp;, you can add stream manipulators-which are free functions- in chain without it:</p>\n\n<pre><code>cout&lt;&lt;hex&lt;&lt;56; //otherwise you would have to write cout&lt;&lt;&amp;hex&lt;&lt;56, not neat.\n</code></pre>\n" }, { "answer_id": 730018, "author": "Özgür", "author_id": 12652, "author_profile": "https://Stackoverflow.com/users/12652", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/questions/257288/possible-for-c-template-to-check-for-a-functions-existence\">Is it possible for C++ template to check for a function’s existence?</a></p>\n" }, { "answer_id": 754133, "author": "Özgür", "author_id": 12652, "author_profile": "https://Stackoverflow.com/users/12652", "pm_score": -1, "selected": false, "text": "<p>Emulating <strong>reinterpret cast</strong> with <strong>static cast</strong> :</p>\n\n<pre><code>int var;\nstring *str = reinterpret_cast&lt;string*&gt;(&amp;var);\n</code></pre>\n\n<p>the above code is equivalent to following:</p>\n\n<pre><code>int var; \nstring *str = static_cast&lt;string*&gt;(static_cast&lt;void*&gt;(&amp;var));\n</code></pre>\n" }, { "answer_id": 876180, "author": "a_m0d", "author_id": 106762, "author_profile": "https://Stackoverflow.com/users/106762", "pm_score": 1, "selected": false, "text": "<p>The class and struct class-keys are nearly identical. The main difference is that classes default to private access for members and bases, while structs default to public:</p>\n\n<pre><code>// this is completely valid C++:\nclass A;\nstruct A { virtual ~A() = 0; };\nclass B : public A { public: virtual ~B(); };\n\n// means the exact same as:\nstruct A;\nclass A { public: virtual ~A() = 0; };\nstruct B : A { virtual ~B(); };\n\n// you can't even tell the difference from other code whether 'struct'\n// or 'class' was used for A and B\n</code></pre>\n\n<p>Unions can also have members and methods, and default to public access similarly to structs.</p>\n" }, { "answer_id": 889001, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 7, "selected": false, "text": "<p>Not only can variables be declared in the init part of a <code>for</code> loop, but also classes and functions. </p>\n\n<pre><code>for(struct { int a; float b; } loop = { 1, 2 }; ...; ...) {\n ...\n}\n</code></pre>\n\n<p>That allows for multiple variables of differing types.</p>\n" }, { "answer_id": 903449, "author": "Özgür", "author_id": 12652, "author_profile": "https://Stackoverflow.com/users/12652", "pm_score": 0, "selected": false, "text": "<p>Adding <a href=\"https://stackoverflow.com/questions/122316/template-constraints-c\">constraints</a> to templates.</p>\n" }, { "answer_id": 1029069, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>Primitive types have constructors.</p>\n\n<pre><code>int i(3);\n</code></pre>\n\n<p>works.</p>\n" }, { "answer_id": 1064070, "author": "vobject", "author_id": 53911, "author_profile": "https://Stackoverflow.com/users/53911", "pm_score": 2, "selected": false, "text": "<p>It seems to me that only few people know about unnamed namespaces: </p>\n\n<pre><code>namespace {\n // Classes, functions, and objects here.\n}\n</code></pre>\n\n<p>Unnamed namespaces behave as if they was replaced by:</p>\n\n<pre><code>namespace __unique_name__ { /* empty body */ }\nusing namespace __unique_name__;\nnamespace __unique_name__ {\n // original namespace body\n}\n</code></pre>\n\n<p>\".. where all occurances of [this unique name] in a translation unit are replaced by the same identifier and this identifier differs from all other identifiers in the entire program.\" [C++03, 7.3.1.1/1]</p>\n" }, { "answer_id": 1065606, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 5, "selected": false, "text": "<p>You can access protected data and function members of any class, without undefined behavior, and with expected semantics. Read on to see how. Read also <a href=\"http://tinyurl.com/defect-report\" rel=\"nofollow noreferrer\">the defect report</a> about this. </p>\n\n<p>Normally, C++ forbids you to access non-static protected members of a class's object, even if that class is your base class</p>\n\n<pre><code>struct A {\nprotected:\n int a;\n};\n\nstruct B : A {\n // error: can't access protected member\n static int get(A &amp;x) { return x.a; }\n};\n\nstruct C : A { };\n</code></pre>\n\n<p>That's forbidden: You and the compiler don't know what the reference actually points at. It could be a <code>C</code> object, in which case class <code>B</code> has no business and clue about its data. Such access is only granted if <code>x</code> is a reference to a derived class or one derived from it. And it could allow arbitrary piece of code to read any protected member by just making up a \"throw-away\" class that reads out members, for example of <code>std::stack</code>:</p>\n\n<pre><code>void f(std::stack&lt;int&gt; &amp;s) {\n // now, let's decide to mess with that stack!\n struct pillager : std::stack&lt;int&gt; {\n static std::deque&lt;int&gt; &amp;get(std::stack&lt;int&gt; &amp;s) {\n // error: stack&lt;int&gt;::c is protected\n return s.c;\n }\n };\n\n // haha, now let's inspect the stack's middle elements!\n std::deque&lt;int&gt; &amp;d = pillager::get(s);\n}\n</code></pre>\n\n<p>Surely, as you see this would cause way too much damage. But now, member pointers allow circumventing this protection! The key point is that the type of a member pointer is bound to the class that actually contains said member - <em>not</em> to the class that you specified when taking the address. This allows us to circumvent checking</p>\n\n<pre><code>struct A {\nprotected:\n int a;\n};\n\nstruct B : A {\n // valid: *can* access protected member\n static int get(A &amp;x) { return x.*(&amp;B::a); }\n};\n\nstruct C : A { };\n</code></pre>\n\n<p>And of course, it also works with the <code>std::stack</code> example. </p>\n\n<pre><code>void f(std::stack&lt;int&gt; &amp;s) {\n // now, let's decide to mess with that stack!\n struct pillager : std::stack&lt;int&gt; {\n static std::deque&lt;int&gt; &amp;get(std::stack&lt;int&gt; &amp;s) {\n return s.*(pillager::c);\n }\n };\n\n // haha, now let's inspect the stack's middle elements!\n std::deque&lt;int&gt; &amp;d = pillager::get(s);\n}\n</code></pre>\n\n<p>That's going to be even easier with a using declaration in the derived class, which makes the member name public and refers to the member of the base class. </p>\n\n<pre><code>void f(std::stack&lt;int&gt; &amp;s) {\n // now, let's decide to mess with that stack!\n struct pillager : std::stack&lt;int&gt; {\n using std::stack&lt;int&gt;::c;\n };\n\n // haha, now let's inspect the stack's middle elements!\n std::deque&lt;int&gt; &amp;d = s.*(&amp;pillager::c);\n}\n</code></pre>\n" }, { "answer_id": 1402670, "author": "Kamil Szot", "author_id": 166921, "author_profile": "https://Stackoverflow.com/users/166921", "pm_score": 0, "selected": false, "text": "<p>Member pointers and member pointer operator ->* </p>\n\n<pre><code>#include &lt;stdio.h&gt;\nstruct A { int d; int e() { return d; } };\nint main() {\n A* a = new A();\n a-&gt;d = 8;\n printf(\"%d %d\\n\", a -&gt;* &amp;A::d, (a -&gt;* &amp;A::e)() );\n return 0;\n}\n</code></pre>\n\n<p>For methods (a ->* &amp;A::e)() is a bit like Function.call() from javascript </p>\n\n<pre><code>var f = A.e\nf.call(a) \n</code></pre>\n\n<p>For members it's a bit like accessing with [] operator </p>\n\n<pre><code>a['d']\n</code></pre>\n" }, { "answer_id": 1414869, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 5, "selected": false, "text": "<p>Many know of the <code>identity</code> / <code>id</code> metafunction, but there is a nice usecase for it for non-template cases: Ease writing declarations:</p>\n\n<pre><code>// void (*f)(); // same\nid&lt;void()&gt;::type *f;\n\n// void (*f(void(*p)()))(int); // same\nid&lt;void(int)&gt;::type *f(id&lt;void()&gt;::type *p);\n\n// int (*p)[2] = new int[10][2]; // same\nid&lt;int[2]&gt;::type *p = new int[10][2];\n\n// void (C::*p)(int) = 0; // same\nid&lt;void(int)&gt;::type C::*p = 0;\n</code></pre>\n\n<p>It helps decrypting C++ declarations greatly!</p>\n\n<pre><code>// boost::identity is pretty much the same\ntemplate&lt;typename T&gt; \nstruct id { typedef T type; };\n</code></pre>\n" }, { "answer_id": 1465581, "author": "sdcvvc", "author_id": 100020, "author_profile": "https://Stackoverflow.com/users/100020", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://www.reddit.com/r/programming/comments/96aku/in_c_throw_is_an_expression/\" rel=\"nofollow noreferrer\">throw is an expression</a></p>\n" }, { "answer_id": 1573354, "author": "Macke", "author_id": 72312, "author_profile": "https://Stackoverflow.com/users/72312", "pm_score": 1, "selected": false, "text": "<p>I find recursive template instatiations pretty cool:</p>\n\n<pre><code>template&lt;class int&gt;\nclass foo;\n\ntemplate\nclass foo&lt;0&gt; {\n int* get&lt;0&gt;() { return array; }\n int* array; \n};\n\ntemplate&lt;class int&gt;\nclass foo&lt;i&gt; : public foo&lt;i-1&gt; {\n int* get&lt;i&gt;() { return array + 1; } \n};\n</code></pre>\n\n<p>I've used that to generate a class with 10-15 functions that return pointers into various parts of an array, since an API I used required one function pointer for each value.</p>\n\n<p>I.e. programming the compiler to generate a bunch of functions, via recursion. Easy as pie. :)</p>\n" }, { "answer_id": 1771776, "author": "Jeffrey Faust", "author_id": 215580, "author_profile": "https://Stackoverflow.com/users/215580", "pm_score": 2, "selected": false, "text": "<p>main() does not need a return value:</p>\n\n<pre><code>int main(){}\n</code></pre>\n\n<p>is the shortest valid C++ program.</p>\n" }, { "answer_id": 1771843, "author": "Kaz Dragon", "author_id": 24913, "author_profile": "https://Stackoverflow.com/users/24913", "pm_score": 4, "selected": false, "text": "<p>You can template bitfields.</p>\n\n<pre><code>template &lt;size_t X, size_t Y&gt;\nstruct bitfield\n{\n char left : X;\n char right : Y;\n};\n</code></pre>\n\n<p>I have yet to come up with any purpose for this, but it sure as heck surprised me.</p>\n" }, { "answer_id": 1966865, "author": "Rune FS", "author_id": 112407, "author_profile": "https://Stackoverflow.com/users/112407", "pm_score": 0, "selected": false, "text": "<p>My favorite (for the time being) is the lack of sematics in a statement like \nA=B=C. What the value of A is basically undetermined.</p>\n\n<p>Think of this:</p>\n\n<pre><code>class clC\n{\npublic:\n clC&amp; operator=(const clC&amp; other)\n {\n //do some assignment stuff\n return copy(other);\n }\n virtual clC&amp; copy(const clC&amp; other);\n}\n\nclass clB : public clC\n{\npublic:\n clB() : m_copy()\n {\n }\n\n clC&amp; copy(const clC&amp; other)\n {\n return m_copy;\n }\n\nprivate:\n class clInnerB : public clC\n {\n }\n clInnerB m_copy;\n}\n</code></pre>\n\n<p>now A might be of a type inaccessible to any other than objects of type clB and have a value that's unrelated to C.</p>\n" }, { "answer_id": 2176229, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 4, "selected": false, "text": "<h3>void functions can return void values</h3>\n\n<p>Little known, but the following code is fine</p>\n\n<pre><code>void f() { }\nvoid g() { return f(); }\n</code></pre>\n\n<p>Aswell as the following weird looking one</p>\n\n<pre><code>void f() { return (void)\"i'm discarded\"; }\n</code></pre>\n\n<p>Knowing about this, you can take advantage in some areas. One example: <code>void</code> functions can't return a value but you can also not just return nothing, because they may be instantiated with non-void. Instead of storing the value into a local variable, which will cause an error for <code>void</code>, just return a value directly</p>\n\n<pre><code>template&lt;typename T&gt;\nstruct sample {\n // assume f&lt;T&gt; may return void\n T dosomething() { return f&lt;T&gt;(); }\n\n // better than T t = f&lt;T&gt;(); /* ... */ return t; !\n};\n</code></pre>\n" }, { "answer_id": 2176258, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 5, "selected": false, "text": "<h3>Preventing comma operator from calling operator overloads</h3>\n\n<p>Sometimes you make valid use of the comma operator, but you want to ensure that no user defined comma operator gets into the way, because for instance you rely on sequence points between the left and right side or want to make sure nothing interferes with the desired action. This is where <code>void()</code> comes into game:</p>\n\n<pre><code>for(T i, j; can_continue(i, j); ++i, void(), ++j)\n do_code(i, j);\n</code></pre>\n\n<p>Ignore the place holders i put for the condition and code. What's important is the <code>void()</code>, which makes the compiler force to use the builtin comma operator. This can be useful when implementing traits classes, sometimes, too. </p>\n" }, { "answer_id": 2339965, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>You can view all the predefined macros through command-line switches with some compilers. This works with gcc and icc (Intel's C++ compiler):</p>\n\n<pre><code>$ touch empty.cpp\n$ g++ -E -dM empty.cpp | sort &gt;gxx-macros.txt\n$ icc -E -dM empty.cpp | sort &gt;icx-macros.txt\n$ touch empty.c\n$ gcc -E -dM empty.c | sort &gt;gcc-macros.txt\n$ icc -E -dM empty.c | sort &gt;icc-macros.txt\n</code></pre>\n\n<p>For MSVC they are listed in a <a href=\"http://msdn.microsoft.com/en-us/library/b0084kay%28VS.80%29.aspx\" rel=\"nofollow noreferrer\">single place</a>. They could be documented in a single place for the others too, but with the above commands you can clearly <em>see</em> what is and isn't defined and exactly what values are used, after applying all of the other command-line switches.</p>\n\n<p>Compare (after sorting):</p>\n\n<pre><code> $ diff gxx-macros.txt icx-macros.txt\n $ diff gxx-macros.txt gcc-macros.txt\n $ diff icx-macros.txt icc-macros.txt\n</code></pre>\n" }, { "answer_id": 2339999, "author": "AnT stands with Russia", "author_id": 187690, "author_profile": "https://Stackoverflow.com/users/187690", "pm_score": 4, "selected": false, "text": "<p>The ternary conditional operator <code>?:</code> requires its second and third operand to have \"agreeable\" types (speaking informally). But this requirement has one exception (pun intended): either the second or third operand can be a throw expression (which has type <code>void</code>), regardless of the type of the other operand.</p>\n\n<p>In other words, one can write the following pefrectly valid C++ expressions using the <code>?:</code> operator</p>\n\n<pre><code>i = a &gt; b ? a : throw something();\n</code></pre>\n\n<p>BTW, the fact that throw expression is actually <em>an expression</em> (of type <code>void</code>) and not a statement is another little-known feature of C++ language. This means, among other things, that the following code is perfectly valid</p>\n\n<pre><code>void foo()\n{\n return throw something();\n}\n</code></pre>\n\n<p>although there's not much point in doing it this way (maybe in some generic template code this might come handy).</p>\n" }, { "answer_id": 2340305, "author": "Viktor Sehr", "author_id": 100724, "author_profile": "https://Stackoverflow.com/users/100724", "pm_score": 2, "selected": false, "text": "<ol>\n<li><p><code>map::insert(std::pair(key, value));</code> doesn't overwrite if key value already exists. </p></li>\n<li><p>You can instantiate a class right after its definition:\n(I might add that this feature has given me hundreds of compilation errors because of the missing semicolon, and I've never ever seen anyone use this on classes)</p>\n\n<pre><code>class MyClass {public: /* code */} myClass;\n</code></pre></li>\n</ol>\n" }, { "answer_id": 2340449, "author": "aheld", "author_id": 259873, "author_profile": "https://Stackoverflow.com/users/259873", "pm_score": -1, "selected": false, "text": "<p>I know somebody who defines a getter and a setter at the same time with only one method. Like this:</p>\n\n<pre><code>class foo\n{\n int x;\n\n int* GetX(){\n return &amp;x;\n }\n}\n</code></pre>\n\n<p>You can now use this as a getter as usual (well, almost):</p>\n\n<pre><code>int a = *GetX();\n</code></pre>\n\n<p>and as a setter:</p>\n\n<pre><code>*GetX() = 17;\n</code></pre>\n" }, { "answer_id": 2520439, "author": "osgx", "author_id": 196561, "author_profile": "https://Stackoverflow.com/users/196561", "pm_score": -1, "selected": false, "text": "<p>Template metaprogramming is.</p>\n" }, { "answer_id": 2912402, "author": "mihai", "author_id": 350838, "author_profile": "https://Stackoverflow.com/users/350838", "pm_score": -1, "selected": false, "text": "<p>Not actually a hidden feature, but pure awesomeness:</p>\n\n<pre><code>#define private public \n</code></pre>\n" }, { "answer_id": 3056080, "author": "Martín Fixman", "author_id": 305597, "author_profile": "https://Stackoverflow.com/users/305597", "pm_score": -1, "selected": false, "text": "<p>You can return a variable reference as part of a function. It has some uses, mostly for producing horrible code:</p>\n\n<pre><code>int s ;\nvector &lt;int&gt; a ;\nvector &lt;int&gt; b ;\n\nint &amp;G(int h)\n{\n if ( h &lt; a.size() ) return a[h] ;\n if ( h - a.size() &lt; b.size() ) return b[ h - a.size() ] ;\n return s ;\n}\n\nint main()\n{\n a = vector &lt;int&gt; (100) ;\n b = vector &lt;int&gt; (100) ;\n\n G( 20) = 40 ; //a[20] becomes 40\n G(120) = 40 ; //b[20] becomes 40\n G(424) = 40 ; //s becomes 40\n}\n</code></pre>\n" }, { "answer_id": 3100801, "author": "Alexandre C.", "author_id": 373025, "author_profile": "https://Stackoverflow.com/users/373025", "pm_score": 3, "selected": false, "text": "<p>Local classes are awesome :</p>\n\n<pre><code>struct MyAwesomeAbstractClass\n{ ... };\n\n\ntemplate &lt;typename T&gt;\nMyAwesomeAbstractClass*\ncreate_awesome(T param)\n{\n struct ans : MyAwesomeAbstractClass\n {\n // Make the implementation depend on T\n };\n\n return new ans(...);\n}\n</code></pre>\n\n<p>quite neat, since it doesn't pollute the namespace with useless class definitions...</p>\n" }, { "answer_id": 3176148, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 3, "selected": false, "text": "<p>One hidden feature, even hidden to the <a href=\"http://gcc.gnu.org/bugzilla/show_bug.cgi?id=43453\" rel=\"nofollow noreferrer\">GCC developers</a>, is to initialize an array member using a string literal. Suppose you have a structure that needs to work with a C array, and you want to initialize the array member with a default content</p>\n\n<pre><code>struct Person {\n char name[255];\n Person():name(\"???\") { }\n};\n</code></pre>\n\n<p>This works, and only works with char arrays and string literal initializers. No <code>strcpy</code> is needed!</p>\n" }, { "answer_id": 3176186, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 5, "selected": false, "text": "<p>Another hidden feature is that you can call class objects that can be converted to function pointers or references. Overload resolution is done on the result of them, and arguments are perfectly forwarded.</p>\n\n<pre><code>template&lt;typename Func1, typename Func2&gt;\nclass callable {\n Func1 *m_f1;\n Func2 *m_f2;\n\npublic:\n callable(Func1 *f1, Func2 *f2):m_f1(f1), m_f2(f2) { }\n operator Func1*() { return m_f1; }\n operator Func2*() { return m_f2; }\n};\n\nvoid foo(int i) { std::cout &lt;&lt; \"foo: \" &lt;&lt; i &lt;&lt; std::endl; }\nvoid bar(long il) { std::cout &lt;&lt; \"bar: \" &lt;&lt; il &lt;&lt; std::endl; }\n\nint main() {\n callable&lt;void(int), void(long)&gt; c(foo, bar);\n c(42); // calls foo\n c(42L); // calls bar\n}\n</code></pre>\n\n<p>These are called \"surrogate call functions\". </p>\n" }, { "answer_id": 3182557, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 6, "selected": false, "text": "<p>Another hidden feature that doesn't work in C is the functionality of the unary <code>+</code> operator. You can use it to promote and decay all sorts of things</p>\n\n<h3>Converting an Enumeration to an integer</h3>\n\n<pre><code>+AnEnumeratorValue\n</code></pre>\n\n<p>And your enumerator value that previously had its enumeration type now has the perfect integer type that can fit its value. Manually, you would hardly know that type! This is needed for example when you want to implement an overloaded operator for your enumeration. </p>\n\n<h3>Get the value out of a variable</h3>\n\n<p>You have to use a class that uses an in-class static initializer without an out of class definition, but sometimes it fails to link? The operator may help to create a temporary without making assumptins or dependencies on its type</p>\n\n<pre><code>struct Foo {\n static int const value = 42;\n};\n\n// This does something interesting...\ntemplate&lt;typename T&gt;\nvoid f(T const&amp;);\n\nint main() {\n // fails to link - tries to get the address of \"Foo::value\"!\n f(Foo::value);\n\n // works - pass a temporary value\n f(+Foo::value);\n}\n</code></pre>\n\n<h3>Decay an array to a pointer</h3>\n\n<p>Do you want to pass two pointers to a function, but it just won't work? The operator may help</p>\n\n<pre><code>// This does something interesting...\ntemplate&lt;typename T&gt;\nvoid f(T const&amp; a, T const&amp; b);\n\nint main() {\n int a[2];\n int b[3];\n f(a, b); // won't work! different values for \"T\"!\n f(+a, +b); // works! T is \"int*\" both time\n}\n</code></pre>\n" }, { "answer_id": 3189052, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 4, "selected": false, "text": "<p>The dominance rule is useful, but little known. It says that even if in a non-unique path through a base-class lattice, name-lookup for a partially hidden member is unique if the member belongs to a virtual base-class:</p>\n\n<pre><code>struct A { void f() { } };\n\nstruct B : virtual A { void f() { cout &lt;&lt; \"B!\"; } };\nstruct C : virtual A { };\n\n// name-lookup sees B::f and A::f, but B::f dominates over A::f !\nstruct D : B, C { void g() { f(); } };\n</code></pre>\n\n<p>I've used this to <a href=\"https://stackoverflow.com/questions/2366879/operator-new-overloading-and-alignment/2366998#2366998\">implement alignment-support</a> that automatically figures out the strictest alignment by means of the dominance rule. </p>\n\n<p><em>This does not only apply to virtual functions, but also to typedef names, static/non-virtual members and anything else.</em> I've seen it used to implement overwritable traits in meta-programs. </p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/75538", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2328/" ]
No C++ love when it comes to the "hidden features of" line of questions? Figured I would throw it out there. What are some of the hidden features of C++?
You can put URIs into C++ source without error. For example: ``` void foo() { http://stackoverflow.com/ int bar = 4; ... } ```
75,608
<p>I'm working on a product feature that will allow the user to export data from a SQL CE database on one copy of my application and re-import it into SQL CE on the other end. This data is not whole tables, but the result of queries.</p> <p>I had hoped to take advantage of .net's built-in XML-based serialization like in DataTable.WriteXML. But, none of the methods for executing queries against a SqlCeCommand provide an obvious way of serializing to XML or extracting a DataTable, which could provide the method.</p> <p>Is there something I'm missing? Do I have to write my own serialization-deserialization methods or is there a built-in way.</p>
[ { "answer_id": 75651, "author": "Grank", "author_id": 12975, "author_profile": "https://Stackoverflow.com/users/12975", "pm_score": 0, "selected": false, "text": "<p>I would think you could retrieve the data to a DataSet, call WriteXML on it, and then on the other end declare a new DataSet and call ReadXML on it.</p>\n" }, { "answer_id": 75681, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 1, "selected": false, "text": "<p>You want to create an <code>SqlCeDataAdapter</code> and use it <code>.Fill()</code> a dataset. Then serialize the entire dataset via it's <code>.WriteXml()</code> method.</p>\n" }, { "answer_id": 75702, "author": "Jonathan Rupp", "author_id": 12502, "author_profile": "https://Stackoverflow.com/users/12502", "pm_score": 3, "selected": true, "text": "<p>Assuming cmd is your SqlCeCommand....</p>\n\n<pre><code>using(var dr = cmd.ExecuteReader())\n{\n DataSet ds = new DataSet();\n DataTable dt = ds.Tables.Add();\n dt.Load(dr);\n ds.WriteXML(...);\n}\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/75608", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5287/" ]
I'm working on a product feature that will allow the user to export data from a SQL CE database on one copy of my application and re-import it into SQL CE on the other end. This data is not whole tables, but the result of queries. I had hoped to take advantage of .net's built-in XML-based serialization like in DataTable.WriteXML. But, none of the methods for executing queries against a SqlCeCommand provide an obvious way of serializing to XML or extracting a DataTable, which could provide the method. Is there something I'm missing? Do I have to write my own serialization-deserialization methods or is there a built-in way.
Assuming cmd is your SqlCeCommand.... ``` using(var dr = cmd.ExecuteReader()) { DataSet ds = new DataSet(); DataTable dt = ds.Tables.Add(); dt.Load(dr); ds.WriteXML(...); } ```
75,614
<p>The following question answers how to get large memory pages on Windows :<br> "<a href="https://stackoverflow.com/questions/39059/how-do-i-run-my-app-with-large-pages-in-windows">how do i run my app with large pages in windows</a>".</p> <p>The problem I'm trying to solve is how do I configure it on Vista and 2008 Server.</p> <p>Normally you just allow a specific user to lock pages in memory and you are done. However on Vista and 2008 this only works if you are using an Administrator account. It doesn't help if the user is actually part of the Administrators group. All other users always get a 1300 error code stating that some rights are missing.</p> <p>Anyone have a clue as to what else needs to be configured?</p> <p>Thanks, Staffan</p>
[ { "answer_id": 75651, "author": "Grank", "author_id": 12975, "author_profile": "https://Stackoverflow.com/users/12975", "pm_score": 0, "selected": false, "text": "<p>I would think you could retrieve the data to a DataSet, call WriteXML on it, and then on the other end declare a new DataSet and call ReadXML on it.</p>\n" }, { "answer_id": 75681, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 1, "selected": false, "text": "<p>You want to create an <code>SqlCeDataAdapter</code> and use it <code>.Fill()</code> a dataset. Then serialize the entire dataset via it's <code>.WriteXml()</code> method.</p>\n" }, { "answer_id": 75702, "author": "Jonathan Rupp", "author_id": 12502, "author_profile": "https://Stackoverflow.com/users/12502", "pm_score": 3, "selected": true, "text": "<p>Assuming cmd is your SqlCeCommand....</p>\n\n<pre><code>using(var dr = cmd.ExecuteReader())\n{\n DataSet ds = new DataSet();\n DataTable dt = ds.Tables.Add();\n dt.Load(dr);\n ds.WriteXML(...);\n}\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/75614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8782/" ]
The following question answers how to get large memory pages on Windows : "[how do i run my app with large pages in windows](https://stackoverflow.com/questions/39059/how-do-i-run-my-app-with-large-pages-in-windows)". The problem I'm trying to solve is how do I configure it on Vista and 2008 Server. Normally you just allow a specific user to lock pages in memory and you are done. However on Vista and 2008 this only works if you are using an Administrator account. It doesn't help if the user is actually part of the Administrators group. All other users always get a 1300 error code stating that some rights are missing. Anyone have a clue as to what else needs to be configured? Thanks, Staffan
Assuming cmd is your SqlCeCommand.... ``` using(var dr = cmd.ExecuteReader()) { DataSet ds = new DataSet(); DataTable dt = ds.Tables.Add(); dt.Load(dr); ds.WriteXML(...); } ```
75,621
<p>I have a web report that uses a Django form (new forms) for fields that control the query used to generate the report (start date, end date, ...). The issue I'm having is that the page should work using the form's initial values (unbound), but I can't access the cleaned_data field unless I call <code>is_valid()</code>. But <code>is_valid()</code> always fails on unbound forms.</p> <p>It seems like Django's forms were designed with the use case of editing data such that an unbound form isn't really useful for anything other than displaying HTML.</p> <p>For example, if I have:</p> <pre><code>if request.method == 'GET': form = MyForm() else: form = MyForm(request.method.POST) if form.is_valid(): do_query(form.cleaned_data['start_date'], form.cleaned_data['end_date']) </code></pre> <p>is_valid() will fail if this is a GET (since it's unbound), and if I do:</p> <pre><code>if request.method == 'GET': form = MyForm() do_query(form.cleaned_data['start_date'], form.cleaned_data['end_date']) else: form = MyForm(request.method.POST) if form.is_valid(): do_query(form.cleaned_data['start_date'], form.cleaned_data['end_date']) </code></pre> <p>the first call to do_query triggers exceptions on form.cleaned_data, which is not a valid field because <code>is_valid()</code> has not been called. It seems like I have to do something like:</p> <pre><code>if request.method == 'GET': form = MyForm() do_query(form['start_date'].field.initial, form['end_date'].field.initial) else: form = MyForm(request.method.POST) if form.is_valid(): do_query(form.cleaned_data['start_date'], form.cleaned_data['end_date']) </code></pre> <p>that is, there isn't a common interface for retrieving the form's values between a bound form and an unbound one.</p> <p>Does anyone see a cleaner way to do this?</p>
[ { "answer_id": 75815, "author": "Justin Voss", "author_id": 5616, "author_profile": "https://Stackoverflow.com/users/5616", "pm_score": 0, "selected": false, "text": "<p>You can pass a dictionary of initial values to your form:</p>\n\n<pre><code>if request.method == \"GET\":\n # calculate my_start_date and my_end_date here...\n form = MyForm( { 'start_date': my_start_date, 'end_date': my_end_date} )\n...\n</code></pre>\n\n<p>See the <a href=\"http://docs.djangoproject.com/en/dev/ref/forms/api/\" rel=\"nofollow noreferrer\">official forms API documentation</a>, where they demonstrate this.</p>\n\n<p><strong>edit</strong>: Based on answers from other users, maybe this is the cleanest solution:</p>\n\n<pre><code>if request.method == \"GET\":\n form = MyForm()\n form['start_date'] = form['start_date'].field.initial\n form['end_date'] = form['end_date'].field.initial\nelse:\n form = MyForm(request.method.POST)\nif form.is_valid():\n do_query(form.cleaned_data['start_date'], form.cleaned_data['end_date'])\n</code></pre>\n\n<p>I haven't tried this though; can someone confirm that this works? I think this is better than creating a new method, because this approach doesn't require other code (possibly not written by you) to know about your new 'magic' accessor.</p>\n" }, { "answer_id": 75923, "author": "Matthew Christensen", "author_id": 2123, "author_profile": "https://Stackoverflow.com/users/2123", "pm_score": 4, "selected": true, "text": "<p>If you add this method to your form class:</p>\n\n<pre><code>def get_cleaned_or_initial(self, fieldname):\n if hasattr(self, 'cleaned_data'):\n return self.cleaned_data.get(fieldname)\n else:\n return self[fieldname].field.initial\n</code></pre>\n\n<p>you could then re-write your code as:</p>\n\n<pre><code>if request.method == 'GET':\n form = MyForm()\nelse:\n form = MyForm(request.method.POST)\n form.is_valid()\n\ndo_query(form.get_cleaned_or_initial('start_date'), form.get_cleaned_or_initial('end_date'))\n</code></pre>\n" }, { "answer_id": 81301, "author": "zgoda", "author_id": 12138, "author_profile": "https://Stackoverflow.com/users/12138", "pm_score": 2, "selected": false, "text": "<p><em>Unbound</em> means there is no data associated with form (either initial or provided later), so the validation may fail. As mentioned in other answers (and in your own conclusion), you have to provide initial values and check for both bound data and initial values.</p>\n\n<p>The use case for forms is form processing <strong>and</strong> validation, so you must have some data to validate before you accessing <code>cleaned_data</code>.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/75621", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8247/" ]
I have a web report that uses a Django form (new forms) for fields that control the query used to generate the report (start date, end date, ...). The issue I'm having is that the page should work using the form's initial values (unbound), but I can't access the cleaned\_data field unless I call `is_valid()`. But `is_valid()` always fails on unbound forms. It seems like Django's forms were designed with the use case of editing data such that an unbound form isn't really useful for anything other than displaying HTML. For example, if I have: ``` if request.method == 'GET': form = MyForm() else: form = MyForm(request.method.POST) if form.is_valid(): do_query(form.cleaned_data['start_date'], form.cleaned_data['end_date']) ``` is\_valid() will fail if this is a GET (since it's unbound), and if I do: ``` if request.method == 'GET': form = MyForm() do_query(form.cleaned_data['start_date'], form.cleaned_data['end_date']) else: form = MyForm(request.method.POST) if form.is_valid(): do_query(form.cleaned_data['start_date'], form.cleaned_data['end_date']) ``` the first call to do\_query triggers exceptions on form.cleaned\_data, which is not a valid field because `is_valid()` has not been called. It seems like I have to do something like: ``` if request.method == 'GET': form = MyForm() do_query(form['start_date'].field.initial, form['end_date'].field.initial) else: form = MyForm(request.method.POST) if form.is_valid(): do_query(form.cleaned_data['start_date'], form.cleaned_data['end_date']) ``` that is, there isn't a common interface for retrieving the form's values between a bound form and an unbound one. Does anyone see a cleaner way to do this?
If you add this method to your form class: ``` def get_cleaned_or_initial(self, fieldname): if hasattr(self, 'cleaned_data'): return self.cleaned_data.get(fieldname) else: return self[fieldname].field.initial ``` you could then re-write your code as: ``` if request.method == 'GET': form = MyForm() else: form = MyForm(request.method.POST) form.is_valid() do_query(form.get_cleaned_or_initial('start_date'), form.get_cleaned_or_initial('end_date')) ```
75,626
<p>I have a JSP page that contains a scriplet where I instantiate an object. I would like to pass that object to the JSP tag without using any cache. </p> <p>For example I would like to accomplish this: </p> <pre><code>&lt;%@ taglib prefix="wf" uri="JspCustomTag" %&gt; &lt;% Object myObject = new Object(); %&gt; &lt;wf:my-tag obj=myObject /&gt; </code></pre> <p>I'm trying to avoid directly interacting with any of the caches (page, session, servletcontext), I would rather have my tag handle that.</p>
[ { "answer_id": 75745, "author": "Brian Matthews", "author_id": 1969, "author_profile": "https://Stackoverflow.com/users/1969", "pm_score": 0, "selected": false, "text": "<p>Use expression language:</p>\n\n<pre>\n &lt;wf:my-tag obj=\"${myObject}\" /&gt;\n</pre>\n" }, { "answer_id": 75843, "author": "Garth Gilmour", "author_id": 2635682, "author_profile": "https://Stackoverflow.com/users/2635682", "pm_score": 3, "selected": false, "text": "<p>The original syntax was to reuse '&lt;%= %>'</p>\n\n<p>So</p>\n\n<pre><code>&lt;wf:my-tag obj=\"&lt;%= myObject %&gt;\" /&gt;\n</code></pre>\n\n<p>See <a href=\"http://java.sun.com/products/jsp/tutorial/TagLibraries16.html#62510\" rel=\"noreferrer\">this part of the Sun Tag Library Tutorial</a> for an example</p>\n" }, { "answer_id": 76187, "author": "Pavel Feldman", "author_id": 5507, "author_profile": "https://Stackoverflow.com/users/5507", "pm_score": 2, "selected": false, "text": "<p>For me expression language works only if I make that variable accessible, by putting it for example in page context.</p>\n\n<pre><code>&lt;% Object myObject = new Object();\n pageContext.setAttribute(\"myObject\", myObject);\n%&gt;\n&lt;wf:my-tag obj=\"${myObject}\" /&gt;\n</code></pre>\n\n<p>Otherwise tas receives null.</p>\n\n<p>And <code>&lt;wf:my-tag obj=\"&lt;%= myObject %&gt;\" /&gt;</code> works with no additional effort. Also &lt;%=%> gives jsp compile-time type validation, while El is validated only in runtime.</p>\n" }, { "answer_id": 355242, "author": "Adeel Ansari", "author_id": 42769, "author_profile": "https://Stackoverflow.com/users/42769", "pm_score": 4, "selected": false, "text": "<pre><code>&lt;jsp:useBean id=\"myObject\" class=\"java.lang.Object\" scope=\"page\" /&gt;\n&lt;wf:my-tag obj=\"${myObject}\" /&gt;\n</code></pre>\n\n<p>Its not encouraged to use Scriptlets in JSP page. It kills the purpose of a template language.</p>\n" }, { "answer_id": 1228031, "author": "dfrankow", "author_id": 34935, "author_profile": "https://Stackoverflow.com/users/34935", "pm_score": 5, "selected": false, "text": "<p>A slightly different question that I looked for here: \"How do you pass an object to a tag file?\"</p>\n\n<p>Answer: Use the \"type\" attribute of the attribute directive:</p>\n\n<pre><code>&lt;%@ attribute name=\"field\" \n required=\"true\"\n type=\"com.mycompany.MyClass\" %&gt;\n</code></pre>\n\n<p>The type <a href=\"http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JSPTags5.html#wp89854\" rel=\"noreferrer\">defaults to java.lang.String</a>, so without it you'll get an error if you try to access object fields saying that it can't find the field from type String.</p>\n" }, { "answer_id": 27396614, "author": "Mike Clark", "author_id": 4261022, "author_profile": "https://Stackoverflow.com/users/4261022", "pm_score": 1, "selected": false, "text": "<p>You can use \"&lt;%= %>\" to get the object value directly in your tag :</p>\n\n<pre><code> &lt;wf:my-tag obj=\"&lt;%= myObject %&gt;\"/&gt;\n</code></pre>\n\n<p>and to get the value of any variable within that object you can get that using \"obj.parameter\" like:</p>\n\n<pre><code>&lt;wf:my-tag obj=\"&lt;%= myObject.variableName %&gt;\"/&gt;\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/75626", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13393/" ]
I have a JSP page that contains a scriplet where I instantiate an object. I would like to pass that object to the JSP tag without using any cache. For example I would like to accomplish this: ``` <%@ taglib prefix="wf" uri="JspCustomTag" %> <% Object myObject = new Object(); %> <wf:my-tag obj=myObject /> ``` I'm trying to avoid directly interacting with any of the caches (page, session, servletcontext), I would rather have my tag handle that.
A slightly different question that I looked for here: "How do you pass an object to a tag file?" Answer: Use the "type" attribute of the attribute directive: ``` <%@ attribute name="field" required="true" type="com.mycompany.MyClass" %> ``` The type [defaults to java.lang.String](http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JSPTags5.html#wp89854), so without it you'll get an error if you try to access object fields saying that it can't find the field from type String.
75,650
<p>I'm working in a team environment where each developer works from their local desktop and deploys to a virtual machine that they own on the network. What I'm trying to do is set up the Visual Studio solution so that when they build the solution each projects deployment is handled in the post-build event to that developers virtual machine.</p> <p>What I'd really like to do is give ownership of those scripts to the individual developer as well so that they own their post build steps and they don't have to be the same for everyone.</p> <p>A couple of questions:</p> <ul> <li>Is a post build event the place to execute this type of deployment operation? If not what is the best place to do it?</li> <li>What software, tools, or tutorials/blog posts are available to assist in developing an automatic deployment system that supports these scenarios?</li> </ul> <p><strong>Edit:</strong> MSBuild seems to be the way to go in this situation. Anyone use alternative technologies with any success?</p> <p><strong>Edit:</strong> If you are reading this question and wondering how to execute a different set of MSBuild tasks for each developer please see this question; <a href="https://stackoverflow.com/questions/78018/executing-different-set-of-msbuild-tasks-for-each-user">Executing different set of MSBuild tasks for each user?</a></p>
[ { "answer_id": 75745, "author": "Brian Matthews", "author_id": 1969, "author_profile": "https://Stackoverflow.com/users/1969", "pm_score": 0, "selected": false, "text": "<p>Use expression language:</p>\n\n<pre>\n &lt;wf:my-tag obj=\"${myObject}\" /&gt;\n</pre>\n" }, { "answer_id": 75843, "author": "Garth Gilmour", "author_id": 2635682, "author_profile": "https://Stackoverflow.com/users/2635682", "pm_score": 3, "selected": false, "text": "<p>The original syntax was to reuse '&lt;%= %>'</p>\n\n<p>So</p>\n\n<pre><code>&lt;wf:my-tag obj=\"&lt;%= myObject %&gt;\" /&gt;\n</code></pre>\n\n<p>See <a href=\"http://java.sun.com/products/jsp/tutorial/TagLibraries16.html#62510\" rel=\"noreferrer\">this part of the Sun Tag Library Tutorial</a> for an example</p>\n" }, { "answer_id": 76187, "author": "Pavel Feldman", "author_id": 5507, "author_profile": "https://Stackoverflow.com/users/5507", "pm_score": 2, "selected": false, "text": "<p>For me expression language works only if I make that variable accessible, by putting it for example in page context.</p>\n\n<pre><code>&lt;% Object myObject = new Object();\n pageContext.setAttribute(\"myObject\", myObject);\n%&gt;\n&lt;wf:my-tag obj=\"${myObject}\" /&gt;\n</code></pre>\n\n<p>Otherwise tas receives null.</p>\n\n<p>And <code>&lt;wf:my-tag obj=\"&lt;%= myObject %&gt;\" /&gt;</code> works with no additional effort. Also &lt;%=%> gives jsp compile-time type validation, while El is validated only in runtime.</p>\n" }, { "answer_id": 355242, "author": "Adeel Ansari", "author_id": 42769, "author_profile": "https://Stackoverflow.com/users/42769", "pm_score": 4, "selected": false, "text": "<pre><code>&lt;jsp:useBean id=\"myObject\" class=\"java.lang.Object\" scope=\"page\" /&gt;\n&lt;wf:my-tag obj=\"${myObject}\" /&gt;\n</code></pre>\n\n<p>Its not encouraged to use Scriptlets in JSP page. It kills the purpose of a template language.</p>\n" }, { "answer_id": 1228031, "author": "dfrankow", "author_id": 34935, "author_profile": "https://Stackoverflow.com/users/34935", "pm_score": 5, "selected": false, "text": "<p>A slightly different question that I looked for here: \"How do you pass an object to a tag file?\"</p>\n\n<p>Answer: Use the \"type\" attribute of the attribute directive:</p>\n\n<pre><code>&lt;%@ attribute name=\"field\" \n required=\"true\"\n type=\"com.mycompany.MyClass\" %&gt;\n</code></pre>\n\n<p>The type <a href=\"http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JSPTags5.html#wp89854\" rel=\"noreferrer\">defaults to java.lang.String</a>, so without it you'll get an error if you try to access object fields saying that it can't find the field from type String.</p>\n" }, { "answer_id": 27396614, "author": "Mike Clark", "author_id": 4261022, "author_profile": "https://Stackoverflow.com/users/4261022", "pm_score": 1, "selected": false, "text": "<p>You can use \"&lt;%= %>\" to get the object value directly in your tag :</p>\n\n<pre><code> &lt;wf:my-tag obj=\"&lt;%= myObject %&gt;\"/&gt;\n</code></pre>\n\n<p>and to get the value of any variable within that object you can get that using \"obj.parameter\" like:</p>\n\n<pre><code>&lt;wf:my-tag obj=\"&lt;%= myObject.variableName %&gt;\"/&gt;\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/75650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3957/" ]
I'm working in a team environment where each developer works from their local desktop and deploys to a virtual machine that they own on the network. What I'm trying to do is set up the Visual Studio solution so that when they build the solution each projects deployment is handled in the post-build event to that developers virtual machine. What I'd really like to do is give ownership of those scripts to the individual developer as well so that they own their post build steps and they don't have to be the same for everyone. A couple of questions: * Is a post build event the place to execute this type of deployment operation? If not what is the best place to do it? * What software, tools, or tutorials/blog posts are available to assist in developing an automatic deployment system that supports these scenarios? **Edit:** MSBuild seems to be the way to go in this situation. Anyone use alternative technologies with any success? **Edit:** If you are reading this question and wondering how to execute a different set of MSBuild tasks for each developer please see this question; [Executing different set of MSBuild tasks for each user?](https://stackoverflow.com/questions/78018/executing-different-set-of-msbuild-tasks-for-each-user)
A slightly different question that I looked for here: "How do you pass an object to a tag file?" Answer: Use the "type" attribute of the attribute directive: ``` <%@ attribute name="field" required="true" type="com.mycompany.MyClass" %> ``` The type [defaults to java.lang.String](http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JSPTags5.html#wp89854), so without it you'll get an error if you try to access object fields saying that it can't find the field from type String.
75,675
<p>How do I dump the data, and only the data, not the schema, of some SQLite3 tables of a database (not all the tables)? The dump should be in SQL format, as it should be easily re-entered into the database later and should be done from the command line. Something like</p> <pre><code>sqlite3 db .dump </code></pre> <p>but without dumping the schema and selecting which tables to dump.</p>
[ { "answer_id": 75694, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>You could do a select on the tables inserting commas after each field to produce a csv, or use a GUI tool to return all the data and save it to a csv.</p>\n" }, { "answer_id": 79168, "author": "harningt", "author_id": 12713, "author_profile": "https://Stackoverflow.com/users/12713", "pm_score": 2, "selected": false, "text": "<p>The best method would be to take the code the sqlite3 db dump would do, excluding schema parts.</p>\n\n<p>Example pseudo code:</p>\n\n<pre><code>SELECT 'INSERT INTO ' || tableName || ' VALUES( ' || \n {for each value} ' quote(' || value || ')' (+ commas until final)\n|| ')' FROM 'tableName' ORDER BY rowid DESC\n</code></pre>\n\n<p>See: <code>src/shell.c:838</code> (for sqlite-3.5.9) for actual code</p>\n\n<p>You might even just take that shell and comment out the schema parts and use that.</p>\n" }, { "answer_id": 199221, "author": "CyberFonic", "author_id": 23999, "author_profile": "https://Stackoverflow.com/users/23999", "pm_score": 8, "selected": false, "text": "<p>You're not saying what you wish to do with the dumped file.</p>\n<p>To get a CSV file (which can be imported into almost everything)</p>\n<pre><code>.mode csv \n-- use '.separator SOME_STRING' for something other than a comma.\n.headers on \n.out file.csv \nselect * from MyTable;\n</code></pre>\n<p>To get an SQL file (which can be reinserted into a different SQLite database)</p>\n<pre><code>.mode insert &lt;target_table_name&gt;\n.out file.sql \nselect * from MyTable;\n</code></pre>\n" }, { "answer_id": 422842, "author": "polyglot", "author_id": 45383, "author_profile": "https://Stackoverflow.com/users/45383", "pm_score": 5, "selected": false, "text": "<p>Not the best way, but at lease does not need external tools (except grep, which is standard on *nix boxes anyway)</p>\n\n<pre><code>sqlite3 database.db3 .dump | grep '^INSERT INTO \"tablename\"'\n</code></pre>\n\n<p>but you do need to do this command for each table you are looking for though.</p>\n\n<p>Note that this does not include schema.</p>\n" }, { "answer_id": 1938480, "author": "Paul Egan", "author_id": 2211429, "author_profile": "https://Stackoverflow.com/users/2211429", "pm_score": 5, "selected": false, "text": "<p>You can specify one or more table arguments to the .dump special command, e.g.<code>sqlite3 db \".dump 'table1' 'table2'\"</code>.</p>\n" }, { "answer_id": 7526055, "author": "jellyfish", "author_id": 534951, "author_profile": "https://Stackoverflow.com/users/534951", "pm_score": 8, "selected": false, "text": "<p>You can do this getting difference of .schema and .dump commands. for example with grep:</p>\n\n<pre><code>sqlite3 some.db .schema &gt; schema.sql\nsqlite3 some.db .dump &gt; dump.sql\ngrep -vx -f schema.sql dump.sql &gt; data.sql\n</code></pre>\n\n<p><code>data.sql</code> file will contain only data without schema, something like this:</p>\n\n<pre><code>BEGIN TRANSACTION;\nINSERT INTO \"table1\" VALUES ...;\n...\nINSERT INTO \"table2\" VALUES ...;\n...\nCOMMIT;\n</code></pre>\n\n<p>I hope this helps you.</p>\n" }, { "answer_id": 7974100, "author": "Drew", "author_id": 295290, "author_profile": "https://Stackoverflow.com/users/295290", "pm_score": 3, "selected": false, "text": "<p>As an improvement to Paul Egan's answer, this can be accomplished as follows:</p>\n\n<pre><code>sqlite3 database.db3 '.dump \"table1\" \"table2\"' | grep '^INSERT'\n</code></pre>\n\n<p>--or--</p>\n\n<pre><code>sqlite3 database.db3 '.dump \"table1\" \"table2\"' | grep -v '^CREATE'\n</code></pre>\n\n<p>The caveat, of course, is that you have to have grep installed. </p>\n" }, { "answer_id": 10619827, "author": "Elia Schito", "author_id": 601782, "author_profile": "https://Stackoverflow.com/users/601782", "pm_score": 2, "selected": false, "text": "<p>This version works well with newlines inside inserts:</p>\n\n<p><code>sqlite3 database.sqlite3 .dump | grep -v '^CREATE'</code></p>\n\n<p>In practice excludes all the lines starting with <code>CREATE</code> which is less likely to contain newlines</p>\n" }, { "answer_id": 20014210, "author": "retracile", "author_id": 100073, "author_profile": "https://Stackoverflow.com/users/100073", "pm_score": 4, "selected": false, "text": "<p>Any answer which suggests using grep to exclude the <code>CREATE</code> lines or just grab the <code>INSERT</code> lines from the <code>sqlite3 $DB .dump</code> output will fail badly. The <code>CREATE TABLE</code> commands list one column per line (so excluding <code>CREATE</code> won't get all of it), and values on the <code>INSERT</code> lines can have embedded newlines (so you can't grab just the <code>INSERT</code> lines).</p>\n\n<pre><code>for t in $(sqlite3 $DB .tables); do\n echo -e \".mode insert $t\\nselect * from $t;\"\ndone | sqlite3 $DB &gt; backup.sql\n</code></pre>\n\n<p>Tested on sqlite3 version 3.6.20.</p>\n\n<p>If you want to exclude certain tables you can filter them with <code>$(sqlite $DB .tables | grep -v -e one -e two -e three)</code>, or if you want to get a specific subset replace that with <code>one two three</code>.</p>\n" }, { "answer_id": 23658679, "author": "Davoud Taghawi-Nejad", "author_id": 236830, "author_profile": "https://Stackoverflow.com/users/236830", "pm_score": 3, "selected": false, "text": "<p>In Python or Java or any high level language the .dump does not work. We need to code the conversion to CSV by hand. I give an Python example. Others, examples would be appreciated:</p>\n\n<pre><code>from os import path \nimport csv \n\ndef convert_to_csv(directory, db_name):\n conn = sqlite3.connect(path.join(directory, db_name + '.db'))\n cursor = conn.cursor()\n cursor.execute(\"SELECT name FROM sqlite_master WHERE type='table';\")\n tables = cursor.fetchall()\n for table in tables:\n table = table[0]\n cursor.execute('SELECT * FROM ' + table)\n column_names = [column_name[0] for column_name in cursor.description]\n with open(path.join(directory, table + '.csv'), 'w') as csv_file:\n csv_writer = csv.writer(csv_file)\n csv_writer.writerow(column_names)\n while True:\n try:\n csv_writer.writerow(cursor.fetchone())\n except csv.Error:\n break\n</code></pre>\n\n<p>If you have 'panel data, in other words many individual entries with id's add this to the with look and it also dumps summary statistics:</p>\n\n<pre><code> if 'id' in column_names:\n with open(path.join(directory, table + '_aggregate.csv'), 'w') as csv_file:\n csv_writer = csv.writer(csv_file)\n column_names.remove('id')\n column_names.remove('round')\n sum_string = ','.join('sum(%s)' % item for item in column_names)\n cursor.execute('SELECT round, ' + sum_string +' FROM ' + table + ' GROUP BY round;')\n csv_writer.writerow(['round'] + column_names)\n while True:\n try:\n csv_writer.writerow(cursor.fetchone())\n except csv.Error:\n break \n</code></pre>\n" }, { "answer_id": 28554255, "author": "Walty Yeung", "author_id": 176423, "author_profile": "https://Stackoverflow.com/users/176423", "pm_score": 0, "selected": false, "text": "<p>The answer by retracile should be the closest one, yet it does not work for my case. One insert query just broke in the middle and the export just stopped. Not sure what is the reason. However It works fine during <code>.dump</code>.</p>\n\n<p>Finally I wrote a tool for the split up the SQL generated from <code>.dump</code>:</p>\n\n<p><a href=\"https://github.com/motherapp/sqlite_sql_parser/\" rel=\"nofollow\">https://github.com/motherapp/sqlite_sql_parser/</a> </p>\n" }, { "answer_id": 37296788, "author": "Francisco Puga", "author_id": 930271, "author_profile": "https://Stackoverflow.com/users/930271", "pm_score": 3, "selected": false, "text": "<h1>Review of other possible solutions</h1>\n\n<p><strong>Include only INSERTs</strong></p>\n\n<pre><code>sqlite3 database.db3 .dump | grep '^INSERT INTO \"tablename\"'\n</code></pre>\n\n<p>Easy to implement but it will fail if any of your columns include new lines</p>\n\n<p><strong>SQLite insert mode</strong></p>\n\n<pre><code>for t in $(sqlite3 $DB .tables); do\n echo -e \".mode insert $t\\nselect * from $t;\"\ndone | sqlite3 $DB &gt; backup.sql\n</code></pre>\n\n<p>This is a nice and customizable solution, but it doesn't work if your columns have blob objects like 'Geometry' type in spatialite</p>\n\n<p><strong>Diff the dump with the schema</strong></p>\n\n<pre><code>sqlite3 some.db .schema &gt; schema.sql\nsqlite3 some.db .dump &gt; dump.sql\ngrep -v -f schema.sql dump &gt; data.sql\n</code></pre>\n\n<p>Not sure why, but is not working for me</p>\n\n<h1>Another (new) possible solution</h1>\n\n<p>Probably there is not a best answer to this question, but one that is working for me is grep the inserts taking into account that be new lines in the column values with an <a href=\"https://stackoverflow.com/a/7167115/930271\">expression like this</a></p>\n\n<pre><code>grep -Pzo \"(?s)^INSERT.*\\);[ \\t]*$\"\n</code></pre>\n\n<p>To select the tables do be dumped <code>.dump</code> admits a LIKE argument to match the table names, but if this is not enough probably a simple script is better option</p>\n\n<pre><code>TABLES='table1 table2 table3'\n\necho '' &gt; /tmp/backup.sql\nfor t in $TABLES ; do\n echo -e \".dump ${t}\" | sqlite3 database.db3 | grep -Pzo \"(?s)^INSERT.*?\\);$\" &gt;&gt; /tmp/backup.sql\ndone\n</code></pre>\n\n<p>or, something more elaborated to respect foreign keys and encapsulate all the dump in only one transaction</p>\n\n<pre><code>TABLES='table1 table2 table3'\n\necho 'BEGIN TRANSACTION;' &gt; /tmp/backup.sql\necho '' &gt;&gt; /tmp/backup.sql\nfor t in $TABLES ; do\n echo -e \".dump ${t}\" | sqlite3 $1 | grep -Pzo \"(?s)^INSERT.*?\\);$\" | grep -v -e 'PRAGMA foreign_keys=OFF;' -e 'BEGIN TRANSACTION;' -e 'COMMIT;' &gt;&gt; /tmp/backup.sql\ndone\n\necho '' &gt;&gt; /tmp/backup.sql\necho 'COMMIT;' &gt;&gt; /tmp/backup.sql\n</code></pre>\n\n<p>Take into account that the grep expression will fail if <code>);</code> is a string present in any of the columns</p>\n\n<p>To restore it (in a database with the tables already created)</p>\n\n<pre><code>sqlite3 -bail database.db3 &lt; /tmp/backup.sql\n</code></pre>\n" }, { "answer_id": 41738349, "author": "PeterCo", "author_id": 2613621, "author_profile": "https://Stackoverflow.com/users/2613621", "pm_score": 2, "selected": false, "text": "<p>According to the SQLite documentation for the <a href=\"https://www.sqlite.org/cli.html\" rel=\"nofollow noreferrer\">Command Line Shell For SQLite</a> you can export an SQLite table (or part of a table) as CSV, simply by setting the \"mode\" to \"csv\" and then run a query to extract the desired rows of the table:</p>\n\n<pre><code>sqlite&gt; .header on\nsqlite&gt; .mode csv\nsqlite&gt; .once c:/work/dataout.csv\nsqlite&gt; SELECT * FROM tab1;\nsqlite&gt; .exit\n</code></pre>\n\n<p>Then use the \".import\" command to import CSV (comma separated value) data into an SQLite table:</p>\n\n<pre><code>sqlite&gt; .mode csv\nsqlite&gt; .import C:/work/dataout.csv tab1\nsqlite&gt; .exit\n</code></pre>\n\n<p>Please read the further documentation about the two cases to consider: (1) Table \"tab1\" does not previously exist and (2) table \"tab1\" does already exist. </p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/75675", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6068/" ]
How do I dump the data, and only the data, not the schema, of some SQLite3 tables of a database (not all the tables)? The dump should be in SQL format, as it should be easily re-entered into the database later and should be done from the command line. Something like ``` sqlite3 db .dump ``` but without dumping the schema and selecting which tables to dump.
You're not saying what you wish to do with the dumped file. To get a CSV file (which can be imported into almost everything) ``` .mode csv -- use '.separator SOME_STRING' for something other than a comma. .headers on .out file.csv select * from MyTable; ``` To get an SQL file (which can be reinserted into a different SQLite database) ``` .mode insert <target_table_name> .out file.sql select * from MyTable; ```
75,700
<p>I have one applicationContext.xml file, and it has two org.springframework.orm.jpa.JpaTransactionManager (each with its own persistence unit, different databases) configured in a Spring middleware custom application. <br><br>I want to use annotation based transactions (@Transactional), to not mess around with TransactionStatus commit, save, and rollback.<br><br> A coworker mentioned that something gets confused doing this when there are multiple transaction managers, even though the context file is set configured correctly (the references go to the correct persistence unit. Anyone ever see an issue?</p> <hr> <p>In your config, would you have two transaction managers? Would you have txManager1 and txManager2?<br><br> That's what I have with JPA, two different Spring beans that are transaction managers.</p>
[ { "answer_id": 78479, "author": "toolkit", "author_id": 3295, "author_profile": "https://Stackoverflow.com/users/3295", "pm_score": 4, "selected": true, "text": "<p>I guess you have 2 choices</p>\n\n<p>If your use-cases never require updates to both databases within the same transaction, then you can use two JpaTransactionManagers, but I'm not sure you will be able to use the @Transactional approach? In this case, you would need to fallback on the older mechanism of using a simple <a href=\"http://static.springframework.org/spring/docs/2.5.5/api/org/springframework/transaction/interceptor/TransactionProxyFactoryBean.html\" rel=\"noreferrer\">TransactionProxyFactoryBean</a> to define transaction boundaries, eg:</p>\n\n<pre><code>&lt;bean id=\"firstRealService\" class=\"com.acme.FirstServiceImpl\"/&gt;\n&lt;bean id=\"firstService\" \n class=\"org.springframework.transaction.interceptor.TransactionProxyFactoryBean\"&gt;\n &lt;property name=\"transactionManager\" ref=\"firstJpaTm\"/&gt;\n &lt;property name=\"target\" ref=\"firstRealService\"/&gt;\n &lt;property name=\"transactionAttributes\"&gt;\n &lt;props&gt;\n &lt;prop key=\"insert*\"&gt;PROPAGATION_REQUIRED&lt;/prop&gt;\n &lt;prop key=\"update*\"&gt;PROPAGATION_REQUIRED&lt;/prop&gt;\n &lt;prop key=\"*\"&gt;PROPAGATION_REQUIRED,readOnly&lt;/prop&gt;\n &lt;/props&gt;\n &lt;/property&gt;\n&lt;/bean&gt;\n&lt;!-- similar for your second service --&gt;\n</code></pre>\n\n<p>If you are require a transaction spanning both databases, then you will need to use a JTA transaction manager. The <a href=\"http://static.springframework.org/spring/docs/2.5.5/api/org/springframework/orm/jpa/JpaTransactionManager.html\" rel=\"noreferrer\">API</a> states:</p>\n\n<blockquote>\n <p>This transaction manager is appropriate for applications that use a single JPA EntityManagerFactory for transactional data access. JTA (usually through JtaTransactionManager) is necessary for accessing multiple transactional resources within the same transaction. Note that you need to configure your JPA provider accordingly in order to make it participate in JTA transactions.</p>\n</blockquote>\n\n<p>What this means is that you will need to provide a JTA transaction manager. In our application, we use config similar to the following:</p>\n\n<pre><code>&lt;tx:annotation-driven transaction-manager=\"txManager\"/&gt;\n\n&lt;bean id=\"txManager\" \n class=\"org.springframework.transaction.jta.JtaTransactionManager\"&gt;\n &lt;property name=\"transactionManagerName\" value=\"appserver/jndi/path\" /&gt;\n&lt;/bean&gt;\n</code></pre>\n\n<p>If you are deploying within an appserver, then the spring JtaTransactionManager needs to do a lookup to the real XA-compliant JTA transaction manager provided by the appserver. However, you can also use a standalone JTA transaction manager (but I haven't tried this myself yet)</p>\n\n<p>As for configuring the Jpa persistence provider, I'm not that familiar. What JPA persistence provider are you using?</p>\n\n<p>The code above is based on our approach, where we were using native Hibernate as opposed to Hibernate's JPA implementation. In this case, we were able to get rid of the two HibernateTransactionManager beans, and simply ensure that both SessionFactories were injected with the same JTA TM, and then use the tx:annotation-driven element.</p>\n\n<p>Hope this helps</p>\n" }, { "answer_id": 280875, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>The only situation in which you can have two Spring transaction managers is if you never have both transactions open at one time. This is not intrinsically to do with distributed transactions - the same restrictions apply even if you want the two datasources to have completely separate (but potentially overlapping in time) transaction lifecyles.</p>\n\n<p>Internally Spring's transaction managers all use Spring's TransactionSynchronizationManager which keeps a bunch of critical state in static ThreadLocal variables, so transaction managers are guaranteed to stomp all over each other's state.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/75700", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13143/" ]
I have one applicationContext.xml file, and it has two org.springframework.orm.jpa.JpaTransactionManager (each with its own persistence unit, different databases) configured in a Spring middleware custom application. I want to use annotation based transactions (@Transactional), to not mess around with TransactionStatus commit, save, and rollback. A coworker mentioned that something gets confused doing this when there are multiple transaction managers, even though the context file is set configured correctly (the references go to the correct persistence unit. Anyone ever see an issue? --- In your config, would you have two transaction managers? Would you have txManager1 and txManager2? That's what I have with JPA, two different Spring beans that are transaction managers.
I guess you have 2 choices If your use-cases never require updates to both databases within the same transaction, then you can use two JpaTransactionManagers, but I'm not sure you will be able to use the @Transactional approach? In this case, you would need to fallback on the older mechanism of using a simple [TransactionProxyFactoryBean](http://static.springframework.org/spring/docs/2.5.5/api/org/springframework/transaction/interceptor/TransactionProxyFactoryBean.html) to define transaction boundaries, eg: ``` <bean id="firstRealService" class="com.acme.FirstServiceImpl"/> <bean id="firstService" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"> <property name="transactionManager" ref="firstJpaTm"/> <property name="target" ref="firstRealService"/> <property name="transactionAttributes"> <props> <prop key="insert*">PROPAGATION_REQUIRED</prop> <prop key="update*">PROPAGATION_REQUIRED</prop> <prop key="*">PROPAGATION_REQUIRED,readOnly</prop> </props> </property> </bean> <!-- similar for your second service --> ``` If you are require a transaction spanning both databases, then you will need to use a JTA transaction manager. The [API](http://static.springframework.org/spring/docs/2.5.5/api/org/springframework/orm/jpa/JpaTransactionManager.html) states: > > This transaction manager is appropriate for applications that use a single JPA EntityManagerFactory for transactional data access. JTA (usually through JtaTransactionManager) is necessary for accessing multiple transactional resources within the same transaction. Note that you need to configure your JPA provider accordingly in order to make it participate in JTA transactions. > > > What this means is that you will need to provide a JTA transaction manager. In our application, we use config similar to the following: ``` <tx:annotation-driven transaction-manager="txManager"/> <bean id="txManager" class="org.springframework.transaction.jta.JtaTransactionManager"> <property name="transactionManagerName" value="appserver/jndi/path" /> </bean> ``` If you are deploying within an appserver, then the spring JtaTransactionManager needs to do a lookup to the real XA-compliant JTA transaction manager provided by the appserver. However, you can also use a standalone JTA transaction manager (but I haven't tried this myself yet) As for configuring the Jpa persistence provider, I'm not that familiar. What JPA persistence provider are you using? The code above is based on our approach, where we were using native Hibernate as opposed to Hibernate's JPA implementation. In this case, we were able to get rid of the two HibernateTransactionManager beans, and simply ensure that both SessionFactories were injected with the same JTA TM, and then use the tx:annotation-driven element. Hope this helps
75,704
<p>I see that within MySQL there are <code>Cast()</code> and <code>Convert()</code> functions to create integers from values, but is there any way to check to see if a value is an integer? Something like <code>is_int()</code> in PHP is what I am looking for.</p>
[ { "answer_id": 75739, "author": "JBB", "author_id": 12332, "author_profile": "https://Stackoverflow.com/users/12332", "pm_score": 4, "selected": false, "text": "<p>Match it against a regular expression.</p>\n<p>c.f. <a href=\"http://forums.mysql.com/read.php?60,1907,38488#msg-38488\" rel=\"noreferrer\">http://forums.mysql.com/read.php?60,1907,38488#msg-38488</a> as quoted below:</p>\n<blockquote>\n<p>Re: IsNumeric() clause in MySQL??\n<br />Posted by: kevinclark ()\n<br />Date: August 08, 2005 01:01PM</p>\n<p><br />I agree. Here is a function I created for MySQL 5:</p>\n</blockquote>\n\n<pre><code>CREATE FUNCTION IsNumeric (sIn varchar(1024)) RETURNS tinyint\nRETURN sIn REGEXP '^(-|\\\\+){0,1}([0-9]+\\\\.[0-9]*|[0-9]*\\\\.[0-9]+|[0-9]+)$';\n</code></pre>\n<blockquote>\n<p><br />This allows for an optional plus/minus sign at the beginning, one optional decimal point, and the rest numeric digits.</p>\n</blockquote>\n" }, { "answer_id": 75880, "author": "Jumpy", "author_id": 9416, "author_profile": "https://Stackoverflow.com/users/9416", "pm_score": 9, "selected": true, "text": "<p>I'll assume you want to check a string value. One nice way is the REGEXP operator, matching the string to a regular expression. Simply do</p>\n\n<pre><code>select field from table where field REGEXP '^-?[0-9]+$';\n</code></pre>\n\n<p>this is reasonably fast. If your field is numeric, just test for</p>\n\n<pre><code>ceil(field) = field\n</code></pre>\n\n<p>instead.</p>\n" }, { "answer_id": 5244724, "author": "Jayjitraj", "author_id": 376948, "author_profile": "https://Stackoverflow.com/users/376948", "pm_score": 3, "selected": false, "text": "<p>Here is the simple solution for it\nassuming the data type is varchar </p>\n\n<pre><code>select * from calender where year &gt; 0\n</code></pre>\n\n<p>It will return true if the year is numeric else false </p>\n" }, { "answer_id": 10626708, "author": "Bill Kelly", "author_id": 1399626, "author_profile": "https://Stackoverflow.com/users/1399626", "pm_score": 1, "selected": false, "text": "<p>I have tried using the regular expressions listed above, but they do not work for the following:</p>\n\n<pre><code>SELECT '12 INCHES' REGEXP '^(-|\\\\+){0,1}([0-9]+\\\\.[0-9]*|[0-9]*\\\\.[0-9]+|[0-9]+)$' FROM ...\n</code></pre>\n\n<p>The above will return <code>1</code> (<code>TRUE</code>), meaning the test of the string '12 INCHES' against the regular expression above, returns <code>TRUE</code>. It looks like a number based on the regular expression used above. In this case, because the 12 is at the beginning of the string, the regular expression interprets it as a number. </p>\n\n<p>The following will return the right value (i.e. <code>0</code>) because the string starts with characters instead of digits</p>\n\n<pre><code>SELECT 'TOP 10' REGEXP '^(-|\\\\+){0,1}([0-9]+\\\\.[0-9]*|[0-9]*\\\\.[0-9]+|[0-9]+)$' FROM ...\n</code></pre>\n\n<p>The above will return <code>0</code> (<code>FALSE</code>) because the beginning of the string is text and not numeric.</p>\n\n<p>However, if you are dealing with strings that have a mix of numbers and letters that begin with a number, you will not get the results you want. REGEXP will interpret the string as a valid number when in fact it is not.</p>\n" }, { "answer_id": 11693466, "author": "Tom Auger", "author_id": 467386, "author_profile": "https://Stackoverflow.com/users/467386", "pm_score": 2, "selected": false, "text": "<p>What about:</p>\n\n<pre><code>WHERE table.field = \"0\" or CAST(table.field as SIGNED) != 0\n</code></pre>\n\n<p>to test for numeric and the corrolary:</p>\n\n<pre><code>WHERE table.field != \"0\" and CAST(table.field as SIGNED) = 0\n</code></pre>\n" }, { "answer_id": 12577316, "author": "Tarun Sood", "author_id": 1696374, "author_profile": "https://Stackoverflow.com/users/1696374", "pm_score": 4, "selected": false, "text": "<p>Suppose we have column with alphanumeric field having entries like</p>\n\n<pre><code>a41q\n1458\nxwe8\n1475\nasde\n9582\n.\n.\n.\n.\n.\nqe84\n</code></pre>\n\n<p>and you want highest numeric value from this db column (in this case it is 9582) then this query will help you</p>\n\n<pre><code>SELECT Max(column_name) from table_name where column_name REGEXP '^[0-9]+$'\n</code></pre>\n" }, { "answer_id": 20761038, "author": "Riad", "author_id": 1957432, "author_profile": "https://Stackoverflow.com/users/1957432", "pm_score": 3, "selected": false, "text": "<p>This also works:</p>\n\n<pre><code>CAST( coulmn_value AS UNSIGNED ) // will return 0 if not numeric string.\n</code></pre>\n\n<p>for example</p>\n\n<pre><code>SELECT CAST('a123' AS UNSIGNED) // returns 0\nSELECT CAST('123' AS UNSIGNED) // returns 123 i.e. &gt; 0\n</code></pre>\n" }, { "answer_id": 31694100, "author": "minhas23", "author_id": 2458916, "author_profile": "https://Stackoverflow.com/users/2458916", "pm_score": 3, "selected": false, "text": "<p>To check if a value is Int in Mysql, we can use the following query.\nThis query will give the rows with Int values</p>\n\n<pre><code>SELECT col1 FROM table WHERE concat('',col * 1) = col;\n</code></pre>\n" }, { "answer_id": 34655769, "author": "PodTech.io", "author_id": 1842743, "author_profile": "https://Stackoverflow.com/users/1842743", "pm_score": 1, "selected": false, "text": "<p>This works well for VARCHAR where it begins with a number or not..</p>\n\n<pre><code>WHERE concat('',fieldname * 1) != fieldname \n</code></pre>\n\n<p>may have restrictions when you get to the larger NNNNE+- numbers</p>\n" }, { "answer_id": 41845958, "author": "Tim", "author_id": 7467766, "author_profile": "https://Stackoverflow.com/users/7467766", "pm_score": 0, "selected": false, "text": "<p>for me the only thing that works is:</p>\n\n<pre><code>CREATE FUNCTION IsNumeric (SIN VARCHAR(1024)) RETURNS TINYINT\nRETURN SIN REGEXP '^(-|\\\\+){0,1}([0-9]+\\\\.[0-9]*|[0-9]*\\\\.[0-9]+|[0-9]+)$';\n</code></pre>\n\n<p>from kevinclark all other return useless stuff for me in case of <code>234jk456</code> or <code>12 inches</code></p>\n" }, { "answer_id": 49898031, "author": "Raymond Nijland", "author_id": 2548147, "author_profile": "https://Stackoverflow.com/users/2548147", "pm_score": 2, "selected": false, "text": "<p>The best i could think of a variable is a int Is a combination with MySQL's functions <code>CAST()</code> and <code>LENGTH()</code>. <br /> \nThis method will work on strings, integers, doubles/floats datatypes.</p>\n\n<pre><code>SELECT (LENGTH(CAST(&lt;data&gt; AS UNSIGNED))) = (LENGTH(&lt;data&gt;)) AS is_int\n</code></pre>\n\n<p>see demo <a href=\"http://sqlfiddle.com/#!9/ff40cd/44\" rel=\"nofollow noreferrer\">http://sqlfiddle.com/#!9/ff40cd/44</a></p>\n\n<blockquote>\n <p>it will fail if the column has a single character value. if column has\n a value 'A' then Cast('A' as UNSIGNED) will evaluate to 0 and\n LENGTH(0) will be 1. so LENGTH(Cast('A' as UNSIGNED))=LENGTH(0) will\n evaluate to 1=1 => 1</p>\n</blockquote>\n\n<p>True Waqas Malik totally fogotten to test that case. the patch is. </p>\n\n<pre><code>SELECT &lt;data&gt;, (LENGTH(CAST(&lt;data&gt; AS UNSIGNED))) = CASE WHEN CAST(&lt;data&gt; AS UNSIGNED) = 0 THEN CAST(&lt;data&gt; AS UNSIGNED) ELSE (LENGTH(&lt;data&gt;)) END AS is_int;\n</code></pre>\n\n<p><strong>Results</strong></p>\n\n<pre><code>**Query #1**\n\n SELECT 1, (LENGTH(CAST(1 AS UNSIGNED))) = CASE WHEN CAST(1 AS UNSIGNED) = 0 THEN CAST(1 AS UNSIGNED) ELSE (LENGTH(1)) END AS is_int;\n\n| 1 | is_int |\n| --- | ------ |\n| 1 | 1 |\n\n---\n**Query #2**\n\n SELECT 1.1, (LENGTH(CAST(1 AS UNSIGNED))) = CASE WHEN CAST(1.1 AS UNSIGNED) = 0 THEN CAST(1.1 AS UNSIGNED) ELSE (LENGTH(1.1)) END AS is_int;\n\n| 1.1 | is_int |\n| --- | ------ |\n| 1.1 | 0 |\n\n---\n**Query #3**\n\n SELECT \"1\", (LENGTH(CAST(\"1\" AS UNSIGNED))) = CASE WHEN CAST(\"1\" AS UNSIGNED) = 0 THEN CAST(\"1\" AS UNSIGNED) ELSE (LENGTH(\"1\")) END AS is_int;\n\n| 1 | is_int |\n| --- | ------ |\n| 1 | 1 |\n\n---\n**Query #4**\n\n SELECT \"1.1\", (LENGTH(CAST(\"1.1\" AS UNSIGNED))) = CASE WHEN CAST(\"1.1\" AS UNSIGNED) = 0 THEN CAST(\"1.1\" AS UNSIGNED) ELSE (LENGTH(\"1.1\")) END AS is_int;\n\n| 1.1 | is_int |\n| --- | ------ |\n| 1.1 | 0 |\n\n---\n**Query #5**\n\n SELECT \"1a\", (LENGTH(CAST(\"1.1\" AS UNSIGNED))) = CASE WHEN CAST(\"1a\" AS UNSIGNED) = 0 THEN CAST(\"1a\" AS UNSIGNED) ELSE (LENGTH(\"1a\")) END AS is_int;\n\n| 1a | is_int |\n| --- | ------ |\n| 1a | 0 |\n\n---\n**Query #6**\n\n SELECT \"1.1a\", (LENGTH(CAST(\"1.1a\" AS UNSIGNED))) = CASE WHEN CAST(\"1.1a\" AS UNSIGNED) = 0 THEN CAST(\"1.1a\" AS UNSIGNED) ELSE (LENGTH(\"1.1a\")) END AS is_int;\n\n| 1.1a | is_int |\n| ---- | ------ |\n| 1.1a | 0 |\n\n---\n**Query #7**\n\n SELECT \"a1\", (LENGTH(CAST(\"1.1a\" AS UNSIGNED))) = CASE WHEN CAST(\"a1\" AS UNSIGNED) = 0 THEN CAST(\"a1\" AS UNSIGNED) ELSE (LENGTH(\"a1\")) END AS is_int;\n\n| a1 | is_int |\n| --- | ------ |\n| a1 | 0 |\n\n---\n**Query #8**\n\n SELECT \"a1.1\", (LENGTH(CAST(\"a1.1\" AS UNSIGNED))) = CASE WHEN CAST(\"a1.1\" AS UNSIGNED) = 0 THEN CAST(\"a1.1\" AS UNSIGNED) ELSE (LENGTH(\"a1.1\")) END AS is_int;\n\n| a1.1 | is_int |\n| ---- | ------ |\n| a1.1 | 0 |\n\n---\n**Query #9**\n\n SELECT \"a\", (LENGTH(CAST(\"a\" AS UNSIGNED))) = CASE WHEN CAST(\"a\" AS UNSIGNED) = 0 THEN CAST(\"a\" AS UNSIGNED) ELSE (LENGTH(\"a\")) END AS is_int;\n\n| a | is_int |\n| --- | ------ |\n| a | 0 |\n</code></pre>\n\n<p>see <a href=\"https://www.db-fiddle.com/f/NNXJ9cPwxjNPz9NknsSGU/0\" rel=\"nofollow noreferrer\">demo</a> </p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/75704", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8224/" ]
I see that within MySQL there are `Cast()` and `Convert()` functions to create integers from values, but is there any way to check to see if a value is an integer? Something like `is_int()` in PHP is what I am looking for.
I'll assume you want to check a string value. One nice way is the REGEXP operator, matching the string to a regular expression. Simply do ``` select field from table where field REGEXP '^-?[0-9]+$'; ``` this is reasonably fast. If your field is numeric, just test for ``` ceil(field) = field ``` instead.
75,705
<p>I have searched for various techniques on how to read/write dBase III (dbf) files using OLEDB or ODBC with C#/.NET. I have tried almost all of the tecniques posted, but without success. Can someone point me in the right direction?</p> <p>Thanks for your time.</p>
[ { "answer_id": 75846, "author": "Kearns", "author_id": 6500, "author_profile": "https://Stackoverflow.com/users/6500", "pm_score": 2, "selected": false, "text": "<p>FoxPro 2.0 files were exactly the same as dBase III files with an extra bit for any field that was of type \"memo\" (not sure the exact name, it's been a while). That means that if you just use a <a href=\"http://www.connectionstrings.com/?carrier=visualfoxpro\" rel=\"nofollow noreferrer\">FoxPro 2.x method</a> for accessing the files, it should work.</p>\n" }, { "answer_id": 75915, "author": "Fionnuala", "author_id": 2548, "author_profile": "https://Stackoverflow.com/users/2548", "pm_score": 3, "selected": false, "text": "<p>Something like ... ?</p>\n\n<pre><code> ConnectionString = \"Provider=Microsoft.Jet.OLEDB.4.0;\" &amp; _\n\"Data Source=e:\\My Documents\\dBase;Extended Properties=dBase III\"\nDim dBaseConnection As New System.Data.OleDb.OleDbConnection(ConnectionString )\ndBaseConnection.Open()\n</code></pre>\n\n<p>From: <a href=\"http://bytes.com/forum/thread112085.html\" rel=\"noreferrer\">http://bytes.com/forum/thread112085.html</a></p>\n" }, { "answer_id": 779865, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>This is a nice aproach, i didn't tested, but i will soon...</p>\n\n<p><a href=\"http://www.c-sharpcorner.com/uploadfile/rfederico/xbaseenginerfv12022005011623am/xbaseenginerfv.aspx\" rel=\"nofollow noreferrer\">http://www.c-sharpcorner.com/uploadfile/rfederico/xbaseenginerfv12022005011623am/xbaseenginerfv.aspx</a></p>\n" }, { "answer_id": 10492908, "author": "Dejan Janjušević", "author_id": 828023, "author_profile": "https://Stackoverflow.com/users/828023", "pm_score": 3, "selected": false, "text": "<p>I realize this is an old thread, but in case someone gets here by google (like I have few days ago).. As I wrote <a href=\"https://stackoverflow.com/questions/3206029/optimal-way-to-handle-dbf-from-c-sharp/10492849#10492849\">here</a>, the elegant solution is to use <a href=\"http://linqtovfp.codeplex.com/\" rel=\"nofollow noreferrer\">LINQ to VFP</a> to read from and write to DBF files. I tested it with some dBase III files. It goes like this:</p>\n\n<p>You define your table to match the DBF definition like this:</p>\n\n<pre><code>public partial class MyTable \n{\n public System.Int32 ID { get; set; }\n public System.Decimal Field1 { get; set; }\n public System.String Field2 { get; set; }\n public System.String Field3 { get; set; }\n}\n</code></pre>\n\n<p>You define the context like this:</p>\n\n<pre><code>public partial class Context : DbEntityContextBase \n{\n public Context(string connectionString)\n : this(connectionString, typeof(ContextAttributes).FullName) \n {\n }\n\n public Context(string connectionString, string mappingId)\n : this(VfpQueryProvider.Create(connectionString, mappingId)) \n {\n }\n\n public Context(VfpQueryProvider provider)\n : base(provider) \n {\n }\n\n public virtual IEntityTable&lt;MyTable&gt; MyTables \n {\n get { return this.GetTable&lt;MyTable&gt;(); }\n }\n}\n</code></pre>\n\n<p>You define context attributes like this:</p>\n\n<pre><code>public partial class ContextAttributes : Context \n{\n public ContextAttributes(string connectionString)\n : base(connectionString) {\n }\n\n [Table(Name=\"mytable\")]\n [Column(Member=\"ID\", IsPrimaryKey=true)]\n [Column(Member=\"Field1\")]\n [Column(Member=\"Field2\")]\n [Column(Member=\"Field3\")]\n public override IEntityTable&lt;MyTable&gt; MyTables \n {\n get { return base.MyTables; }\n }\n}\n</code></pre>\n\n<p>You also need a connection string, you can define it in app.config like this (<code>Data\\</code> relative path is used as the source of DBF files in this case):</p>\n\n<pre><code>&lt;connectionStrings&gt;\n &lt;add name=\"VfpData\" providerName=\"System.Data.OleDb\"\n connectionString=\"Provider=VFPOLEDB.1;Data Source=Data\\;\"/&gt;\n&lt;/connectionStrings&gt;\n</code></pre>\n\n<p>And finally, you can perform reading and writing to and from DBF files as simple as:</p>\n\n<pre><code>// Construct a new context\nvar context = new Context(ConfigurationManager.ConnectionStrings[\"VfpData\"].ConnectionString);\n\n// Write to MyTable.dbf\nvar my = new MyTable\n{\n ID = 1,\n Field1 = 10,\n Field2 = \"foo\",\n Field3 = \"bar\"\n}\ncontext.MyTables.Insert(my);\n\n// Read from MyTable.dbf\nConsole.WriteLine(\"Count: \" + context.MyTables.Count());\nforeach (var o in context.MyTables)\n{\n Console.WriteLine(o.Field2 + \" \" + o.Field3);\n}\n</code></pre>\n" }, { "answer_id": 36814803, "author": "DRapp", "author_id": 74195, "author_profile": "https://Stackoverflow.com/users/74195", "pm_score": 0, "selected": false, "text": "<p>I have offered many answers on working with database files (more specifically VFP, but the Microsoft VFP OleDb provider will recognize older dbase files. You can do a search to find more of these links via:</p>\n\n<p>user:74195[vfp][oledb]</p>\n\n<p>First, I would start with getting the <a href=\"https://www.microsoft.com/en-us/download/details.aspx?id=14839\" rel=\"nofollow noreferrer\">Microsoft VFP OleDb Provider</a> download.</p>\n\n<p>Next, if you already have some dbf files you are trying to connect to for testing, you need to establish a connection. The connection must point to the PATH where the files are located, not the specific .dbf file. So, if you have a folder with 20 tables in it, once you connect to the PATH, you can query from any/all the tables via standard VFP-SQL Syntax (common with many sql the overall structure, but different based on some functions like string, date and number manipulations).</p>\n\n<p>Learn about PARAMETERIZING your queries. With VFP OleDb, parameters are done with the \"?\" character as a place-holder, so the parameters need to be added in the exact same sequence as they appear in the query. The \"?\" can appear as field values, join conditions, where criteria, etc.</p>\n\n<p>The following are a FEW to get you started to HOPEFULLY get you started with a valid connection, query, then insert/update/delete with parameters.</p>\n\n<ol>\n<li><p><a href=\"https://stackoverflow.com/questions/33746435/how-to-query-a-foxpro-dbf-file-with-ndx-index-file-using-the-oledb-driver-in-c/33746532#33746532\">Sample showing a connection string and simple query from a table</a></p></li>\n<li><p><a href=\"https://stackoverflow.com/questions/32578233/create-dbf-file-from-sql-table-records/32696552#32696552\">Shows a parameterized sql-insert</a>but in this case gets the data from another data source, such as sql-server and creating a VFP/dbf style table from it. It goes through cycling through records and pulling values for each parameter and inserting.</p></li>\n<li><p><a href=\"https://stackoverflow.com/questions/30648602/oledb-update-command-not-changing-data/30650636#30650636\">and another showing parameterized SQL-update</a></p></li>\n</ol>\n\n<p>Good luck, and there are plenty of others who answer on VFP and OleDb Access, these are just some that I have specifically participated in and show functional implementations that may have something you may otherwise may have missed.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/75705", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10333/" ]
I have searched for various techniques on how to read/write dBase III (dbf) files using OLEDB or ODBC with C#/.NET. I have tried almost all of the tecniques posted, but without success. Can someone point me in the right direction? Thanks for your time.
Something like ... ? ``` ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source=e:\My Documents\dBase;Extended Properties=dBase III" Dim dBaseConnection As New System.Data.OleDb.OleDbConnection(ConnectionString ) dBaseConnection.Open() ``` From: <http://bytes.com/forum/thread112085.html>
75,713
<p>I'm trying to bind controls in a WPF form to an interface and I get a runtime error that it can't find the interface's properties.</p> <p>Here's the class I'm using as a datasource:</p> <pre><code>public interface IPerson { string UserId { get; set; } string UserName { get; set; } string Email { get; set; } } public class Person : EntityBase, IPerson { public virtual string UserId { get; set; } public string UserName { get; set; } public virtual string Email { get; set; } } </code></pre> <p>Here's the XAML (an excerpt):</p> <pre><code>&lt;TextBox Name="userIdTextBox" Text="{Binding UserId}" /&gt; &lt;TextBox Name="userNameTextBox" Text="{Binding UserName}" /&gt; &lt;TextBox Name="emailTextBox" Text="{Binding Email}" /&gt; </code></pre> <p>Here's the code behind (again, an excerpt):</p> <pre><code>var person = PolicyInjection.Wrap&lt;IPerson&gt;(new Person()); person.UserId = "jdoe"; person.UserName = "John Doe"; person.Email = "[email protected]"; this.DataContext = person; </code></pre> <p>Note that the class I'm using as the data source needs to be an entity because I'm using Policy Injection through the entlib's Policy Injection Application Block.</p> <p>I'm getting this error at runtime:</p> <pre><code>System.Windows.Data Error: 16 : Cannot get 'Email' value (type 'String') from '' (type 'Person'). BindingExpression:Path=Email; DataItem='Person' (HashCode=22322349); target element is 'TextBox' (Name='emailTextBox'); target property is 'Text' (type 'String') TargetException:'System.Reflection.TargetException: Object does not match target type. at System.Reflection.RuntimeMethodInfo.CheckConsistency(Object target) at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks) at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) at System.Reflection.RuntimePropertyInfo.GetValue(Object obj, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture) at System.Reflection.RuntimePropertyInfo.GetValue(Object obj, Object[] index) at MS.Internal.Data.PropertyPathWorker.GetValue(Object item, Int32 level) at MS.Internal.Data.PropertyPathWorker.RawValue(Int32 k)' </code></pre>
[ { "answer_id": 77322, "author": "Robert Jeppesen", "author_id": 9436, "author_profile": "https://Stackoverflow.com/users/9436", "pm_score": 3, "selected": true, "text": "<p>I'm not familiar with entlib's policy injection, but I'm pretty sure that your problem lies there, and not in the fact that you're using an interface.<br>\nIf you were to replace</p>\n\n<pre><code>var person = PolicyInjection.Wrap&lt;IPerson&gt;(new Person());\n</code></pre>\n\n<p>with </p>\n\n<pre><code>IPerson person = new Person();\n</code></pre>\n\n<p>surely it would work?</p>\n" }, { "answer_id": 77356, "author": "Senkwe", "author_id": 6419, "author_profile": "https://Stackoverflow.com/users/6419", "pm_score": 0, "selected": false, "text": "<p>I don't see much wrong with the code. Technically you're binding an instance of the Person class (ie it doesn't make sense to try and bind to an interface anyway) I don't know what your PolicyInjection.Wrap method does, but I'm assuming it returns a concrete Person class? Anyway, I just tried this on my end and it works fine...</p>\n\n<pre><code>public partial class Window1 : Window\n{\n public Window1()\n {\n InitializeComponent();\n\n IPerson person = new Person() { FirstName = \"Hovito\" };\n\n this.DataContext = person;\n }\n}\n\npublic class Person : IPerson\n{\n public virtual string FirstName { get; set; }\n public string LastName { get; set; }\n}\n\npublic interface IPerson\n{\n string FirstName { get; set; }\n string LastName { get; set; }\n}\n</code></pre>\n\n<p>I would suggest you look into that PolicyInjection class a bit more. Find out if it really does return a Person type as you expect.</p>\n" }, { "answer_id": 77391, "author": "cranley", "author_id": 10308, "author_profile": "https://Stackoverflow.com/users/10308", "pm_score": 1, "selected": false, "text": "<p>We bind to almost nothing but Interfaces in our project, all without problem. The problem you're experiencing is due to entlib... but I'm not familiar enough with entlib to help you there. WPF can, however, bind to Interfaces.</p>\n" }, { "answer_id": 9040770, "author": "Philipp Munin", "author_id": 508797, "author_profile": "https://Stackoverflow.com/users/508797", "pm_score": 0, "selected": false, "text": "<p>Try to specify property path explicitly in your XAML:</p>\n\n<pre><code>&lt;TextBox Name=\"userIdTextBox\" Text=\"{Binding (myns:IPerson.UserId)}\" /&gt; \n&lt;TextBox Name=\"userNameTextBox\" Text=\"{Binding (myns:IPerson.UserName)}\" /&gt; \n&lt;TextBox Name=\"emailTextBox\" Text=\"{Binding (myns:IPerson.Email)}\" /&gt; \n</code></pre>\n\n<p>I guess the type generated by policy injection is based on Person class, but is dynamic and internal. As far as I know XAML data binding engine can work only with public types.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/75713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6542/" ]
I'm trying to bind controls in a WPF form to an interface and I get a runtime error that it can't find the interface's properties. Here's the class I'm using as a datasource: ``` public interface IPerson { string UserId { get; set; } string UserName { get; set; } string Email { get; set; } } public class Person : EntityBase, IPerson { public virtual string UserId { get; set; } public string UserName { get; set; } public virtual string Email { get; set; } } ``` Here's the XAML (an excerpt): ``` <TextBox Name="userIdTextBox" Text="{Binding UserId}" /> <TextBox Name="userNameTextBox" Text="{Binding UserName}" /> <TextBox Name="emailTextBox" Text="{Binding Email}" /> ``` Here's the code behind (again, an excerpt): ``` var person = PolicyInjection.Wrap<IPerson>(new Person()); person.UserId = "jdoe"; person.UserName = "John Doe"; person.Email = "[email protected]"; this.DataContext = person; ``` Note that the class I'm using as the data source needs to be an entity because I'm using Policy Injection through the entlib's Policy Injection Application Block. I'm getting this error at runtime: ``` System.Windows.Data Error: 16 : Cannot get 'Email' value (type 'String') from '' (type 'Person'). BindingExpression:Path=Email; DataItem='Person' (HashCode=22322349); target element is 'TextBox' (Name='emailTextBox'); target property is 'Text' (type 'String') TargetException:'System.Reflection.TargetException: Object does not match target type. at System.Reflection.RuntimeMethodInfo.CheckConsistency(Object target) at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks) at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) at System.Reflection.RuntimePropertyInfo.GetValue(Object obj, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture) at System.Reflection.RuntimePropertyInfo.GetValue(Object obj, Object[] index) at MS.Internal.Data.PropertyPathWorker.GetValue(Object item, Int32 level) at MS.Internal.Data.PropertyPathWorker.RawValue(Int32 k)' ```
I'm not familiar with entlib's policy injection, but I'm pretty sure that your problem lies there, and not in the fact that you're using an interface. If you were to replace ``` var person = PolicyInjection.Wrap<IPerson>(new Person()); ``` with ``` IPerson person = new Person(); ``` surely it would work?
75,714
<p>Note: I am using .Net 1.1, although I am not completely against answer that use higher versions.</p> <p>I am displaying some dynamically generated objects in a PropertyGrid. These objects have numeric, text, and enumeration properties. Currently I am having issues setting the default value for the enumerations so that they don't always appear bold in the list. The enumerations themselves are also dynamically generated and appear to work fine with the exception of the default value.</p> <p>First, I would like to show how I generate the enumerations in the case that it is causing the error. The first line uses a custom class to query the database. Simply replace this line with a DataAdapter or your preferred method of filling a DataSet with Database values. I am using the string values in column 1 to create my enumeration.</p> <pre><code>private Type GetNewObjectType(string field, ModuleBuilder module, DatabaseAccess da) //Query the database. System.Data.DataSet ds = da.QueryDB(query); EnumBuilder eb = module.DefineEnum(field, TypeAttributes.Public, typeof(int)); for(int i = 0; i &lt; ds.Tables[0].Rows.Count; i++) { if(ds.Tables[0].Rows[i][1] != DBNull.Value) { string text = Convert.ToString(ds.Tables[0].Rows[i][1]); eb.DefineLiteral(text, i); } } return eb.CreateType(); </code></pre> <p>Now on to how the type is created. This is largely based of the sample code provided <a href="http://mironabramson.com/blog/post/2008/06/Create-you-own-new-Type-and-use-it-on-run-time-(C).aspx" rel="nofollow noreferrer">here</a>. Essentially, think of pFeature as a database row. We loop through the columns and use the column name as the new property name and use the column value as the default value; that is the goal at least.</p> <pre><code>// create a dynamic assembly and module AssemblyName assemblyName = new AssemblyName(); assemblyName.Name = "tmpAssembly"; AssemblyBuilder assemblyBuilder = System.Threading.Thread.GetDomain().DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run); ModuleBuilder module = assemblyBuilder.DefineDynamicModule("tmpModule"); // create a new type builder TypeBuilder typeBuilder = module.DefineType("BindableRowCellCollection", TypeAttributes.Public | TypeAttributes.Class); // Loop over the attributes that will be used as the properties names in out new type for(int i = 0; i &lt; pFeature.Fields.FieldCount; i++) { string propertyName = pFeature.Fields.get_Field(i).Name; object val = pFeature.get_Value(i); Type type = GetNewObjectType(propertyName, module, da); // Generate a private field FieldBuilder field = typeBuilder.DefineField("_" + propertyName, type, FieldAttributes.Private); // Generate a public property PropertyBuilder property = typeBuilder.DefineProperty(propertyName, PropertyAttributes.None, type, new Type[0]); //Create the custom attribute to set the description. Type[] ctorParams = new Type[] { typeof(string) }; ConstructorInfo classCtorInfo = typeof(DescriptionAttribute).GetConstructor(ctorParams); CustomAttributeBuilder myCABuilder = new CustomAttributeBuilder( classCtorInfo, new object[] { "This is the long description of this property." }); property.SetCustomAttribute(myCABuilder); //Set the default value. ctorParams = new Type[] { type }; classCtorInfo = typeof(DefaultValueAttribute).GetConstructor(ctorParams); if(type.IsEnum) { //val contains the text version of the enum. Parse it to the enumeration value. object o = Enum.Parse(type, val.ToString(), true); myCABuilder = new CustomAttributeBuilder( classCtorInfo, new object[] { o }); } else { myCABuilder = new CustomAttributeBuilder( classCtorInfo, new object[] { val }); } property.SetCustomAttribute(myCABuilder); // The property set and property get methods require a special set of attributes: MethodAttributes GetSetAttr = MethodAttributes.Public | MethodAttributes.HideBySig; // Define the "get" accessor method for current private field. MethodBuilder currGetPropMthdBldr = typeBuilder.DefineMethod("get_value", GetSetAttr, type, Type.EmptyTypes); // Intermediate Language stuff... ILGenerator currGetIL = currGetPropMthdBldr.GetILGenerator(); currGetIL.Emit(OpCodes.Ldarg_0); currGetIL.Emit(OpCodes.Ldfld, field); currGetIL.Emit(OpCodes.Ret); // Define the "set" accessor method for current private field. MethodBuilder currSetPropMthdBldr = typeBuilder.DefineMethod("set_value", GetSetAttr, null, new Type[] { type }); // Again some Intermediate Language stuff... ILGenerator currSetIL = currSetPropMthdBldr.GetILGenerator(); currSetIL.Emit(OpCodes.Ldarg_0); currSetIL.Emit(OpCodes.Ldarg_1); currSetIL.Emit(OpCodes.Stfld, field); currSetIL.Emit(OpCodes.Ret); // Last, we must map the two methods created above to our PropertyBuilder to // their corresponding behaviors, "get" and "set" respectively. property.SetGetMethod(currGetPropMthdBldr); property.SetSetMethod(currSetPropMthdBldr); } // Generate our type Type generatedType = typeBuilder.CreateType(); </code></pre> <p>Finally, we use that type to create an instance of it and load in the default values so we can later display it using the PropertiesGrid.</p> <pre><code>// Now we have our type. Let's create an instance from it: object generatedObject = Activator.CreateInstance(generatedType); // Loop over all the generated properties, and assign the default values PropertyInfo[] properties = generatedType.GetProperties(); PropertyDescriptorCollection props = TypeDescriptor.GetProperties(generatedType); for(int i = 0; i &lt; properties.Length; i++) { string field = properties[i].Name; DefaultValueAttribute dva = (DefaultValueAttribute)props[field].Attributes[typeof(DefaultValueAttribute)]; object o = dva.Value; Type pType = properties[i].PropertyType; if(pType.IsEnum) { o = Enum.Parse(pType, o.ToString(), true); } else { o = Convert.ChangeType(o, pType); } properties[i].SetValue(generatedObject, o, null); } return generatedObject; </code></pre> <p>However, this causes an error when we try to get the default value for an enumeration. The DefaultValueAttribute dva does not get set and thus causes an exception when we try to use it.</p> <p>If we change this code segment:</p> <pre><code> if(type.IsEnum) { object o = Enum.Parse(type, val.ToString(), true); myCABuilder = new CustomAttributeBuilder( classCtorInfo, new object[] { o }); } </code></pre> <p>to this:</p> <pre><code> if(type.IsEnum) { myCABuilder = new CustomAttributeBuilder( classCtorInfo, new object[] { 0 }); } </code></pre> <p>There are no problems getting the DefaultValueAttribute dva; however, the field is then bolded in the PropertiesGrid because it does not match the default value.</p> <p>Can anyone figure out why I cannot get the DefaultValueAttribute when I set the default value to my generated enumeration? As you can probably guess, I am still new to Reflection, so this is all pretty new to me.</p> <p>Thanks.</p> <p>Update: In response to alabamasucks.blogspot, using ShouldSerialize would certainly solve my problem. I was able to create the method using a normal class; however, I am unsure on how to do this for a generated type. From what I can figure out, I would need to use MethodBuilder and generate the IL to check if the field is equal to the default value. Sounds simple enough. I want to represent this in IL code:</p> <pre><code>public bool ShouldSerializepropertyName() { return (field != val); } </code></pre> <p>I was able to get the IL code using ildasm.exe from similar code, but I have a couple of questions. How do I use the val variable in the IL code? In my example, I used a int with the value of 0.</p> <pre><code>IL_0000: ldc.i4.s 0 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: ldarg.0 IL_0005: ldfld int32 TestNamespace.TestClass::field IL_000a: ceq IL_000c: ldc.i4.0 IL_000d: ceq IL_000f: stloc.1 IL_0010: br.s IL_0012 IL_0012: ldloc.1 IL_0013: ret </code></pre> <p>This certainly can get tricky because IL has a different load command for each type. Currently, I use ints, doubles, strings, and enumerations, so the code will have to be adaptive based on the type. </p> <p>Does anyone have an idea how to do this? Or am I heading in the wrong direction?</p>
[ { "answer_id": 80194, "author": "Eric W", "author_id": 14972, "author_profile": "https://Stackoverflow.com/users/14972", "pm_score": 2, "selected": false, "text": "<p>I'm not sure how to get the attribute to work, but there is another option that may be easier.</p>\n\n<p>In addition to checking for the DefaultValueAttribute, the PropertyGrid also uses reflection to look for a method named \"ShouldSerializeProperty Name\", where [Property Name] is the name of the property in question. This method should return a boolean that is true if the property is set to a non-default value and false otherwise. It would probably be easier for you to use reflection to create a method that returns the correct value then to fix up the attribute.</p>\n" }, { "answer_id": 201521, "author": "csgero", "author_id": 21764, "author_profile": "https://Stackoverflow.com/users/21764", "pm_score": 2, "selected": false, "text": "<p>You should try it with the DefaultValueAttribute taking a String and a Type parameter, passing in the string enum value (val.ToString), and the type of your enum.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/75714", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Note: I am using .Net 1.1, although I am not completely against answer that use higher versions. I am displaying some dynamically generated objects in a PropertyGrid. These objects have numeric, text, and enumeration properties. Currently I am having issues setting the default value for the enumerations so that they don't always appear bold in the list. The enumerations themselves are also dynamically generated and appear to work fine with the exception of the default value. First, I would like to show how I generate the enumerations in the case that it is causing the error. The first line uses a custom class to query the database. Simply replace this line with a DataAdapter or your preferred method of filling a DataSet with Database values. I am using the string values in column 1 to create my enumeration. ``` private Type GetNewObjectType(string field, ModuleBuilder module, DatabaseAccess da) //Query the database. System.Data.DataSet ds = da.QueryDB(query); EnumBuilder eb = module.DefineEnum(field, TypeAttributes.Public, typeof(int)); for(int i = 0; i < ds.Tables[0].Rows.Count; i++) { if(ds.Tables[0].Rows[i][1] != DBNull.Value) { string text = Convert.ToString(ds.Tables[0].Rows[i][1]); eb.DefineLiteral(text, i); } } return eb.CreateType(); ``` Now on to how the type is created. This is largely based of the sample code provided [here](http://mironabramson.com/blog/post/2008/06/Create-you-own-new-Type-and-use-it-on-run-time-(C).aspx). Essentially, think of pFeature as a database row. We loop through the columns and use the column name as the new property name and use the column value as the default value; that is the goal at least. ``` // create a dynamic assembly and module AssemblyName assemblyName = new AssemblyName(); assemblyName.Name = "tmpAssembly"; AssemblyBuilder assemblyBuilder = System.Threading.Thread.GetDomain().DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run); ModuleBuilder module = assemblyBuilder.DefineDynamicModule("tmpModule"); // create a new type builder TypeBuilder typeBuilder = module.DefineType("BindableRowCellCollection", TypeAttributes.Public | TypeAttributes.Class); // Loop over the attributes that will be used as the properties names in out new type for(int i = 0; i < pFeature.Fields.FieldCount; i++) { string propertyName = pFeature.Fields.get_Field(i).Name; object val = pFeature.get_Value(i); Type type = GetNewObjectType(propertyName, module, da); // Generate a private field FieldBuilder field = typeBuilder.DefineField("_" + propertyName, type, FieldAttributes.Private); // Generate a public property PropertyBuilder property = typeBuilder.DefineProperty(propertyName, PropertyAttributes.None, type, new Type[0]); //Create the custom attribute to set the description. Type[] ctorParams = new Type[] { typeof(string) }; ConstructorInfo classCtorInfo = typeof(DescriptionAttribute).GetConstructor(ctorParams); CustomAttributeBuilder myCABuilder = new CustomAttributeBuilder( classCtorInfo, new object[] { "This is the long description of this property." }); property.SetCustomAttribute(myCABuilder); //Set the default value. ctorParams = new Type[] { type }; classCtorInfo = typeof(DefaultValueAttribute).GetConstructor(ctorParams); if(type.IsEnum) { //val contains the text version of the enum. Parse it to the enumeration value. object o = Enum.Parse(type, val.ToString(), true); myCABuilder = new CustomAttributeBuilder( classCtorInfo, new object[] { o }); } else { myCABuilder = new CustomAttributeBuilder( classCtorInfo, new object[] { val }); } property.SetCustomAttribute(myCABuilder); // The property set and property get methods require a special set of attributes: MethodAttributes GetSetAttr = MethodAttributes.Public | MethodAttributes.HideBySig; // Define the "get" accessor method for current private field. MethodBuilder currGetPropMthdBldr = typeBuilder.DefineMethod("get_value", GetSetAttr, type, Type.EmptyTypes); // Intermediate Language stuff... ILGenerator currGetIL = currGetPropMthdBldr.GetILGenerator(); currGetIL.Emit(OpCodes.Ldarg_0); currGetIL.Emit(OpCodes.Ldfld, field); currGetIL.Emit(OpCodes.Ret); // Define the "set" accessor method for current private field. MethodBuilder currSetPropMthdBldr = typeBuilder.DefineMethod("set_value", GetSetAttr, null, new Type[] { type }); // Again some Intermediate Language stuff... ILGenerator currSetIL = currSetPropMthdBldr.GetILGenerator(); currSetIL.Emit(OpCodes.Ldarg_0); currSetIL.Emit(OpCodes.Ldarg_1); currSetIL.Emit(OpCodes.Stfld, field); currSetIL.Emit(OpCodes.Ret); // Last, we must map the two methods created above to our PropertyBuilder to // their corresponding behaviors, "get" and "set" respectively. property.SetGetMethod(currGetPropMthdBldr); property.SetSetMethod(currSetPropMthdBldr); } // Generate our type Type generatedType = typeBuilder.CreateType(); ``` Finally, we use that type to create an instance of it and load in the default values so we can later display it using the PropertiesGrid. ``` // Now we have our type. Let's create an instance from it: object generatedObject = Activator.CreateInstance(generatedType); // Loop over all the generated properties, and assign the default values PropertyInfo[] properties = generatedType.GetProperties(); PropertyDescriptorCollection props = TypeDescriptor.GetProperties(generatedType); for(int i = 0; i < properties.Length; i++) { string field = properties[i].Name; DefaultValueAttribute dva = (DefaultValueAttribute)props[field].Attributes[typeof(DefaultValueAttribute)]; object o = dva.Value; Type pType = properties[i].PropertyType; if(pType.IsEnum) { o = Enum.Parse(pType, o.ToString(), true); } else { o = Convert.ChangeType(o, pType); } properties[i].SetValue(generatedObject, o, null); } return generatedObject; ``` However, this causes an error when we try to get the default value for an enumeration. The DefaultValueAttribute dva does not get set and thus causes an exception when we try to use it. If we change this code segment: ``` if(type.IsEnum) { object o = Enum.Parse(type, val.ToString(), true); myCABuilder = new CustomAttributeBuilder( classCtorInfo, new object[] { o }); } ``` to this: ``` if(type.IsEnum) { myCABuilder = new CustomAttributeBuilder( classCtorInfo, new object[] { 0 }); } ``` There are no problems getting the DefaultValueAttribute dva; however, the field is then bolded in the PropertiesGrid because it does not match the default value. Can anyone figure out why I cannot get the DefaultValueAttribute when I set the default value to my generated enumeration? As you can probably guess, I am still new to Reflection, so this is all pretty new to me. Thanks. Update: In response to alabamasucks.blogspot, using ShouldSerialize would certainly solve my problem. I was able to create the method using a normal class; however, I am unsure on how to do this for a generated type. From what I can figure out, I would need to use MethodBuilder and generate the IL to check if the field is equal to the default value. Sounds simple enough. I want to represent this in IL code: ``` public bool ShouldSerializepropertyName() { return (field != val); } ``` I was able to get the IL code using ildasm.exe from similar code, but I have a couple of questions. How do I use the val variable in the IL code? In my example, I used a int with the value of 0. ``` IL_0000: ldc.i4.s 0 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: ldarg.0 IL_0005: ldfld int32 TestNamespace.TestClass::field IL_000a: ceq IL_000c: ldc.i4.0 IL_000d: ceq IL_000f: stloc.1 IL_0010: br.s IL_0012 IL_0012: ldloc.1 IL_0013: ret ``` This certainly can get tricky because IL has a different load command for each type. Currently, I use ints, doubles, strings, and enumerations, so the code will have to be adaptive based on the type. Does anyone have an idea how to do this? Or am I heading in the wrong direction?
I'm not sure how to get the attribute to work, but there is another option that may be easier. In addition to checking for the DefaultValueAttribute, the PropertyGrid also uses reflection to look for a method named "ShouldSerializeProperty Name", where [Property Name] is the name of the property in question. This method should return a boolean that is true if the property is set to a non-default value and false otherwise. It would probably be easier for you to use reflection to create a method that returns the correct value then to fix up the attribute.
75,722
<p>In C#, if I want to deterministically clean up non-managed resources, I can use the "using" keyword. But for multiple dependent objects, this ends up nesting further and further:</p> <pre><code>using (FileStream fs = new FileStream("c:\file.txt", FileMode.Open)) { using (BufferedStream bs = new BufferedStream(fs)) { using (StreamReader sr = new StreamReader(bs)) { // use sr, and have everything cleaned up when done. } } } </code></pre> <p>In C++, I'm used to being able to use destructors to do it like this:</p> <pre><code>{ FileStream fs("c:\file.txt", FileMode.Open); BufferedStream bs(fs); StreamReader sr(bs); // use sr, and have everything cleaned up when done. } </code></pre> <p>Is there a better way in C# to do this? Or am I stuck with the multiple levels of nesting?</p>
[ { "answer_id": 75741, "author": "Abe Heidebrecht", "author_id": 9268, "author_profile": "https://Stackoverflow.com/users/9268", "pm_score": -1, "selected": false, "text": "<p>The using statement is syntactic sugar that converts to:</p>\n\n<pre><code> try\n {\n obj declaration\n ...\n }\n finally\n {\n obj.Dispose();\n }\n</code></pre>\n\n<p>You can explicitly call Dispose on your objects, but it won't be as safe, since if one of them throws an exception, the resources won't be freed properly.</p>\n" }, { "answer_id": 75751, "author": "Greg Hurlman", "author_id": 35, "author_profile": "https://Stackoverflow.com/users/35", "pm_score": 1, "selected": false, "text": "<p>Instead of nesting using statements, you can just write out the .Dispose calls manually - but you'll almost certainly miss one at some point.</p>\n\n<p>Either run FxCop or something else that can make sure that all IDisposable-implementing type instances have a .Dispose() call, or deal with the nesting.</p>\n" }, { "answer_id": 75755, "author": "Ryan Lundy", "author_id": 5486, "author_profile": "https://Stackoverflow.com/users/5486", "pm_score": 6, "selected": true, "text": "<p>You don't have to nest with multiple usings:</p>\n\n<pre><code>using (FileStream fs = new FileStream(\"c:\\file.txt\", FileMode.Open))\nusing (BufferedStream bs = new BufferedStream(fs))\nusing (StreamReader sr = new StreamReader(bs))\n{\n // all three get disposed when you're done\n}\n</code></pre>\n" }, { "answer_id": 75761, "author": "Bob Wintemberg", "author_id": 12999, "author_profile": "https://Stackoverflow.com/users/12999", "pm_score": 3, "selected": false, "text": "<p>You can put using statements together before the opening braces like so:</p>\n\n<pre><code> using (StreamWriter w1 = File.CreateText(\"W1\"))\n using (StreamWriter w2 = File.CreateText(\"W2\"))\n {\n // code here\n }\n</code></pre>\n\n<p><a href=\"http://blogs.msdn.com/ericgu/archive/2004/08/05/209267.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/ericgu/archive/2004/08/05/209267.aspx</a></p>\n" }, { "answer_id": 75764, "author": "JeffFoster", "author_id": 9853, "author_profile": "https://Stackoverflow.com/users/9853", "pm_score": 2, "selected": false, "text": "<p>You could use this syntax to condense things down a bit:</p>\n\n<pre><code>using (FileStream fs = new FileStream(\"c:\\file.txt\", FileMode.Open))\nusing (BufferedStream bs = new BufferedStream(fs))\nusing (StreamReader sr = new StreamReader(bs))\n{\n}\n</code></pre>\n\n<p>This is one of those rare occasions where not using { } for all blocks makes sense IMHO.</p>\n" }, { "answer_id": 75778, "author": "Paul van Brenk", "author_id": 1837197, "author_profile": "https://Stackoverflow.com/users/1837197", "pm_score": 0, "selected": false, "text": "<p>you can omit the curly braces, like:</p>\n\n<pre><code>using (FileStream fs = new FileStream(\"c:\\file.txt\", FileMode.Open))\nusing (BufferedStream bs = new BufferedStream(fs))\nusing (StreamReader sr = new StreamReader(bs))\n{\n // use sr, and have everything cleaned up when done.\n}\n</code></pre>\n\n<p>or use the regular try finally approach:</p>\n\n<pre><code>FileStream fs = new FileStream(\"c:\\file.txt\", FileMode.Open);\nBufferedStream bs = new BufferedStream(fs);\nStreamReader sr = new StreamReader(bs);\ntry\n{\n // use sr, and have everything cleaned up when done.\n}finally{\n sr.Close(); // should be enough since you hand control to the reader\n}\n</code></pre>\n" }, { "answer_id": 75836, "author": "Michael Meadows", "author_id": 7643, "author_profile": "https://Stackoverflow.com/users/7643", "pm_score": 0, "selected": false, "text": "<p>This makes for a much larger net plus in lines of code, but a tangible gain in readability:</p>\n\n<pre><code>using (StreamWrapper wrapper = new StreamWrapper(\"c:\\file.txt\", FileMode.Open))\n{\n // do stuff using wrapper.Reader\n}\n</code></pre>\n\n<p>Where StreamWrapper is defined here:</p>\n\n<pre><code>private class StreamWrapper : IDisposable\n{\n private readonly FileStream fs;\n private readonly BufferedStream bs;\n private readonly StreamReader sr;\n\n public StreamWrapper(string fileName, FileMode mode)\n {\n fs = new FileStream(fileName, mode);\n bs = new BufferedStream(fs);\n sr = new StreamReader(bs);\n }\n\n public StreamReader Reader\n {\n get { return sr; }\n }\n\n public void Dispose()\n {\n sr.Dispose();\n bs.Dispose();\n fs.Dispose();\n }\n}\n</code></pre>\n\n<p>With some effort, StreamWrapper could be refactored to be more generic and reusable.</p>\n" }, { "answer_id": 76587, "author": "Jesse C. Slicer", "author_id": 3312, "author_profile": "https://Stackoverflow.com/users/3312", "pm_score": 1, "selected": false, "text": "<p>I have implemented solutions like <a href=\"https://stackoverflow.com/questions/75722/is-there-a-better-deterministic-disposal-pattern-than-nested-usings-in-c#75836\">Michael Meadows</a>'s before, but his <code>StreamWrapper</code> code doesn't take into account if the <code>Dispose()</code> methods called on the member variables throw an exception for one reason or another, the subsequent <code>Dispose()</code>es will not be called and resources could dangle. The safer way for that one to work is:</p>\n\n<pre><code> var exceptions = new List&lt;Exception&gt;();\n\n try\n {\n this.sr.Dispose();\n }\n catch (Exception ex)\n {\n exceptions.Add(ex);\n }\n\n try\n {\n this.bs.Dispose();\n }\n catch (Exception ex)\n {\n exceptions.Add(ex);\n }\n\n try\n {\n this.fs.Dispose();\n }\n catch (Exception ex)\n {\n exceptions.Add(ex);\n }\n\n if (exceptions.Count &gt; 0)\n {\n throw new AggregateException(exceptions);\n }\n }\n</code></pre>\n" }, { "answer_id": 78362, "author": "Joel Lucsy", "author_id": 645, "author_profile": "https://Stackoverflow.com/users/645", "pm_score": 0, "selected": false, "text": "<p>It should be noted that generally when creating stream based off another stream the new stream will close the one being passed in. So, to further reduce your example:</p>\n\n<pre><code>using (Stream Reader sr = new StreamReader( new BufferedStream( new FileStream(\"c:\\file.txt\", FileMode.Open))))\n{\n // all three get disposed when you're done\n}\n</code></pre>\n" }, { "answer_id": 6076898, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>for this example let us assume you have:</p>\n\n<p>a file named 1.xml under c:\\</p>\n\n<p>a textbox named textBox1, with the multi-line properties set ON.</p>\n\n<pre><code>const string fname = @\"c:\\1.xml\";\n\nStreamReader sr=new StreamReader(new BufferedStream(new FileStream(fname,FileMode.Open,FileAccess.Read,FileShare.Delete)));\ntextBox1.Text = sr.ReadToEnd();\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/75722", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8701/" ]
In C#, if I want to deterministically clean up non-managed resources, I can use the "using" keyword. But for multiple dependent objects, this ends up nesting further and further: ``` using (FileStream fs = new FileStream("c:\file.txt", FileMode.Open)) { using (BufferedStream bs = new BufferedStream(fs)) { using (StreamReader sr = new StreamReader(bs)) { // use sr, and have everything cleaned up when done. } } } ``` In C++, I'm used to being able to use destructors to do it like this: ``` { FileStream fs("c:\file.txt", FileMode.Open); BufferedStream bs(fs); StreamReader sr(bs); // use sr, and have everything cleaned up when done. } ``` Is there a better way in C# to do this? Or am I stuck with the multiple levels of nesting?
You don't have to nest with multiple usings: ``` using (FileStream fs = new FileStream("c:\file.txt", FileMode.Open)) using (BufferedStream bs = new BufferedStream(fs)) using (StreamReader sr = new StreamReader(bs)) { // all three get disposed when you're done } ```
75,746
<pre><code>EmployeeNumber = string.IsNullOrEmpty(employeeNumberTextBox.Text) ? null : Convert.ToInt32(employeeNumberTextBox.Text), </code></pre> <p>I often find myself wanting to do things like this (<code>EmployeeNumber</code> is a <code>Nullable&lt;int&gt;</code> as it's a property on a LINQ-to-SQL dbml object where the column allows NULL values). Unfortunately, the compiler feels that</p> <blockquote> <p>There is no implicit conversion between 'null' and 'int'</p> </blockquote> <p>even though both types would be valid in an assignment operation to a nullable int on their own.</p> <p>Using the null coalescing operator is not an option as far as I can see because of the inline conversion that needs to happen on the <code>.Text</code> string if it's not null.</p> <p>As far as I know the only way to do this is to use an if statement and/or assign it in two steps. In this particular case I find that very frustrating because I wanted to use the object initializer syntax and this assignment would be in the initialization block...</p> <p>Does anyone know a more elegant solution?</p>
[ { "answer_id": 75795, "author": "Abe Heidebrecht", "author_id": 9268, "author_profile": "https://Stackoverflow.com/users/9268", "pm_score": 2, "selected": false, "text": "<p>You can cast the output of Convert:</p>\n\n<pre><code>EmployeeNumber = string.IsNullOrEmpty(employeeNumberTextBox.Text)\n ? null\n : (int?)Convert.ToInt32(employeeNumberTextBox.Text)\n</code></pre>\n" }, { "answer_id": 75822, "author": "Alex Lyman", "author_id": 5897, "author_profile": "https://Stackoverflow.com/users/5897", "pm_score": 7, "selected": true, "text": "<p>The problem occurs because the conditional operator doesn't look at how the value is used (assigned in this case) to determine the type of the expression -- just the true/false values. In this case, you have a <code>null</code> and an <code>Int32</code>, and the type can not be determined (there are real reasons it can't just assume <code>Nullable&lt;Int32&gt;</code>).</p>\n<p>If you really want to use it in this way, you must cast one of the values to <code>Nullable&lt;Int32&gt;</code> yourself, so C# can resolve the type:</p>\n<pre><code>EmployeeNumber =\n string.IsNullOrEmpty(employeeNumberTextBox.Text)\n ? (int?)null\n : Convert.ToInt32(employeeNumberTextBox.Text),\n</code></pre>\n<p>or</p>\n<pre><code>EmployeeNumber =\n string.IsNullOrEmpty(employeeNumberTextBox.Text)\n ? null\n : (int?)Convert.ToInt32(employeeNumberTextBox.Text),\n</code></pre>\n" }, { "answer_id": 75944, "author": "NerdFury", "author_id": 6146, "author_profile": "https://Stackoverflow.com/users/6146", "pm_score": 3, "selected": false, "text": "<p>I think a utility method could help make this cleaner.</p>\n\n<pre><code>public static class Convert\n{\n public static T? To&lt;T&gt;(string value, Converter&lt;string, T&gt; converter) where T: struct\n {\n return string.IsNullOrEmpty(value) ? null : (T?)converter(value);\n }\n}\n</code></pre>\n\n<p>then</p>\n\n<pre><code>EmployeeNumber = Convert.To&lt;int&gt;(employeeNumberTextBox.Text, Int32.Parse);\n</code></pre>\n" }, { "answer_id": 76049, "author": "user13493", "author_id": 13493, "author_profile": "https://Stackoverflow.com/users/13493", "pm_score": 3, "selected": false, "text": "<p>While Alex provides the correct and proximal answer to your question, I prefer to use <code>TryParse</code>:</p>\n\n<pre><code>int value;\nint? EmployeeNumber = int.TryParse(employeeNumberTextBox.Text, out value)\n ? (int?)value\n : null;\n</code></pre>\n\n<p>It's safer and takes care of cases of invalid input as well as your empty string scenario. Otherwise if the user inputs something like <code>1b</code> they will be presented with an error page with the unhandled exception caused in <code>Convert.ToInt32(string)</code>.</p>\n" }, { "answer_id": 29851598, "author": "Sandeep", "author_id": 1604050, "author_profile": "https://Stackoverflow.com/users/1604050", "pm_score": 1, "selected": false, "text": "<pre><code>//Some operation to populate Posid.I am not interested in zero or null\nint? Posid = SvcClient.GetHolidayCount(xDateFrom.Value.Date,xDateTo.Value.Date).Response;\nvar x1 = (Posid.HasValue &amp;&amp; Posid.Value &gt; 0) ? (int?)Posid.Value : null;\n</code></pre>\n\n<p>EDIT: \nBrief explanation of above, I was trying to get the value of <code>Posid</code> (if its nonnull <code>int</code> and having value greater than 0) in varibale <code>X1</code>. I had to use <code>(int?)</code> on <code>Posid.Value</code> to get the conditional operator not throwing any compilation error.\nJust a FYI <code>GetHolidayCount</code> is a <code>WCF</code> method that could give <code>null</code> or any number.\nHope that helps</p>\n" }, { "answer_id": 62727948, "author": "Glorfindel", "author_id": 4751173, "author_profile": "https://Stackoverflow.com/users/4751173", "pm_score": 0, "selected": false, "text": "<p>As of <a href=\"https://devblogs.microsoft.com/dotnet/welcome-to-c-9-0/#target-typed--and-\" rel=\"nofollow noreferrer\">C# 9.0</a>, this will finally be possible:</p>\n<blockquote>\n<h3>Target typed ?? and ?:</h3>\n<p>Sometimes conditional ?? and ?: expressions don’t have an obvious shared type between the branches. Such cases fail today, but C# 9.0 will allow them if there’s a target type that both branches convert to:</p>\n<pre><code>Person person = student ?? customer; // Shared base type\nint? result = b ? 0 : null; // nullable value type\n</code></pre>\n</blockquote>\n<p>That means the code block in the question will also compile without errors.</p>\n<pre><code>EmployeeNumber =\nstring.IsNullOrEmpty(employeeNumberTextBox.Text)\n ? null\n : Convert.ToInt32(employeeNumberTextBox.Text),\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/75746", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12975/" ]
``` EmployeeNumber = string.IsNullOrEmpty(employeeNumberTextBox.Text) ? null : Convert.ToInt32(employeeNumberTextBox.Text), ``` I often find myself wanting to do things like this (`EmployeeNumber` is a `Nullable<int>` as it's a property on a LINQ-to-SQL dbml object where the column allows NULL values). Unfortunately, the compiler feels that > > There is no implicit conversion between 'null' and 'int' > > > even though both types would be valid in an assignment operation to a nullable int on their own. Using the null coalescing operator is not an option as far as I can see because of the inline conversion that needs to happen on the `.Text` string if it's not null. As far as I know the only way to do this is to use an if statement and/or assign it in two steps. In this particular case I find that very frustrating because I wanted to use the object initializer syntax and this assignment would be in the initialization block... Does anyone know a more elegant solution?
The problem occurs because the conditional operator doesn't look at how the value is used (assigned in this case) to determine the type of the expression -- just the true/false values. In this case, you have a `null` and an `Int32`, and the type can not be determined (there are real reasons it can't just assume `Nullable<Int32>`). If you really want to use it in this way, you must cast one of the values to `Nullable<Int32>` yourself, so C# can resolve the type: ``` EmployeeNumber = string.IsNullOrEmpty(employeeNumberTextBox.Text) ? (int?)null : Convert.ToInt32(employeeNumberTextBox.Text), ``` or ``` EmployeeNumber = string.IsNullOrEmpty(employeeNumberTextBox.Text) ? null : (int?)Convert.ToInt32(employeeNumberTextBox.Text), ```
75,752
<p>I'm building a quick csv from a mysql table with a query like:</p> <pre><code>select DATE(date),count(date) from table group by DATE(date) order by date asc; </code></pre> <p>and just dumping them to a file in perl over a:</p> <pre><code>while(my($date,$sum) = $sth-&gt;fetchrow) { print CSV "$date,$sum\n" } </code></pre> <p>There are date gaps in the data, though:</p> <pre><code>| 2008-08-05 | 4 | | 2008-08-07 | 23 | </code></pre> <p>I would like to pad the data to fill in the missing days with zero-count entries to end up with:</p> <pre><code>| 2008-08-05 | 4 | | 2008-08-06 | 0 | | 2008-08-07 | 23 | </code></pre> <p>I slapped together a really awkward (and almost certainly buggy) workaround with an array of days-per-month and some math, but there has to be something more straightforward either on the mysql or perl side. </p> <p>Any genius ideas/slaps in the face for why me am being so dumb?</p> <hr> <p>I ended up going with a stored procedure which generated a temp table for the date range in question for a couple of reasons:</p> <ul> <li>I know the date range I'll be looking for every time</li> <li>The server in question unfortunately was not one that I can install perl modules on atm, and the state of it was decrepit enough that it didn't have anything remotely Date::-y installed</li> </ul> <p>The perl Date/DateTime-iterating answers were also very good, I wish I could select multiple answers!</p>
[ { "answer_id": 75807, "author": "Aeon", "author_id": 13289, "author_profile": "https://Stackoverflow.com/users/13289", "pm_score": 3, "selected": false, "text": "<p>When I had to deal with this problem, to fill in missing dates I actually created a reference table that just contained all dates I'm interested in and joined the data table on the date field. It's crude, but it works. </p>\n\n<pre><code>SELECT DATE(r.date),count(d.date) \nFROM dates AS r \nLEFT JOIN table AS d ON d.date = r.date \nGROUP BY DATE(r.date) \nORDER BY r.date ASC;\n</code></pre>\n\n<p>As for output, I'd just use <a href=\"http://dev.mysql.com/doc/refman/5.0/en/select.html\" rel=\"noreferrer\">SELECT INTO OUTFILE</a> instead of generating the CSV by hand. Leaves us free from worrying about escaping special characters as well.</p>\n" }, { "answer_id": 75837, "author": "Ben", "author_id": 11522, "author_profile": "https://Stackoverflow.com/users/11522", "pm_score": -1, "selected": false, "text": "<p>I don't know if this would work, but how about if you created a new table which contained all the possible dates (that might be the problem with this idea, if the range of dates is going to change unpredictably...) and then do a left join on the two tables? I guess it's a crazy solution if there are a vast number of possible dates, or no way to predict the first and last date, but if the range of dates is either fixed or easy to work out, then this might work.</p>\n" }, { "answer_id": 75865, "author": "coffeepac", "author_id": 13421, "author_profile": "https://Stackoverflow.com/users/13421", "pm_score": 2, "selected": false, "text": "<p>not dumb, this isn't something that MySQL does, inserting the empty date values. I do this in perl with a two-step process. First, load all of the data from the query into a hash organised by date. Then, I create a Date::EzDate object and increment it by day, so...</p>\n\n<pre><code>my $current_date = Date::EzDate-&gt;new();\n$current_date-&gt;{'default'} = '{YEAR}-{MONTH NUMBER BASE 1}-{DAY OF MONTH}';\nwhile ($current_date &lt;= $final_date)\n{\n print \"$current_date\\t|\\t%hash_o_data{$current_date}\"; # EzDate provides for automatic stringification in the format specfied in 'default'\n $current_date++;\n}\n</code></pre>\n\n<p>where final date is another EzDate object or a string containing the end of your date range. </p>\n\n<p>EzDate isn't on CPAN right now, but you can probably find another perl mod that will do date compares and provide a date incrementor. </p>\n" }, { "answer_id": 75890, "author": "Alexandr Ciornii", "author_id": 13467, "author_profile": "https://Stackoverflow.com/users/13467", "pm_score": 0, "selected": false, "text": "<p>Use some Perl module to do date calculations, like recommended DateTime or Time::Piece (core from 5.10). Just increment date and print date and 0 until date will match current.</p>\n" }, { "answer_id": 75928, "author": "GSerg", "author_id": 11683, "author_profile": "https://Stackoverflow.com/users/11683", "pm_score": 5, "selected": true, "text": "<p>When you need something like that on server side, you usually create a table which contains all possible dates between two points in time, and then left join this table with query results. Something like this:</p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>create procedure sp1(d1 date, d2 date)\n declare d datetime;\n\n create temporary table foo (d date not null);\n\n set d = d1\n while d &lt;= d2 do\n insert into foo (d) values (d)\n set d = date_add(d, interval 1 day)\n end while\n\n select foo.d, count(date)\n from foo left join table on foo.d = table.date\n group by foo.d order by foo.d asc;\n\n drop temporary table foo;\nend procedure\n</code></pre>\n\n<p>In this particular case it would be better to put a little check on the client side, if current date is not previos+1, put some addition strings.</p>\n" }, { "answer_id": 76081, "author": "8jean", "author_id": 10011, "author_profile": "https://Stackoverflow.com/users/10011", "pm_score": 2, "selected": false, "text": "<p>You could use a <a href=\"http://search.cpan.org/perldoc?DateTime\" rel=\"nofollow noreferrer\">DateTime</a> object:</p>\n\n<pre><code>use DateTime;\nmy $dt;\n\nwhile ( my ($date, $sum) = $sth-&gt;fetchrow ) {\n if (defined $dt) {\n print CSV $dt-&gt;ymd . \",0\\n\" while $dt-&gt;add(days =&gt; 1)-&gt;ymd lt $date;\n }\n else {\n my ($y, $m, $d) = split /-/, $date;\n $dt = DateTime-&gt;new(year =&gt; $y, month =&gt; $m, day =&gt; $d);\n }\n print CSV, \"$date,$sum\\n\";\n}\n</code></pre>\n\n<p>What the above code does is it keeps the last printed date stored in a\n<code>DateTime</code> object <code>$dt</code>, and when the current date is more than one day\nin the future, it increments <code>$dt</code> by one day (and prints it a line to\n<code>CSV</code>) until it is the same as the current date.</p>\n\n<p>This way you don't need extra tables, and don't need to fetch all your\nrows in advance.</p>\n" }, { "answer_id": 76147, "author": "castaway", "author_id": 4840, "author_profile": "https://Stackoverflow.com/users/4840", "pm_score": 1, "selected": false, "text": "<p>Since you don't know where the gaps are, and yet you want all the values (presumably) from the first date in your list to the last one, do something like:</p>\n\n<pre><code>use DateTime;\nuse DateTime::Format::Strptime;\nmy @row = $sth-&gt;fetchrow;\nmy $countdate = strptime(\"%Y-%m-%d\", $firstrow[0]);\nmy $thisdate = strptime(\"%Y-%m-%d\", $firstrow[0]);\n\nwhile ($countdate) {\n # keep looping countdate until it hits the next db row date\n if(DateTime-&gt;compare($countdate, $thisdate) == -1) {\n # counter not reached next date yet\n print CSV $countdate-&gt;ymd . \",0\\n\";\n $countdate = $countdate-&gt;add( days =&gt; 1 );\n $next;\n }\n\n # countdate is equal to next row's date, so print that instead\n print CSV $thisdate-&gt;ymd . \",$row[1]\\n\";\n\n # increase both\n @row = $sth-&gt;fetchrow;\n $thisdate = strptime(\"%Y-%m-%d\", $firstrow[0]);\n $countdate = $countdate-&gt;add( days =&gt; 1 );\n}\n</code></pre>\n\n<p>Hmm, that turned out to be more complicated than I thought it would be.. I hope it makes sense!</p>\n" }, { "answer_id": 6156000, "author": "theazureshadow", "author_id": 177633, "author_profile": "https://Stackoverflow.com/users/177633", "pm_score": 1, "selected": false, "text": "<p>I think the simplest general solution to the problem would be to create an <code>Ordinal</code> table with the highest number of rows that you need (in your case 31*3 = 93).</p>\n\n<pre><code>CREATE TABLE IF NOT EXISTS `Ordinal` (\n `n` int(10) unsigned NOT NULL AUTO_INCREMENT, PRIMARY KEY (`n`)\n);\nINSERT INTO `Ordinal` (`n`)\nVALUES (NULL), (NULL), (NULL); #etc\n</code></pre>\n\n<p>Next, do a <code>LEFT JOIN</code> from <code>Ordinal</code> onto your data. Here's a simple case, getting every day in the last week:</p>\n\n<pre><code>SELECT CURDATE() - INTERVAL `n` DAY AS `day`\nFROM `Ordinal` WHERE `n` &lt;= 7\nORDER BY `n` ASC\n</code></pre>\n\n<p>The two things you would need to change about this are the starting point and the interval. I have used <code>SET @var = 'value'</code> syntax for clarity.</p>\n\n<pre><code>SET @end = CURDATE() - INTERVAL DAY(CURDATE()) DAY;\nSET @begin = @end - INTERVAL 3 MONTH;\nSET @period = DATEDIFF(@end, @begin);\n\nSELECT @begin + INTERVAL (`n` + 1) DAY AS `date`\nFROM `Ordinal` WHERE `n` &lt; @period\nORDER BY `n` ASC;\n</code></pre>\n\n<p>So the final code would look something like this, if you were joining to get the number of messages per day over the last three months:</p>\n\n<pre><code>SELECT COUNT(`msg`.`id`) AS `message_count`, `ord`.`date` FROM (\n SELECT ((CURDATE() - INTERVAL DAY(CURDATE()) DAY) - INTERVAL 3 MONTH) + INTERVAL (`n` + 1) DAY AS `date`\n FROM `Ordinal`\n WHERE `n` &lt; (DATEDIFF((CURDATE() - INTERVAL DAY(CURDATE()) DAY), ((CURDATE() - INTERVAL DAY(CURDATE()) DAY) - INTERVAL 3 MONTH)))\n ORDER BY `n` ASC\n) AS `ord`\nLEFT JOIN `Message` AS `msg`\n ON `ord`.`date` = `msg`.`date`\nGROUP BY `ord`.`date`\n</code></pre>\n\n<p>Tips and Comments:</p>\n\n<ul>\n<li>Probably the hardest part of your query was determining the number of days to use when limiting <code>Ordinal</code>. By comparison, transforming that integer sequence into dates was easy.</li>\n<li>You can use <code>Ordinal</code> for all of your uninterrupted-sequence needs. Just make sure it contains more rows than your longest sequence.</li>\n<li>You can use multiple queries on <code>Ordinal</code> for multiple sequences, for example listing every weekday (1-5) for the past seven (1-7) weeks.</li>\n<li>You could make it faster by storing dates in your <code>Ordinal</code> table, but it would be less flexible. This way you only need one <code>Ordinal</code> table, no matter how many times you use it. Still, if the speed is worth it, try the <code>INSERT INTO ... SELECT</code> syntax.</li>\n</ul>\n" }, { "answer_id": 16318007, "author": "Igor Kryltsov", "author_id": 1051674, "author_profile": "https://Stackoverflow.com/users/1051674", "pm_score": 2, "selected": false, "text": "<p>I hope you will figure out the rest.</p>\n\n<pre><code>select * from (\nselect date_add('2003-01-01 00:00:00.000', INTERVAL n5.num*10000+n4.num*1000+n3.num*100+n2.num*10+n1.num DAY ) as date from\n(select 0 as num\n union all select 1\n union all select 2\n union all select 3\n union all select 4\n union all select 5\n union all select 6\n union all select 7\n union all select 8\n union all select 9) n1,\n(select 0 as num\n union all select 1\n union all select 2\n union all select 3\n union all select 4\n union all select 5\n union all select 6\n union all select 7\n union all select 8\n union all select 9) n2,\n(select 0 as num\n union all select 1\n union all select 2\n union all select 3\n union all select 4\n union all select 5\n union all select 6\n union all select 7\n union all select 8\n union all select 9) n3,\n(select 0 as num\n union all select 1\n union all select 2\n union all select 3\n union all select 4\n union all select 5\n union all select 6\n union all select 7\n union all select 8\n union all select 9) n4,\n(select 0 as num\n union all select 1\n union all select 2\n union all select 3\n union all select 4\n union all select 5\n union all select 6\n union all select 7\n union all select 8\n union all select 9) n5\n) a\nwhere date &gt;'2011-01-02 00:00:00.000' and date &lt; NOW()\norder by date\n</code></pre>\n\n<p>With </p>\n\n<pre><code>select n3.num*100+n2.num*10+n1.num as date\n</code></pre>\n\n<p>you will get a column with numbers from 0 to max(n3)*100+max(n2)*10+max(n1)</p>\n\n<p>Since here we have max n3 as 3, SELECT will return 399, plus 0 -> 400 records (dates in calendar).</p>\n\n<p>You can tune your dynamic calendar by limiting it, for example, from min(date) you have to now(). </p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/75752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13196/" ]
I'm building a quick csv from a mysql table with a query like: ``` select DATE(date),count(date) from table group by DATE(date) order by date asc; ``` and just dumping them to a file in perl over a: ``` while(my($date,$sum) = $sth->fetchrow) { print CSV "$date,$sum\n" } ``` There are date gaps in the data, though: ``` | 2008-08-05 | 4 | | 2008-08-07 | 23 | ``` I would like to pad the data to fill in the missing days with zero-count entries to end up with: ``` | 2008-08-05 | 4 | | 2008-08-06 | 0 | | 2008-08-07 | 23 | ``` I slapped together a really awkward (and almost certainly buggy) workaround with an array of days-per-month and some math, but there has to be something more straightforward either on the mysql or perl side. Any genius ideas/slaps in the face for why me am being so dumb? --- I ended up going with a stored procedure which generated a temp table for the date range in question for a couple of reasons: * I know the date range I'll be looking for every time * The server in question unfortunately was not one that I can install perl modules on atm, and the state of it was decrepit enough that it didn't have anything remotely Date::-y installed The perl Date/DateTime-iterating answers were also very good, I wish I could select multiple answers!
When you need something like that on server side, you usually create a table which contains all possible dates between two points in time, and then left join this table with query results. Something like this: ```sql create procedure sp1(d1 date, d2 date) declare d datetime; create temporary table foo (d date not null); set d = d1 while d <= d2 do insert into foo (d) values (d) set d = date_add(d, interval 1 day) end while select foo.d, count(date) from foo left join table on foo.d = table.date group by foo.d order by foo.d asc; drop temporary table foo; end procedure ``` In this particular case it would be better to put a little check on the client side, if current date is not previos+1, put some addition strings.
75,759
<p>What's the best way to implement the enum idiom in Ruby? I'm looking for something which I can use (almost) like the Java/C# enums.</p>
[ { "answer_id": 75787, "author": "Jan Krüger", "author_id": 12471, "author_profile": "https://Stackoverflow.com/users/12471", "pm_score": 1, "selected": false, "text": "<p>Most people use symbols (that's the <code>:foo_bar</code> syntax). They're sort of unique opaque values. Symbols don't belong to any enum-style type so they're not really a faithful representation of C's enum type but this is pretty much as good as it gets.</p>\n" }, { "answer_id": 75801, "author": "emk", "author_id": 12089, "author_profile": "https://Stackoverflow.com/users/12089", "pm_score": 6, "selected": false, "text": "<p>The most idiomatic way to do this is to use symbols. For example, instead of:</p>\n\n<pre><code>enum {\n FOO,\n BAR,\n BAZ\n}\n\nmyFunc(FOO);\n</code></pre>\n\n<p>...you can just use symbols:</p>\n\n<pre><code># You don't actually need to declare these, of course--this is\n# just to show you what symbols look like.\n:foo\n:bar\n:baz\n\nmy_func(:foo)\n</code></pre>\n\n<p>This is a bit more open-ended than enums, but it fits well with the Ruby spirit.</p>\n\n<p>Symbols also perform very well. Comparing two symbols for equality, for example, is much faster than comparing two strings.</p>\n" }, { "answer_id": 76046, "author": "mlibby", "author_id": 13468, "author_profile": "https://Stackoverflow.com/users/13468", "pm_score": 9, "selected": true, "text": "<p>Two ways. Symbols (<code>:foo</code> notation) or constants (<code>FOO</code> notation).</p>\n<p>Symbols are appropriate when you want to enhance readability without littering code with literal strings.</p>\n<pre><code>postal_code[:minnesota] = &quot;MN&quot;\npostal_code[:new_york] = &quot;NY&quot;\n</code></pre>\n<p>Constants are appropriate when you have an underlying value that is important. Just declare a module to hold your constants and then declare the constants within that.</p>\n<pre><code>module Foo\n BAR = 1\n BAZ = 2\n BIZ = 4\nend\n \nflags = Foo::BAR | Foo::BAZ # flags = 3\n</code></pre>\n<p>Added 2021-01-17</p>\n<p>If you are passing the enum value around (for example, storing it in a database) and you need to be able to translate the value back into the symbol, there's a mashup of both approaches</p>\n<pre><code>COMMODITY_TYPE = {\n currency: 1,\n investment: 2,\n}\n\ndef commodity_type_string(value)\n COMMODITY_TYPE.key(value)\nend\n\nCOMMODITY_TYPE[:currency]\n</code></pre>\n<p>This approach inspired by andrew-grimm's answer <a href=\"https://stackoverflow.com/a/5332950/13468\">https://stackoverflow.com/a/5332950/13468</a></p>\n<p>I'd also recommend reading through the rest of the answers here since there are a lot of ways to solve this and it really boils down to what it is about the other language's enum that you care about</p>\n" }, { "answer_id": 76722, "author": "mislav", "author_id": 11687, "author_profile": "https://Stackoverflow.com/users/11687", "pm_score": 2, "selected": false, "text": "<p>It all depends how you use Java or C# enums. How you use it will dictate the solution you'll choose in Ruby.</p>\n\n<p>Try the native <code>Set</code> type, for instance:</p>\n\n<pre><code>&gt;&gt; enum = Set['a', 'b', 'c']\n=&gt; #&lt;Set: {\"a\", \"b\", \"c\"}&gt;\n&gt;&gt; enum.member? \"b\"\n=&gt; true\n&gt;&gt; enum.member? \"d\"\n=&gt; false\n&gt;&gt; enum.add? \"b\"\n=&gt; nil\n&gt;&gt; enum.add? \"d\"\n=&gt; #&lt;Set: {\"a\", \"b\", \"c\", \"d\"}&gt;\n</code></pre>\n" }, { "answer_id": 164514, "author": "Jonke", "author_id": 15638, "author_profile": "https://Stackoverflow.com/users/15638", "pm_score": 2, "selected": false, "text": "<p>Symbols is the ruby way. However, sometimes one need to talk to some C code or something or Java that expose some enum for various things.</p>\n\n<hr>\n\n<pre><code>#server_roles.rb\nmodule EnumLike\n\n def EnumLike.server_role\n server_Symb=[ :SERVER_CLOUD, :SERVER_DESKTOP, :SERVER_WORKSTATION]\n server_Enum=Hash.new\n i=0\n server_Symb.each{ |e| server_Enum[e]=i; i +=1}\n return server_Symb,server_Enum\n end\n\nend\n</code></pre>\n\n<hr>\n\n<p>This can then be used like this</p>\n\n<hr>\n\n<pre><code>require 'server_roles'\n\nsSymb, sEnum =EnumLike.server_role()\n\nforeignvec[sEnum[:SERVER_WORKSTATION]]=8\n</code></pre>\n\n<hr>\n\n<p>This is can of course be made abstract and you can roll our own Enum class </p>\n" }, { "answer_id": 612357, "author": "dlamblin", "author_id": 459, "author_profile": "https://Stackoverflow.com/users/459", "pm_score": 2, "selected": false, "text": "<p>Someone went ahead and wrote a ruby gem called <a href=\"http://renum.rubyforge.org/\" rel=\"nofollow noreferrer\">Renum</a>. It claims to get the closest Java/C# like behavior. Personally I'm still learning Ruby, and I was a little shocked when I wanted to make a specific class contain a static enum, possibly a hash, that it wasn't exactly easily found via google.</p>\n" }, { "answer_id": 1494092, "author": "Philippe Monnet", "author_id": 23308, "author_profile": "https://Stackoverflow.com/users/23308", "pm_score": 0, "selected": false, "text": "<p>Another approach is to use a Ruby class with a hash containing names and values as described in the following <a href=\"http://www.rubyfleebie.com/enumerations-and-ruby/\" rel=\"nofollow noreferrer\">RubyFleebie blog post</a>. This allows you to convert easily between values and constants (especially if you add a class method to lookup the name for a given value).</p>\n" }, { "answer_id": 2573093, "author": "goreorto", "author_id": 308517, "author_profile": "https://Stackoverflow.com/users/308517", "pm_score": 0, "selected": false, "text": "<p>I think the best way to implement enumeration like types is with symbols since the pretty much behave as integer (when it comes to performace, object_id is used to make comparisons ); you don't need to worry about indexing and they look really neat in your code xD</p>\n" }, { "answer_id": 5332215, "author": "dB.", "author_id": 123094, "author_profile": "https://Stackoverflow.com/users/123094", "pm_score": 3, "selected": false, "text": "<p>Check out the ruby-enum gem, <a href=\"https://github.com/dblock/ruby-enum\" rel=\"noreferrer\">https://github.com/dblock/ruby-enum</a>.</p>\n\n<pre><code>class Gender\n include Enum\n\n Gender.define :MALE, \"male\"\n Gender.define :FEMALE, \"female\"\nend\n\nGender.all\nGender::MALE\n</code></pre>\n" }, { "answer_id": 5332950, "author": "Andrew Grimm", "author_id": 38765, "author_profile": "https://Stackoverflow.com/users/38765", "pm_score": 3, "selected": false, "text": "<p>If you're worried about typos with symbols, make sure your code raises an exception when you access a value with a non-existent key. You can do this by using <code>fetch</code> rather than <code>[]</code>:</p>\n\n<pre><code>my_value = my_hash.fetch(:key)\n</code></pre>\n\n<p>or by making the hash raise an exception by default if you supply a non-existent key:</p>\n\n<pre><code>my_hash = Hash.new do |hash, key|\n raise \"You tried to access using #{key.inspect} when the only keys we have are #{hash.keys.inspect}\"\nend\n</code></pre>\n\n<p>If the hash already exists, you can add on exception-raising behaviour:</p>\n\n<pre><code>my_hash = Hash[[[1,2]]]\nmy_hash.default_proc = proc do |hash, key|\n raise \"You tried to access using #{key.inspect} when the only keys we have are #{hash.keys.inspect}\"\nend\n</code></pre>\n\n<p>Normally, you don't have to worry about typo safety with constants. If you misspell a constant name, it'll usually raise an exception.</p>\n" }, { "answer_id": 5675566, "author": "Alexey", "author_id": 126529, "author_profile": "https://Stackoverflow.com/users/126529", "pm_score": 6, "selected": false, "text": "<p>I use the following approach:</p>\n\n<pre><code>class MyClass\n MY_ENUM = [MY_VALUE_1 = 'value1', MY_VALUE_2 = 'value2']\nend\n</code></pre>\n\n<p>I like it for the following advantages:</p>\n\n<ol>\n<li>It groups values visually as one whole</li>\n<li>It does some compilation-time checking (in contrast with just using symbols)</li>\n<li>I can easily access the list of all possible values: just <code>MY_ENUM</code></li>\n<li>I can easily access distinct values: <code>MY_VALUE_1</code></li>\n<li>It can have values of any type, not just Symbol</li>\n</ol>\n\n<p>Symbols may be better cause you don't have to write the name of outer class, if you are using it in another class (<code>MyClass::MY_VALUE_1</code>)</p>\n" }, { "answer_id": 6170494, "author": "Charles", "author_id": 48483, "author_profile": "https://Stackoverflow.com/users/48483", "pm_score": 6, "selected": false, "text": "<p>I'm surprised that no one has offered something like the following (harvested from the <a href=\"https://github.com/cstrahan/rapi/blob/master/lib/rapi.rb\" rel=\"noreferrer\">RAPI</a> gem):</p>\n\n<pre><code>class Enum\n\n private\n\n def self.enum_attr(name, num)\n name = name.to_s\n\n define_method(name + '?') do\n @attrs &amp; num != 0\n end\n\n define_method(name + '=') do |set|\n if set\n @attrs |= num\n else\n @attrs &amp;= ~num\n end\n end\n end\n\n public\n\n def initialize(attrs = 0)\n @attrs = attrs\n end\n\n def to_i\n @attrs\n end\nend\n</code></pre>\n\n<p>Which can be used like so:</p>\n\n<pre><code>class FileAttributes &lt; Enum\n enum_attr :readonly, 0x0001\n enum_attr :hidden, 0x0002\n enum_attr :system, 0x0004\n enum_attr :directory, 0x0010\n enum_attr :archive, 0x0020\n enum_attr :in_rom, 0x0040\n enum_attr :normal, 0x0080\n enum_attr :temporary, 0x0100\n enum_attr :sparse, 0x0200\n enum_attr :reparse_point, 0x0400\n enum_attr :compressed, 0x0800\n enum_attr :rom_module, 0x2000\nend\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>&gt;&gt; example = FileAttributes.new(3)\n=&gt; #&lt;FileAttributes:0x629d90 @attrs=3&gt;\n&gt;&gt; example.readonly?\n=&gt; true\n&gt;&gt; example.hidden?\n=&gt; true\n&gt;&gt; example.system?\n=&gt; false\n&gt;&gt; example.system = true\n=&gt; true\n&gt;&gt; example.system?\n=&gt; true\n&gt;&gt; example.to_i\n=&gt; 7\n</code></pre>\n\n<p>This plays well in database scenarios, or when dealing with C style constants/enums (as is the case when using <a href=\"https://github.com/ffi/ffi/\" rel=\"noreferrer\">FFI</a>, which RAPI makes extensive use of).</p>\n\n<p>Also, you don't have to worry about typos causing silent failures, as you would with using a hash-type solution.</p>\n" }, { "answer_id": 9482922, "author": "Masuschi", "author_id": 1238002, "author_profile": "https://Stackoverflow.com/users/1238002", "pm_score": 2, "selected": false, "text": "<p>I have implemented enums like that </p>\n\n<pre><code>module EnumType\n\n def self.find_by_id id\n if id.instance_of? String\n id = id.to_i\n end \n values.each do |type|\n if id == type.id\n return type\n end\n end\n nil\n end\n\n def self.values\n [@ENUM_1, @ENUM_2] \n end\n\n class Enum\n attr_reader :id, :label\n\n def initialize id, label\n @id = id\n @label = label\n end\n end\n\n @ENUM_1 = Enum.new(1, \"first\")\n @ENUM_2 = Enum.new(2, \"second\")\n\nend\n</code></pre>\n\n<p>then its easy to do operations </p>\n\n<pre><code>EnumType.ENUM_1.label\n</code></pre>\n\n<p>...</p>\n\n<pre><code>enum = EnumType.find_by_id 1\n</code></pre>\n\n<p>...</p>\n\n<pre><code>valueArray = EnumType.values\n</code></pre>\n" }, { "answer_id": 9582957, "author": "Anu", "author_id": 1252072, "author_profile": "https://Stackoverflow.com/users/1252072", "pm_score": 1, "selected": false, "text": "<pre><code>irb(main):016:0&gt; num=[1,2,3,4]\nirb(main):017:0&gt; alph=['a','b','c','d']\nirb(main):018:0&gt; l_enum=alph.to_enum\nirb(main):019:0&gt; s_enum=num.to_enum\nirb(main):020:0&gt; loop do\nirb(main):021:1* puts \"#{s_enum.next} - #{l_enum.next}\"\nirb(main):022:1&gt; end\n</code></pre>\n\n<p>Output:</p>\n\n<p>1 - a<br>\n2 - b<br>\n3 - c<br>\n4 - d</p>\n" }, { "answer_id": 11432676, "author": "Hossein", "author_id": 1107992, "author_profile": "https://Stackoverflow.com/users/1107992", "pm_score": 2, "selected": false, "text": "<pre><code>module Status\n BAD = 13\n GOOD = 24\n\n def self.to_str(status)\n for sym in self.constants\n if self.const_get(sym) == status\n return sym.to_s\n end\n end\n end\n\nend\n\n\nmystatus = Status::GOOD\n\nputs Status::to_str(mystatus)\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>GOOD\n</code></pre>\n" }, { "answer_id": 11455651, "author": "johnnypez", "author_id": 366277, "author_profile": "https://Stackoverflow.com/users/366277", "pm_score": 4, "selected": false, "text": "<p>This is my approach to enums in Ruby. I was going for short and sweet, not necessarily the the most C-like. Any thoughts?</p>\n<pre><code>module Kernel\n def enum(values)\n Module.new do |mod|\n values.each_with_index{ |v,i| mod.const_set(v.to_s.capitalize, 2**i) }\n\n def mod.inspect\n &quot;#{self.name} {#{self.constants.join(', ')}}&quot;\n end\n end\n end\nend\n\nStates = enum %w(Draft Published Trashed)\n=&gt; States {Draft, Published, Trashed} \n\nStates::Draft\n=&gt; 1\n\nStates::Published\n=&gt; 2\n\nStates::Trashed\n=&gt; 4\n\nStates::Draft | States::Trashed\n=&gt; 5\n</code></pre>\n" }, { "answer_id": 13764335, "author": "Oded Niv", "author_id": 1056158, "author_profile": "https://Stackoverflow.com/users/1056158", "pm_score": 4, "selected": false, "text": "<p>I know it's been a long time since the guy posted this question, but I had the same question and this post didn't give me the answer. I wanted an easy way to see what the number represents, easy comparison, and most of all ActiveRecord support for lookup using the column representing the enum.</p>\n\n<p>I didn't find anything, so I made an awesome implementation called <a href=\"https://github.com/toplex/enum\" rel=\"nofollow noreferrer\">yinum</a> which allowed everything I was looking for. Made ton of specs, so I'm pretty sure it's safe.</p>\n\n<p>Some example features:</p>\n\n<pre><code>COLORS = Enum.new(:COLORS, :red =&gt; 1, :green =&gt; 2, :blue =&gt; 3)\n=&gt; COLORS(:red =&gt; 1, :green =&gt; 2, :blue =&gt; 3)\nCOLORS.red == 1 &amp;&amp; COLORS.red == :red\n=&gt; true\n\nclass Car &lt; ActiveRecord::Base \n attr_enum :color, :COLORS, :red =&gt; 1, :black =&gt; 2\nend\ncar = Car.new\ncar.color = :red / \"red\" / 1 / \"1\"\ncar.color\n=&gt; Car::COLORS.red\ncar.color.black?\n=&gt; false\nCar.red.to_sql\n=&gt; \"SELECT `cars`.* FROM `cars` WHERE `cars`.`color` = 1\"\nCar.last.red?\n=&gt; true\n</code></pre>\n" }, { "answer_id": 14087590, "author": "Daniel Doubleday", "author_id": 1104754, "author_profile": "https://Stackoverflow.com/users/1104754", "pm_score": 0, "selected": false, "text": "<p>Another way to mimic an enum with consistent equality handling (shamelessly adopted from Dave Thomas). Allows open enums (much like symbols) and closed (predefined) enums.</p>\n\n<pre><code>class Enum\n def self.new(values = nil)\n enum = Class.new do\n unless values\n def self.const_missing(name)\n const_set(name, new(name))\n end\n end\n\n def initialize(name)\n @enum_name = name\n end\n\n def to_s\n \"#{self.class}::#@enum_name\"\n end\n end\n\n if values\n enum.instance_eval do\n values.each { |e| const_set(e, enum.new(e)) }\n end\n end\n\n enum\n end\nend\n\nGenre = Enum.new %w(Gothic Metal) # creates closed enum\nArchitecture = Enum.new # creates open enum\n\nGenre::Gothic == Genre::Gothic # =&gt; true\nGenre::Gothic != Architecture::Gothic # =&gt; true\n</code></pre>\n" }, { "answer_id": 16046129, "author": "jjk", "author_id": 1965639, "author_profile": "https://Stackoverflow.com/users/1965639", "pm_score": 2, "selected": false, "text": "<p>This seems a bit superfluous, but this is a methodology that I have used a few times, especially where I am integrating with xml or some such.</p>\n\n<pre><code>#model\nclass Profession\n def self.pro_enum\n {:BAKER =&gt; 0, \n :MANAGER =&gt; 1, \n :FIREMAN =&gt; 2, \n :DEV =&gt; 3, \n :VAL =&gt; [\"BAKER\", \"MANAGER\", \"FIREMAN\", \"DEV\"]\n }\n end\nend\n\nProfession.pro_enum[:DEV] #=&gt;3\nProfession.pro_enum[:VAL][1] #=&gt;MANAGER\n</code></pre>\n\n<p>This gives me the rigor of a c# enum and it is tied to the model.</p>\n" }, { "answer_id": 27349423, "author": "Vedant Agarwala", "author_id": 1396264, "author_profile": "https://Stackoverflow.com/users/1396264", "pm_score": 4, "selected": false, "text": "<p>If you are using Rails 4.2 or greater you can use Rails enums.</p>\n\n<p>Rails now has enums by default without the need for including any gems.</p>\n\n<p>This is very similar (and more with features) to Java, C++ enums.</p>\n\n<p>Quoted from <a href=\"http://edgeapi.rubyonrails.org/classes/ActiveRecord/Enum.html\" rel=\"noreferrer\">http://edgeapi.rubyonrails.org/classes/ActiveRecord/Enum.html</a> :</p>\n\n<pre><code>class Conversation &lt; ActiveRecord::Base\n enum status: [ :active, :archived ]\nend\n\n# conversation.update! status: 0\nconversation.active!\nconversation.active? # =&gt; true\nconversation.status # =&gt; \"active\"\n\n# conversation.update! status: 1\nconversation.archived!\nconversation.archived? # =&gt; true\nconversation.status # =&gt; \"archived\"\n\n# conversation.update! status: 1\nconversation.status = \"archived\"\n\n# conversation.update! status: nil\nconversation.status = nil\nconversation.status.nil? # =&gt; true\nconversation.status # =&gt; nil\n</code></pre>\n" }, { "answer_id": 27574382, "author": "Daniel Lubarov", "author_id": 714009, "author_profile": "https://Stackoverflow.com/users/714009", "pm_score": 3, "selected": false, "text": "<p>Perhaps the best lightweight approach would be</p>\n\n<pre><code>module MyConstants\n ABC = Class.new\n DEF = Class.new\n GHI = Class.new\nend\n</code></pre>\n\n<p>This way values have associated names, as in Java/C#:</p>\n\n<pre><code>MyConstants::ABC\n=&gt; MyConstants::ABC\n</code></pre>\n\n<p>To get all values, you can do</p>\n\n<pre><code>MyConstants.constants\n=&gt; [:ABC, :DEF, :GHI] \n</code></pre>\n\n<p>If you want an enum's ordinal value, you can do</p>\n\n<pre><code>MyConstants.constants.index :GHI\n=&gt; 2\n</code></pre>\n" }, { "answer_id": 32149803, "author": "dark_src", "author_id": 371572, "author_profile": "https://Stackoverflow.com/users/371572", "pm_score": 1, "selected": false, "text": "<p>Sometimes all I need is to be able to fetch enum's value and identify its name similar to java world.</p>\n\n<pre><code>module Enum\n def get_value(str)\n const_get(str)\n end\n def get_name(sym)\n sym.to_s.upcase\n end\n end\n\n class Fruits\n include Enum\n APPLE = \"Delicious\"\n MANGO = \"Sweet\"\n end\n\n Fruits.get_value('APPLE') #'Delicious'\n Fruits.get_value('MANGO') # 'Sweet'\n\n Fruits.get_name(:apple) # 'APPLE'\n Fruits.get_name(:mango) # 'MANGO'\n</code></pre>\n\n<p>This to me serves the purpose of enum and keeps it very extensible too. You can add more methods to the Enum class and viola get them for free in all the defined enums. for example. get_all_names and stuff like that.</p>\n" }, { "answer_id": 34498312, "author": "ka8725", "author_id": 1178074, "author_profile": "https://Stackoverflow.com/users/1178074", "pm_score": 2, "selected": false, "text": "<p>Recently we released a <a href=\"https://github.com/mezuka/enum\" rel=\"nofollow\">gem</a> that implements <strong>Enums in Ruby</strong>. In my <a href=\"http://railsguides.net/safe-enums-in-ruby/\" rel=\"nofollow\">post</a> you will find the answers on your questions. Also I described there why our implementation is better than existing ones (actually there are many implementations of this feature in Ruby yet as gems). </p>\n" }, { "answer_id": 45097718, "author": "Roger", "author_id": 549010, "author_profile": "https://Stackoverflow.com/users/549010", "pm_score": 3, "selected": false, "text": "<p>Another solution is using OpenStruct. Its pretty straight forward and clean.</p>\n\n<p><a href=\"https://ruby-doc.org/stdlib-2.3.1/libdoc/ostruct/rdoc/OpenStruct.html\" rel=\"noreferrer\">https://ruby-doc.org/stdlib-2.3.1/libdoc/ostruct/rdoc/OpenStruct.html</a></p>\n\n<p>Example:</p>\n\n<pre><code># bar.rb\nrequire 'ostruct' # not needed when using Rails\n\n# by patching Array you have a simple way of creating a ENUM-style\nclass Array\n def to_enum(base=0)\n OpenStruct.new(map.with_index(base).to_h)\n end\nend\n\nclass Bar\n\n MY_ENUM = OpenStruct.new(ONE: 1, TWO: 2, THREE: 3)\n MY_ENUM2 = %w[ONE TWO THREE].to_enum\n\n def use_enum (value)\n case value\n when MY_ENUM.ONE\n puts \"Hello, this is ENUM 1\"\n when MY_ENUM.TWO\n puts \"Hello, this is ENUM 2\"\n when MY_ENUM.THREE\n puts \"Hello, this is ENUM 3\"\n else\n puts \"#{value} not found in ENUM\"\n end\n end\n\nend\n\n# usage\nfoo = Bar.new \nfoo.use_enum 1\nfoo.use_enum 2\nfoo.use_enum 9\n\n\n# put this code in a file 'bar.rb', start IRB and type: load 'bar.rb'\n</code></pre>\n" }, { "answer_id": 48199917, "author": "horun", "author_id": 3940165, "author_profile": "https://Stackoverflow.com/users/3940165", "pm_score": 1, "selected": false, "text": "<p>Try the inum.\n<a href=\"https://github.com/alfa-jpn/inum\" rel=\"nofollow noreferrer\">https://github.com/alfa-jpn/inum</a></p>\n\n<pre class=\"lang-js prettyprint-override\"><code>class Color &lt; Inum::Base\n define :RED\n define :GREEN\n define :BLUE\nend\n</code></pre>\n\n<pre class=\"lang-js prettyprint-override\"><code>Color::RED \nColor.parse('blue') # =&gt; Color::BLUE\nColor.parse(2) # =&gt; Color::GREEN\n</code></pre>\n\n<p>see more <a href=\"https://github.com/alfa-jpn/inum#usage\" rel=\"nofollow noreferrer\">https://github.com/alfa-jpn/inum#usage</a></p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/75759", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4110/" ]
What's the best way to implement the enum idiom in Ruby? I'm looking for something which I can use (almost) like the Java/C# enums.
Two ways. Symbols (`:foo` notation) or constants (`FOO` notation). Symbols are appropriate when you want to enhance readability without littering code with literal strings. ``` postal_code[:minnesota] = "MN" postal_code[:new_york] = "NY" ``` Constants are appropriate when you have an underlying value that is important. Just declare a module to hold your constants and then declare the constants within that. ``` module Foo BAR = 1 BAZ = 2 BIZ = 4 end flags = Foo::BAR | Foo::BAZ # flags = 3 ``` Added 2021-01-17 If you are passing the enum value around (for example, storing it in a database) and you need to be able to translate the value back into the symbol, there's a mashup of both approaches ``` COMMODITY_TYPE = { currency: 1, investment: 2, } def commodity_type_string(value) COMMODITY_TYPE.key(value) end COMMODITY_TYPE[:currency] ``` This approach inspired by andrew-grimm's answer <https://stackoverflow.com/a/5332950/13468> I'd also recommend reading through the rest of the answers here since there are a lot of ways to solve this and it really boils down to what it is about the other language's enum that you care about
75,785
<p>Is there any complete guidance on doing AppBar docking (such as locking to the screen edge) in WPF? I understand there are InterOp calls that need to be made, but I'm looking for either a proof of concept based on a simple WPF form, or a componentized version that can be consumed.</p> <p>Related resources:</p> <ul> <li><a href="http://www.codeproject.com/KB/dotnet/AppBar.aspx" rel="noreferrer">http://www.codeproject.com/KB/dotnet/AppBar.aspx</a></li> <li><a href="http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/05c73c9c-e85d-4ecd-b9b6-4c714a65e72b/" rel="noreferrer">http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/05c73c9c-e85d-4ecd-b9b6-4c714a65e72b/</a></li> </ul>
[ { "answer_id": 84987, "author": "Philip Rieck", "author_id": 12643, "author_profile": "https://Stackoverflow.com/users/12643", "pm_score": 8, "selected": true, "text": "<p><strong>Please Note:</strong> This question gathered a good amount of feedback, and some people below have made great points or fixes. Therefore, while I'll keep the code here (and possibly update it), I've also <strong>created a <a href=\"https://github.com/PhilipRieck/WpfAppBar\" rel=\"noreferrer\">WpfAppBar project on github</a></strong>. Feel free to send pull requests. </p>\n\n<p>That same project also builds to a <a href=\"https://www.nuget.org/packages/WpfAppBar/\" rel=\"noreferrer\">WpfAppBar nuget package</a> </p>\n\n<hr>\n\n<p>I took the code from the first link provided in the question ( <a href=\"http://www.codeproject.com/KB/dotnet/AppBar.aspx\" rel=\"noreferrer\">http://www.codeproject.com/KB/dotnet/AppBar.aspx</a> ) and modified it to do two things:</p>\n\n<ol>\n<li>Work with WPF</li>\n<li>Be \"standalone\" - if you put this single file in your project, you can call AppBarFunctions.SetAppBar(...) without any further modification to the window.</li>\n</ol>\n\n<p>This approach doesn't create a base class.</p>\n\n<p>To use, just call this code from anywhere within a normal wpf window (say a button click or the initialize). Note that you can not call this until AFTER the window is initialized, if the HWND hasn't been created yet (like in the constructor), an error will occur.</p>\n\n<p>Make the window an appbar:</p>\n\n<pre><code>AppBarFunctions.SetAppBar( this, ABEdge.Right );\n</code></pre>\n\n<p>Restore the window to a normal window:</p>\n\n<pre><code>AppBarFunctions.SetAppBar( this, ABEdge.None );\n</code></pre>\n\n<p>Here's the full code to the file - <strong>note</strong> you'll want to change the namespace on line 7 to something apropriate.</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Runtime.InteropServices;\nusing System.Windows;\nusing System.Windows.Interop;\nusing System.Windows.Threading;\n\nnamespace AppBarApplication\n{ \n public enum ABEdge : int\n {\n Left = 0,\n Top,\n Right,\n Bottom,\n None\n }\n\n internal static class AppBarFunctions\n {\n [StructLayout(LayoutKind.Sequential)]\n private struct RECT\n {\n public int left;\n public int top;\n public int right;\n public int bottom;\n }\n\n [StructLayout(LayoutKind.Sequential)]\n private struct APPBARDATA\n {\n public int cbSize;\n public IntPtr hWnd;\n public int uCallbackMessage;\n public int uEdge;\n public RECT rc;\n public IntPtr lParam;\n }\n\n private enum ABMsg : int\n {\n ABM_NEW = 0,\n ABM_REMOVE,\n ABM_QUERYPOS,\n ABM_SETPOS,\n ABM_GETSTATE,\n ABM_GETTASKBARPOS,\n ABM_ACTIVATE,\n ABM_GETAUTOHIDEBAR,\n ABM_SETAUTOHIDEBAR,\n ABM_WINDOWPOSCHANGED,\n ABM_SETSTATE\n }\n private enum ABNotify : int\n {\n ABN_STATECHANGE = 0,\n ABN_POSCHANGED,\n ABN_FULLSCREENAPP,\n ABN_WINDOWARRANGE\n }\n\n [DllImport(\"SHELL32\", CallingConvention = CallingConvention.StdCall)]\n private static extern uint SHAppBarMessage(int dwMessage, ref APPBARDATA pData);\n\n [DllImport(\"User32.dll\", CharSet = CharSet.Auto)]\n private static extern int RegisterWindowMessage(string msg);\n\n private class RegisterInfo\n {\n public int CallbackId { get; set; }\n public bool IsRegistered { get; set; }\n public Window Window { get; set; }\n public ABEdge Edge { get; set; }\n public WindowStyle OriginalStyle { get; set; } \n public Point OriginalPosition { get; set; }\n public Size OriginalSize { get; set; }\n public ResizeMode OriginalResizeMode { get; set; }\n\n\n public IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, \n IntPtr lParam, ref bool handled)\n {\n if (msg == CallbackId)\n {\n if (wParam.ToInt32() == (int)ABNotify.ABN_POSCHANGED)\n {\n ABSetPos(Edge, Window);\n handled = true;\n }\n }\n return IntPtr.Zero;\n }\n\n }\n private static Dictionary&lt;Window, RegisterInfo&gt; s_RegisteredWindowInfo \n = new Dictionary&lt;Window, RegisterInfo&gt;();\n private static RegisterInfo GetRegisterInfo(Window appbarWindow)\n {\n RegisterInfo reg;\n if( s_RegisteredWindowInfo.ContainsKey(appbarWindow))\n {\n reg = s_RegisteredWindowInfo[appbarWindow];\n }\n else\n {\n reg = new RegisterInfo()\n {\n CallbackId = 0,\n Window = appbarWindow,\n IsRegistered = false,\n Edge = ABEdge.Top,\n OriginalStyle = appbarWindow.WindowStyle, \n OriginalPosition =new Point( appbarWindow.Left, appbarWindow.Top),\n OriginalSize = \n new Size( appbarWindow.ActualWidth, appbarWindow.ActualHeight),\n OriginalResizeMode = appbarWindow.ResizeMode,\n };\n s_RegisteredWindowInfo.Add(appbarWindow, reg);\n }\n return reg;\n }\n\n private static void RestoreWindow(Window appbarWindow)\n {\n RegisterInfo info = GetRegisterInfo(appbarWindow);\n\n appbarWindow.WindowStyle = info.OriginalStyle; \n appbarWindow.ResizeMode = info.OriginalResizeMode;\n appbarWindow.Topmost = false;\n\n Rect rect = new Rect(info.OriginalPosition.X, info.OriginalPosition.Y, \n info.OriginalSize.Width, info.OriginalSize.Height);\n appbarWindow.Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle,\n new ResizeDelegate(DoResize), appbarWindow, rect);\n\n }\n\n public static void SetAppBar(Window appbarWindow, ABEdge edge)\n {\n RegisterInfo info = GetRegisterInfo(appbarWindow);\n info.Edge = edge;\n\n APPBARDATA abd = new APPBARDATA();\n abd.cbSize = Marshal.SizeOf(abd);\n abd.hWnd = new WindowInteropHelper(appbarWindow).Handle;\n\n if( edge == ABEdge.None)\n {\n if( info.IsRegistered)\n {\n SHAppBarMessage((int)ABMsg.ABM_REMOVE, ref abd);\n info.IsRegistered = false;\n }\n RestoreWindow(appbarWindow);\n return;\n }\n\n if (!info.IsRegistered)\n {\n info.IsRegistered = true; \n info.CallbackId = RegisterWindowMessage(\"AppBarMessage\");\n abd.uCallbackMessage = info.CallbackId;\n\n uint ret = SHAppBarMessage((int)ABMsg.ABM_NEW, ref abd);\n\n HwndSource source = HwndSource.FromHwnd(abd.hWnd);\n source.AddHook(new HwndSourceHook(info.WndProc));\n }\n\n appbarWindow.WindowStyle = WindowStyle.None; \n appbarWindow.ResizeMode = ResizeMode.NoResize;\n appbarWindow.Topmost = true;\n\n ABSetPos(info.Edge, appbarWindow); \n }\n\n private delegate void ResizeDelegate(Window appbarWindow, Rect rect);\n private static void DoResize(Window appbarWindow, Rect rect)\n {\n appbarWindow.Width = rect.Width;\n appbarWindow.Height = rect.Height;\n appbarWindow.Top = rect.Top;\n appbarWindow.Left = rect.Left;\n }\n\n\n\n private static void ABSetPos(ABEdge edge, Window appbarWindow)\n {\n APPBARDATA barData = new APPBARDATA();\n barData.cbSize = Marshal.SizeOf(barData);\n barData.hWnd = new WindowInteropHelper(appbarWindow).Handle;\n barData.uEdge = (int)edge;\n\n if (barData.uEdge == (int)ABEdge.Left || barData.uEdge == (int)ABEdge.Right)\n {\n barData.rc.top = 0;\n barData.rc.bottom = (int)SystemParameters.PrimaryScreenHeight;\n if (barData.uEdge == (int)ABEdge.Left)\n {\n barData.rc.left = 0;\n barData.rc.right = (int)Math.Round(appbarWindow.ActualWidth);\n }\n else\n {\n barData.rc.right = (int)SystemParameters.PrimaryScreenWidth;\n barData.rc.left = barData.rc.right - (int)Math.Round(appbarWindow.ActualWidth);\n }\n }\n else\n {\n barData.rc.left = 0;\n barData.rc.right = (int)SystemParameters.PrimaryScreenWidth;\n if (barData.uEdge == (int)ABEdge.Top)\n {\n barData.rc.top = 0;\n barData.rc.bottom = (int)Math.Round(appbarWindow.ActualHeight);\n }\n else\n {\n barData.rc.bottom = (int)SystemParameters.PrimaryScreenHeight;\n barData.rc.top = barData.rc.bottom - (int)Math.Round(appbarWindow.ActualHeight);\n }\n }\n\n SHAppBarMessage((int)ABMsg.ABM_QUERYPOS, ref barData);\n SHAppBarMessage((int)ABMsg.ABM_SETPOS, ref barData);\n\n Rect rect = new Rect((double)barData.rc.left, (double)barData.rc.top, \n (double)(barData.rc.right - barData.rc.left), (double)(barData.rc.bottom - barData.rc.top));\n //This is done async, because WPF will send a resize after a new appbar is added. \n //if we size right away, WPFs resize comes last and overrides us.\n appbarWindow.Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, \n new ResizeDelegate(DoResize), appbarWindow, rect);\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 624235, "author": "Shuft", "author_id": 1587, "author_profile": "https://Stackoverflow.com/users/1587", "pm_score": 2, "selected": false, "text": "<p>Very happy to have found this question. Above class is really useful, but doesnt quite cover all the bases of AppBar implementation. </p>\n\n<p>To fully implement all the behaviour of an AppBar (cope with fullscreen apps etc) you're going to want to read this MSDN article too.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/bb776821.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/bb776821.aspx</a></p>\n" }, { "answer_id": 779175, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Sorry, the last code I posted didn't work when the Taskbar is resized. The following code change seems to work better:</p>\n\n<blockquote>\n<pre><code> SHAppBarMessage((int)ABMsg.ABM_QUERYPOS, ref barData);\n\n if (barData.uEdge == (int)ABEdge.Top)\n barData.rc.bottom = barData.rc.top + (int)Math.Round(appbarWindow.ActualHeight);\n else if (barData.uEdge == (int)ABEdge.Bottom)\n barData.rc.top = barData.rc.bottom - (int)Math.Round(appbarWindow.ActualHeight);\n\n SHAppBarMessage((int)ABMsg.ABM_SETPOS, ref barData);\n</code></pre>\n</blockquote>\n" }, { "answer_id": 1117766, "author": "logicnp", "author_id": 51919, "author_profile": "https://Stackoverflow.com/users/51919", "pm_score": 1, "selected": false, "text": "<p>As a commercial alternative, see the ready-to-use <a href=\"http://www.ssware.com/shlobj/shlobj.htm\" rel=\"nofollow noreferrer\">ShellAppBar</a> component for WPF which supports all cases and secnarios such as taskbar docked to left,right,top,bottom edge, support for multiple monitors, drag-docking, autohide , etc etc. It may save you time and money over trying to handle all these cases yourself.</p>\n\n<p><strong>DISCLAIMER</strong>: I work for LogicNP Software, the developer of ShellAppBar.</p>\n" }, { "answer_id": 5610186, "author": "Dmitry Andreev", "author_id": 700625, "author_profile": "https://Stackoverflow.com/users/700625", "pm_score": 2, "selected": false, "text": "<p>Sorry for my English... Here is the Philip Rieck's solution with some corrects. It correctly works with Taskbar position and size changes.</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Runtime.InteropServices;\nusing System.Windows;\nusing System.Windows.Interop;\nusing System.Windows.Threading;\n\nnamespace wpf_appbar\n{\n public enum ABEdge : int\n {\n Left,\n Top,\n Right,\n Bottom,\n None\n }\n\n internal static class AppBarFunctions\n {\n [StructLayout(LayoutKind.Sequential)]\n private struct RECT\n {\n public int Left;\n public int Top;\n public int Right;\n public int Bottom;\n public RECT(Rect r)\n {\n Left = (int)r.Left;\n Right = (int)r.Right;\n Top = (int)r.Top;\n Bottom = (int)r.Bottom;\n }\n public static bool operator ==(RECT r1, RECT r2)\n {\n return r1.Bottom == r2.Bottom &amp;&amp; r1.Left == r2.Left &amp;&amp; r1.Right == r2.Right &amp;&amp; r1.Top == r2.Top;\n }\n public static bool operator !=(RECT r1, RECT r2)\n {\n return !(r1 == r2);\n }\n public override bool Equals(object obj)\n {\n return base.Equals(obj);\n }\n public override int GetHashCode()\n {\n return base.GetHashCode();\n }\n }\n\n [StructLayout(LayoutKind.Sequential)]\n private struct APPBARDATA\n {\n public int cbSize;\n public IntPtr hWnd;\n public int uCallbackMessage;\n public int uEdge;\n public RECT rc;\n public IntPtr lParam;\n }\n\n private enum ABMsg : int\n {\n ABM_NEW = 0,\n ABM_REMOVE,\n ABM_QUERYPOS,\n ABM_SETPOS,\n ABM_GETSTATE,\n ABM_GETTASKBARPOS,\n ABM_ACTIVATE,\n ABM_GETAUTOHIDEBAR,\n ABM_SETAUTOHIDEBAR,\n ABM_WINDOWPOSCHANGED,\n ABM_SETSTATE\n }\n private enum ABNotify : int\n {\n ABN_STATECHANGE = 0,\n ABN_POSCHANGED,\n ABN_FULLSCREENAPP,\n ABN_WINDOWARRANGE\n }\n\n private enum TaskBarPosition : int\n {\n Left,\n Top,\n Right,\n Bottom\n }\n\n [StructLayout(LayoutKind.Sequential)]\n class TaskBar\n {\n public TaskBarPosition Position;\n public TaskBarPosition PreviousPosition;\n public RECT Rectangle;\n public RECT PreviousRectangle;\n public int Width;\n public int PreviousWidth;\n public int Height;\n public int PreviousHeight;\n public TaskBar()\n {\n Refresh();\n }\n public void Refresh()\n {\n APPBARDATA msgData = new APPBARDATA();\n msgData.cbSize = Marshal.SizeOf(msgData);\n SHAppBarMessage((int)ABMsg.ABM_GETTASKBARPOS, ref msgData);\n PreviousPosition = Position;\n PreviousRectangle = Rectangle;\n PreviousHeight = Height;\n PreviousWidth = Width;\n Rectangle = msgData.rc;\n Width = Rectangle.Right - Rectangle.Left;\n Height = Rectangle.Bottom - Rectangle.Top;\n int h = (int)SystemParameters.PrimaryScreenHeight;\n int w = (int)SystemParameters.PrimaryScreenWidth;\n if (Rectangle.Bottom == h &amp;&amp; Rectangle.Top != 0) Position = TaskBarPosition.Bottom;\n else if (Rectangle.Top == 0 &amp;&amp; Rectangle.Bottom != h) Position = TaskBarPosition.Top;\n else if (Rectangle.Right == w &amp;&amp; Rectangle.Left != 0) Position = TaskBarPosition.Right;\n else if (Rectangle.Left == 0 &amp;&amp; Rectangle.Right != w) Position = TaskBarPosition.Left;\n }\n }\n\n [DllImport(\"SHELL32\", CallingConvention = CallingConvention.StdCall)]\n private static extern uint SHAppBarMessage(int dwMessage, ref APPBARDATA pData);\n\n [DllImport(\"User32.dll\", CharSet = CharSet.Auto)]\n private static extern int RegisterWindowMessage(string msg);\n\n private class RegisterInfo\n {\n public int CallbackId { get; set; }\n public bool IsRegistered { get; set; }\n public Window Window { get; set; }\n public ABEdge Edge { get; set; }\n public ABEdge PreviousEdge { get; set; }\n public WindowStyle OriginalStyle { get; set; }\n public Point OriginalPosition { get; set; }\n public Size OriginalSize { get; set; }\n public ResizeMode OriginalResizeMode { get; set; }\n\n\n public IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam,\n IntPtr lParam, ref bool handled)\n {\n if (msg == CallbackId)\n {\n if (wParam.ToInt32() == (int)ABNotify.ABN_POSCHANGED)\n {\n PreviousEdge = Edge;\n ABSetPos(Edge, PreviousEdge, Window);\n handled = true;\n }\n }\n return IntPtr.Zero;\n }\n\n }\n private static Dictionary&lt;Window, RegisterInfo&gt; s_RegisteredWindowInfo\n = new Dictionary&lt;Window, RegisterInfo&gt;();\n private static RegisterInfo GetRegisterInfo(Window appbarWindow)\n {\n RegisterInfo reg;\n if (s_RegisteredWindowInfo.ContainsKey(appbarWindow))\n {\n reg = s_RegisteredWindowInfo[appbarWindow];\n }\n else\n {\n reg = new RegisterInfo()\n {\n CallbackId = 0,\n Window = appbarWindow,\n IsRegistered = false,\n Edge = ABEdge.None,\n PreviousEdge = ABEdge.None,\n OriginalStyle = appbarWindow.WindowStyle,\n OriginalPosition = new Point(appbarWindow.Left, appbarWindow.Top),\n OriginalSize =\n new Size(appbarWindow.ActualWidth, appbarWindow.ActualHeight),\n OriginalResizeMode = appbarWindow.ResizeMode,\n };\n s_RegisteredWindowInfo.Add(appbarWindow, reg);\n }\n return reg;\n }\n\n private static void RestoreWindow(Window appbarWindow)\n {\n RegisterInfo info = GetRegisterInfo(appbarWindow);\n\n appbarWindow.WindowStyle = info.OriginalStyle;\n appbarWindow.ResizeMode = info.OriginalResizeMode;\n appbarWindow.Topmost = false;\n\n Rect rect = new Rect(info.OriginalPosition.X, info.OriginalPosition.Y,\n info.OriginalSize.Width, info.OriginalSize.Height);\n appbarWindow.Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle,\n new ResizeDelegate(DoResize), appbarWindow, rect);\n\n }\n\n\n public static void SetAppBar(Window appbarWindow, ABEdge edge)\n {\n RegisterInfo info = GetRegisterInfo(appbarWindow);\n info.Edge = edge;\n\n APPBARDATA abd = new APPBARDATA();\n abd.cbSize = Marshal.SizeOf(abd);\n abd.hWnd = new WindowInteropHelper(appbarWindow).Handle;\n\n if (edge == ABEdge.None)\n {\n if (info.IsRegistered)\n {\n SHAppBarMessage((int)ABMsg.ABM_REMOVE, ref abd);\n info.IsRegistered = false;\n }\n RestoreWindow(appbarWindow);\n info.PreviousEdge = info.Edge;\n return;\n }\n\n if (!info.IsRegistered)\n {\n info.IsRegistered = true;\n info.CallbackId = RegisterWindowMessage(\"AppBarMessage\");\n abd.uCallbackMessage = info.CallbackId;\n\n uint ret = SHAppBarMessage((int)ABMsg.ABM_NEW, ref abd);\n\n HwndSource source = HwndSource.FromHwnd(abd.hWnd);\n source.AddHook(new HwndSourceHook(info.WndProc));\n }\n\n appbarWindow.WindowStyle = WindowStyle.None;\n appbarWindow.ResizeMode = ResizeMode.NoResize;\n appbarWindow.Topmost = true;\n\n ABSetPos(info.Edge, info.PreviousEdge, appbarWindow);\n }\n\n private delegate void ResizeDelegate(Window appbarWindow, Rect rect);\n private static void DoResize(Window appbarWindow, Rect rect)\n {\n appbarWindow.Width = rect.Width;\n appbarWindow.Height = rect.Height;\n appbarWindow.Top = rect.Top;\n appbarWindow.Left = rect.Left;\n }\n\n static TaskBar tb = new TaskBar();\n\n private static void ABSetPos(ABEdge edge, ABEdge prevEdge, Window appbarWindow)\n {\n APPBARDATA barData = new APPBARDATA();\n barData.cbSize = Marshal.SizeOf(barData);\n barData.hWnd = new WindowInteropHelper(appbarWindow).Handle;\n barData.uEdge = (int)edge;\n RECT wa = new RECT(SystemParameters.WorkArea);\n tb.Refresh();\n switch (edge)\n {\n case ABEdge.Top:\n barData.rc.Left = wa.Left - (prevEdge == ABEdge.Left ? (int)Math.Round(appbarWindow.ActualWidth) : 0);\n barData.rc.Right = wa.Right + (prevEdge == ABEdge.Right ? (int)Math.Round(appbarWindow.ActualWidth) : 0);\n barData.rc.Top = wa.Top - (prevEdge == ABEdge.Top ? (int)Math.Round(appbarWindow.ActualHeight) : 0) - ((tb.Position != TaskBarPosition.Top &amp;&amp; tb.PreviousPosition == TaskBarPosition.Top) ? tb.Height : 0) + ((tb.Position == TaskBarPosition.Top &amp;&amp; tb.PreviousPosition != TaskBarPosition.Top) ? tb.Height : 0);\n barData.rc.Bottom = barData.rc.Top + (int)Math.Round(appbarWindow.ActualHeight);\n break;\n case ABEdge.Bottom:\n barData.rc.Left = wa.Left - (prevEdge == ABEdge.Left ? (int)Math.Round(appbarWindow.ActualWidth) : 0);\n barData.rc.Right = wa.Right + (prevEdge == ABEdge.Right ? (int)Math.Round(appbarWindow.ActualWidth) : 0);\n barData.rc.Bottom = wa.Bottom + (prevEdge == ABEdge.Bottom ? (int)Math.Round(appbarWindow.ActualHeight) : 0) - 1 + ((tb.Position != TaskBarPosition.Bottom &amp;&amp; tb.PreviousPosition == TaskBarPosition.Bottom) ? tb.Height : 0) - ((tb.Position == TaskBarPosition.Bottom &amp;&amp; tb.PreviousPosition != TaskBarPosition.Bottom) ? tb.Height : 0);\n barData.rc.Top = barData.rc.Bottom - (int)Math.Round(appbarWindow.ActualHeight);\n break;\n }\n\n SHAppBarMessage((int)ABMsg.ABM_QUERYPOS, ref barData);\n switch (barData.uEdge)\n {\n case (int)ABEdge.Bottom:\n if (tb.Position == TaskBarPosition.Bottom &amp;&amp; tb.PreviousPosition == tb.Position)\n {\n barData.rc.Top += (tb.PreviousHeight - tb.Height);\n barData.rc.Bottom = barData.rc.Top + (int)appbarWindow.ActualHeight;\n }\n break;\n case (int)ABEdge.Top:\n if (tb.Position == TaskBarPosition.Top &amp;&amp; tb.PreviousPosition == tb.Position)\n {\n if (tb.PreviousHeight - tb.Height &gt; 0) barData.rc.Top -= (tb.PreviousHeight - tb.Height);\n barData.rc.Bottom = barData.rc.Top + (int)appbarWindow.ActualHeight;\n }\n break;\n }\n SHAppBarMessage((int)ABMsg.ABM_SETPOS, ref barData);\n\n Rect rect = new Rect((double)barData.rc.Left, (double)barData.rc.Top, (double)(barData.rc.Right - barData.rc.Left), (double)(barData.rc.Bottom - barData.rc.Top));\n appbarWindow.Dispatcher.BeginInvoke(new ResizeDelegate(DoResize), DispatcherPriority.ApplicationIdle, appbarWindow, rect);\n }\n }\n}\n</code></pre>\n\n<p>The same code you can write for the Left and Right edges.\nGood job, Philip Rieck, thank you!</p>\n" }, { "answer_id": 18896608, "author": "Miky Jadro", "author_id": 2795750, "author_profile": "https://Stackoverflow.com/users/2795750", "pm_score": 2, "selected": false, "text": "<p>I modified code from Philip Rieck (btw. Thanks a lot) to work in multiple display settings. Here's my solution.</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Runtime.InteropServices;\nusing System.Windows;\nusing System.Windows.Interop;\nusing System.Windows.Threading;\n\nnamespace AppBarApplication\n{\n public enum ABEdge : int\n {\n Left = 0,\n Top,\n Right,\n Bottom,\n None\n }\n\n internal static class AppBarFunctions\n {\n [StructLayout(LayoutKind.Sequential)]\n private struct RECT\n {\n public int left;\n public int top;\n public int right;\n public int bottom;\n }\n\n [StructLayout(LayoutKind.Sequential)]\n private struct APPBARDATA\n {\n public int cbSize;\n public IntPtr hWnd;\n public int uCallbackMessage;\n public int uEdge;\n public RECT rc;\n public IntPtr lParam;\n }\n\n [StructLayout(LayoutKind.Sequential)]\n private struct MONITORINFO\n {\n public int cbSize;\n public RECT rcMonitor;\n public RECT rcWork;\n public int dwFlags;\n }\n\n private enum ABMsg : int\n {\n ABM_NEW = 0,\n ABM_REMOVE,\n ABM_QUERYPOS,\n ABM_SETPOS,\n ABM_GETSTATE,\n ABM_GETTASKBARPOS,\n ABM_ACTIVATE,\n ABM_GETAUTOHIDEBAR,\n ABM_SETAUTOHIDEBAR,\n ABM_WINDOWPOSCHANGED,\n ABM_SETSTATE\n }\n private enum ABNotify : int\n {\n ABN_STATECHANGE = 0,\n ABN_POSCHANGED,\n ABN_FULLSCREENAPP,\n ABN_WINDOWARRANGE\n }\n\n [DllImport(\"SHELL32\", CallingConvention = CallingConvention.StdCall)]\n private static extern uint SHAppBarMessage(int dwMessage, ref APPBARDATA pData);\n\n [DllImport(\"User32.dll\", CharSet = CharSet.Auto)]\n private static extern int RegisterWindowMessage(string msg);\n\n [DllImport(\"User32.dll\", CharSet = CharSet.Auto)]\n private static extern IntPtr MonitorFromWindow(IntPtr hwnd, uint dwFlags);\n\n [DllImport(\"User32.dll\", CharSet = CharSet.Auto)]\n private static extern bool GetMonitorInfo(IntPtr hMonitor, ref MONITORINFO mi);\n\n\n private const int MONITOR_DEFAULTTONEAREST = 0x2;\n private const int MONITORINFOF_PRIMARY = 0x1;\n\n private class RegisterInfo\n {\n public int CallbackId { get; set; }\n public bool IsRegistered { get; set; }\n public Window Window { get; set; }\n public ABEdge Edge { get; set; }\n public WindowStyle OriginalStyle { get; set; }\n public Point OriginalPosition { get; set; }\n public Size OriginalSize { get; set; }\n public ResizeMode OriginalResizeMode { get; set; }\n\n\n public IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam,\n IntPtr lParam, ref bool handled)\n {\n if (msg == CallbackId)\n {\n if (wParam.ToInt32() == (int)ABNotify.ABN_POSCHANGED)\n {\n ABSetPos(Edge, Window);\n handled = true;\n }\n }\n return IntPtr.Zero;\n }\n\n }\n private static Dictionary&lt;Window, RegisterInfo&gt; s_RegisteredWindowInfo\n = new Dictionary&lt;Window, RegisterInfo&gt;();\n private static RegisterInfo GetRegisterInfo(Window appbarWindow)\n {\n RegisterInfo reg;\n if (s_RegisteredWindowInfo.ContainsKey(appbarWindow))\n {\n reg = s_RegisteredWindowInfo[appbarWindow];\n }\n else\n {\n reg = new RegisterInfo()\n {\n CallbackId = 0,\n Window = appbarWindow,\n IsRegistered = false,\n Edge = ABEdge.Top,\n OriginalStyle = appbarWindow.WindowStyle,\n OriginalPosition = new Point(appbarWindow.Left, appbarWindow.Top),\n OriginalSize =\n new Size(appbarWindow.ActualWidth, appbarWindow.ActualHeight),\n OriginalResizeMode = appbarWindow.ResizeMode,\n };\n s_RegisteredWindowInfo.Add(appbarWindow, reg);\n }\n return reg;\n }\n\n private static void RestoreWindow(Window appbarWindow)\n {\n RegisterInfo info = GetRegisterInfo(appbarWindow);\n\n appbarWindow.WindowStyle = info.OriginalStyle;\n appbarWindow.ResizeMode = info.OriginalResizeMode;\n appbarWindow.Topmost = false;\n\n Rect rect = new Rect(info.OriginalPosition.X, info.OriginalPosition.Y,\n info.OriginalSize.Width, info.OriginalSize.Height);\n appbarWindow.Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle,\n new ResizeDelegate(DoResize), appbarWindow, rect);\n\n }\n\n public static void SetAppBar(Window appbarWindow, ABEdge edge)\n {\n RegisterInfo info = GetRegisterInfo(appbarWindow);\n\n info.Edge = edge;\n\n APPBARDATA abd = new APPBARDATA();\n abd.cbSize = Marshal.SizeOf(abd);\n abd.hWnd = new WindowInteropHelper(appbarWindow).Handle;\n\n if (edge == ABEdge.None)\n {\n if (info.IsRegistered)\n {\n SHAppBarMessage((int)ABMsg.ABM_REMOVE, ref abd);\n info.IsRegistered = false;\n }\n RestoreWindow(appbarWindow);\n return;\n }\n\n if (!info.IsRegistered)\n {\n info.IsRegistered = true;\n info.CallbackId = RegisterWindowMessage(\"AppBarMessage\");\n abd.uCallbackMessage = info.CallbackId;\n\n uint ret = SHAppBarMessage((int)ABMsg.ABM_NEW, ref abd);\n\n HwndSource source = HwndSource.FromHwnd(abd.hWnd);\n source.AddHook(new HwndSourceHook(info.WndProc));\n }\n\n appbarWindow.WindowStyle = WindowStyle.None;\n appbarWindow.ResizeMode = ResizeMode.NoResize;\n appbarWindow.Topmost = true;\n\n ABSetPos(info.Edge, appbarWindow);\n }\n\n private delegate void ResizeDelegate(Window appbarWindow, Rect rect);\n private static void DoResize(Window appbarWindow, Rect rect)\n {\n appbarWindow.Width = rect.Width;\n appbarWindow.Height = rect.Height;\n appbarWindow.Top = rect.Top;\n appbarWindow.Left = rect.Left;\n }\n\n private static void GetActualScreenData(ABEdge edge, Window appbarWindow, ref int leftOffset, ref int topOffset, ref int actualScreenWidth, ref int actualScreenHeight)\n {\n IntPtr handle = new WindowInteropHelper(appbarWindow).Handle;\n IntPtr monitorHandle = MonitorFromWindow(handle, MONITOR_DEFAULTTONEAREST);\n\n MONITORINFO mi = new MONITORINFO();\n mi.cbSize = Marshal.SizeOf(mi);\n\n if (GetMonitorInfo(monitorHandle, ref mi))\n {\n if (mi.dwFlags == MONITORINFOF_PRIMARY)\n {\n return;\n }\n leftOffset = mi.rcWork.left;\n topOffset = mi.rcWork.top;\n actualScreenWidth = mi.rcWork.right - leftOffset;\n actualScreenHeight = mi.rcWork.bottom - mi.rcWork.top;\n }\n }\n\n private static void ABSetPos(ABEdge edge, Window appbarWindow)\n {\n APPBARDATA barData = new APPBARDATA();\n barData.cbSize = Marshal.SizeOf(barData);\n barData.hWnd = new WindowInteropHelper(appbarWindow).Handle;\n barData.uEdge = (int)edge;\n\n int leftOffset = 0;\n int topOffset = 0;\n int actualScreenWidth = (int)SystemParameters.PrimaryScreenWidth;\n int actualScreenHeight = (int)SystemParameters.PrimaryScreenHeight;\n\n GetActualScreenData(edge, appbarWindow, ref leftOffset, ref topOffset, ref actualScreenWidth, ref actualScreenHeight);\n\n if (barData.uEdge == (int)ABEdge.Left || barData.uEdge == (int)ABEdge.Right)\n {\n barData.rc.top = topOffset;\n barData.rc.bottom = actualScreenHeight;\n if (barData.uEdge == (int)ABEdge.Left)\n {\n barData.rc.left = leftOffset;\n barData.rc.right = (int)Math.Round(appbarWindow.ActualWidth) + leftOffset;\n }\n else\n {\n barData.rc.right = actualScreenWidth + leftOffset;\n barData.rc.left = barData.rc.right - (int)Math.Round(appbarWindow.ActualWidth);\n }\n }\n else\n {\n barData.rc.left = leftOffset;\n barData.rc.right = actualScreenWidth + leftOffset;\n if (barData.uEdge == (int)ABEdge.Top)\n {\n barData.rc.top = topOffset;\n barData.rc.bottom = (int)Math.Round(appbarWindow.ActualHeight) + topOffset;\n }\n else\n {\n barData.rc.bottom = actualScreenHeight + topOffset;\n barData.rc.top = barData.rc.bottom - (int)Math.Round(appbarWindow.ActualHeight);\n }\n }\n\n SHAppBarMessage((int)ABMsg.ABM_QUERYPOS, ref barData);\n SHAppBarMessage((int)ABMsg.ABM_SETPOS, ref barData);\n\n Rect rect = new Rect((double)barData.rc.left, (double)barData.rc.top,\n (double)(barData.rc.right - barData.rc.left), (double)(barData.rc.bottom - barData.rc.top));\n //This is done async, because WPF will send a resize after a new appbar is added. \n //if we size right away, WPFs resize comes last and overrides us.\n appbarWindow.Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle,\n new ResizeDelegate(DoResize), appbarWindow, rect);\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 33272341, "author": "Hugh", "author_id": 5347352, "author_profile": "https://Stackoverflow.com/users/5347352", "pm_score": 1, "selected": false, "text": "<p>I've spent some weeks exploring this challenge and finally created a very solid NuGet package delivering this functionality in very friendly way. Simply create a new WPF app then change the main window's class from Window to DockWindow (in the XAML) and that's it!</p>\n\n<p>Get the package <a href=\"https://www.nuget.org/packages/Canyonix.UI.Windows/1.0.1\" rel=\"nofollow\">here</a> and see the Git repo for a demonstration app.</p>\n" }, { "answer_id": 43024177, "author": "Mitch", "author_id": 138200, "author_profile": "https://Stackoverflow.com/users/138200", "pm_score": 3, "selected": false, "text": "<p>There is an excellent MSDN article from 1996 which is entertainingly up to date: <a href=\"http://web.archive.org/web/20170704171718/https://www.microsoft.com/msj/archive/S274.aspx\" rel=\"nofollow noreferrer\">Extend the Windows 95 Shell with Application Desktop Toolbars</a>. Following its guidance produces an WPF based appbar which handles a number of scenarios that the other answers on this page do not:</p>\n\n<ul>\n<li>Allow dock to any side of the screen</li>\n<li>Allow dock to a particular monitor</li>\n<li>Allow resizing of the appbar (if desired)</li>\n<li>Handle screen layout changes and monitor disconnections</li>\n<li>Handle <kbd>Win</kbd> + <kbd>Shift</kbd> + <kbd>Left</kbd> and attempts to minimize or move the window</li>\n<li>Handle co-operation with other appbars (OneNote et al.)</li>\n<li>Handle per-monitor DPI scaling</li>\n</ul>\n\n<p>I have both a <a href=\"https://github.com/mgaffigan/WpfAppBar\" rel=\"nofollow noreferrer\">demo app and the implementation of <code>AppBarWindow</code> on GitHub</a>.</p>\n\n<p>Example use:</p>\n\n<pre><code>&lt;apb:AppBarWindow x:Class=\"WpfAppBarDemo.MainWindow\" xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:apb=\"clr-namespace:WpfAppBar;assembly=WpfAppBar\"\n DataContext=\"{Binding RelativeSource={RelativeSource Self}}\" Title=\"MainWindow\" \n DockedWidthOrHeight=\"200\" MinHeight=\"100\" MinWidth=\"100\"&gt;\n &lt;Grid&gt;\n &lt;Button x:Name=\"btClose\" Content=\"Close\" HorizontalAlignment=\"Left\" VerticalAlignment=\"Top\" Width=\"75\" Height=\"23\" Margin=\"10,10,0,0\" Click=\"btClose_Click\"/&gt;\n &lt;ComboBox x:Name=\"cbMonitor\" SelectedItem=\"{Binding Path=Monitor, Mode=TwoWay}\" HorizontalAlignment=\"Left\" VerticalAlignment=\"Top\" Width=\"120\" Margin=\"10,38,0,0\"/&gt;\n &lt;ComboBox x:Name=\"cbEdge\" SelectedItem=\"{Binding Path=DockMode, Mode=TwoWay}\" HorizontalAlignment=\"Left\" Margin=\"10,65,0,0\" VerticalAlignment=\"Top\" Width=\"120\"/&gt;\n\n &lt;Thumb Width=\"5\" HorizontalAlignment=\"Right\" Background=\"Gray\" x:Name=\"rzThumb\" Cursor=\"SizeWE\" DragCompleted=\"rzThumb_DragCompleted\" /&gt;\n &lt;/Grid&gt;\n&lt;/apb:AppBarWindow&gt;\n</code></pre>\n\n<p>Codebehind:</p>\n\n<pre><code>public partial class MainWindow\n{\n public MainWindow()\n {\n InitializeComponent();\n\n this.cbEdge.ItemsSource = new[]\n {\n AppBarDockMode.Left,\n AppBarDockMode.Right,\n AppBarDockMode.Top,\n AppBarDockMode.Bottom\n };\n this.cbMonitor.ItemsSource = MonitorInfo.GetAllMonitors();\n }\n\n private void btClose_Click(object sender, RoutedEventArgs e)\n {\n Close();\n }\n\n private void rzThumb_DragCompleted(object sender, DragCompletedEventArgs e)\n {\n this.DockedWidthOrHeight += (int)(e.HorizontalChange / VisualTreeHelper.GetDpi(this).PixelsPerDip);\n }\n}\n</code></pre>\n\n<p>Changing docked position:</p>\n\n<blockquote>\n <p><a href=\"https://i.stack.imgur.com/f13P8.gif\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/f13P8.gif\" alt=\"AppBar docked to edges\"></a></p>\n</blockquote>\n\n<p>Resizing with thumb:</p>\n\n<blockquote>\n <p><a href=\"https://i.stack.imgur.com/ifgn8.gif\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ifgn8.gif\" alt=\"Resize\"></a></p>\n</blockquote>\n\n<p>Cooperation with other appbars:</p>\n\n<blockquote>\n <p><a href=\"https://i.stack.imgur.com/PiydR.gif\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/PiydR.gif\" alt=\"Coordination\"></a></p>\n</blockquote>\n\n<p>Clone <a href=\"https://github.com/mgaffigan/WpfAppBar\" rel=\"nofollow noreferrer\">from GitHub</a> if you want to use it. The library itself is only three files, and can easily be dropped in a project.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/75785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7301/" ]
Is there any complete guidance on doing AppBar docking (such as locking to the screen edge) in WPF? I understand there are InterOp calls that need to be made, but I'm looking for either a proof of concept based on a simple WPF form, or a componentized version that can be consumed. Related resources: * <http://www.codeproject.com/KB/dotnet/AppBar.aspx> * <http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/05c73c9c-e85d-4ecd-b9b6-4c714a65e72b/>
**Please Note:** This question gathered a good amount of feedback, and some people below have made great points or fixes. Therefore, while I'll keep the code here (and possibly update it), I've also **created a [WpfAppBar project on github](https://github.com/PhilipRieck/WpfAppBar)**. Feel free to send pull requests. That same project also builds to a [WpfAppBar nuget package](https://www.nuget.org/packages/WpfAppBar/) --- I took the code from the first link provided in the question ( <http://www.codeproject.com/KB/dotnet/AppBar.aspx> ) and modified it to do two things: 1. Work with WPF 2. Be "standalone" - if you put this single file in your project, you can call AppBarFunctions.SetAppBar(...) without any further modification to the window. This approach doesn't create a base class. To use, just call this code from anywhere within a normal wpf window (say a button click or the initialize). Note that you can not call this until AFTER the window is initialized, if the HWND hasn't been created yet (like in the constructor), an error will occur. Make the window an appbar: ``` AppBarFunctions.SetAppBar( this, ABEdge.Right ); ``` Restore the window to a normal window: ``` AppBarFunctions.SetAppBar( this, ABEdge.None ); ``` Here's the full code to the file - **note** you'll want to change the namespace on line 7 to something apropriate. ``` using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Windows; using System.Windows.Interop; using System.Windows.Threading; namespace AppBarApplication { public enum ABEdge : int { Left = 0, Top, Right, Bottom, None } internal static class AppBarFunctions { [StructLayout(LayoutKind.Sequential)] private struct RECT { public int left; public int top; public int right; public int bottom; } [StructLayout(LayoutKind.Sequential)] private struct APPBARDATA { public int cbSize; public IntPtr hWnd; public int uCallbackMessage; public int uEdge; public RECT rc; public IntPtr lParam; } private enum ABMsg : int { ABM_NEW = 0, ABM_REMOVE, ABM_QUERYPOS, ABM_SETPOS, ABM_GETSTATE, ABM_GETTASKBARPOS, ABM_ACTIVATE, ABM_GETAUTOHIDEBAR, ABM_SETAUTOHIDEBAR, ABM_WINDOWPOSCHANGED, ABM_SETSTATE } private enum ABNotify : int { ABN_STATECHANGE = 0, ABN_POSCHANGED, ABN_FULLSCREENAPP, ABN_WINDOWARRANGE } [DllImport("SHELL32", CallingConvention = CallingConvention.StdCall)] private static extern uint SHAppBarMessage(int dwMessage, ref APPBARDATA pData); [DllImport("User32.dll", CharSet = CharSet.Auto)] private static extern int RegisterWindowMessage(string msg); private class RegisterInfo { public int CallbackId { get; set; } public bool IsRegistered { get; set; } public Window Window { get; set; } public ABEdge Edge { get; set; } public WindowStyle OriginalStyle { get; set; } public Point OriginalPosition { get; set; } public Size OriginalSize { get; set; } public ResizeMode OriginalResizeMode { get; set; } public IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) { if (msg == CallbackId) { if (wParam.ToInt32() == (int)ABNotify.ABN_POSCHANGED) { ABSetPos(Edge, Window); handled = true; } } return IntPtr.Zero; } } private static Dictionary<Window, RegisterInfo> s_RegisteredWindowInfo = new Dictionary<Window, RegisterInfo>(); private static RegisterInfo GetRegisterInfo(Window appbarWindow) { RegisterInfo reg; if( s_RegisteredWindowInfo.ContainsKey(appbarWindow)) { reg = s_RegisteredWindowInfo[appbarWindow]; } else { reg = new RegisterInfo() { CallbackId = 0, Window = appbarWindow, IsRegistered = false, Edge = ABEdge.Top, OriginalStyle = appbarWindow.WindowStyle, OriginalPosition =new Point( appbarWindow.Left, appbarWindow.Top), OriginalSize = new Size( appbarWindow.ActualWidth, appbarWindow.ActualHeight), OriginalResizeMode = appbarWindow.ResizeMode, }; s_RegisteredWindowInfo.Add(appbarWindow, reg); } return reg; } private static void RestoreWindow(Window appbarWindow) { RegisterInfo info = GetRegisterInfo(appbarWindow); appbarWindow.WindowStyle = info.OriginalStyle; appbarWindow.ResizeMode = info.OriginalResizeMode; appbarWindow.Topmost = false; Rect rect = new Rect(info.OriginalPosition.X, info.OriginalPosition.Y, info.OriginalSize.Width, info.OriginalSize.Height); appbarWindow.Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, new ResizeDelegate(DoResize), appbarWindow, rect); } public static void SetAppBar(Window appbarWindow, ABEdge edge) { RegisterInfo info = GetRegisterInfo(appbarWindow); info.Edge = edge; APPBARDATA abd = new APPBARDATA(); abd.cbSize = Marshal.SizeOf(abd); abd.hWnd = new WindowInteropHelper(appbarWindow).Handle; if( edge == ABEdge.None) { if( info.IsRegistered) { SHAppBarMessage((int)ABMsg.ABM_REMOVE, ref abd); info.IsRegistered = false; } RestoreWindow(appbarWindow); return; } if (!info.IsRegistered) { info.IsRegistered = true; info.CallbackId = RegisterWindowMessage("AppBarMessage"); abd.uCallbackMessage = info.CallbackId; uint ret = SHAppBarMessage((int)ABMsg.ABM_NEW, ref abd); HwndSource source = HwndSource.FromHwnd(abd.hWnd); source.AddHook(new HwndSourceHook(info.WndProc)); } appbarWindow.WindowStyle = WindowStyle.None; appbarWindow.ResizeMode = ResizeMode.NoResize; appbarWindow.Topmost = true; ABSetPos(info.Edge, appbarWindow); } private delegate void ResizeDelegate(Window appbarWindow, Rect rect); private static void DoResize(Window appbarWindow, Rect rect) { appbarWindow.Width = rect.Width; appbarWindow.Height = rect.Height; appbarWindow.Top = rect.Top; appbarWindow.Left = rect.Left; } private static void ABSetPos(ABEdge edge, Window appbarWindow) { APPBARDATA barData = new APPBARDATA(); barData.cbSize = Marshal.SizeOf(barData); barData.hWnd = new WindowInteropHelper(appbarWindow).Handle; barData.uEdge = (int)edge; if (barData.uEdge == (int)ABEdge.Left || barData.uEdge == (int)ABEdge.Right) { barData.rc.top = 0; barData.rc.bottom = (int)SystemParameters.PrimaryScreenHeight; if (barData.uEdge == (int)ABEdge.Left) { barData.rc.left = 0; barData.rc.right = (int)Math.Round(appbarWindow.ActualWidth); } else { barData.rc.right = (int)SystemParameters.PrimaryScreenWidth; barData.rc.left = barData.rc.right - (int)Math.Round(appbarWindow.ActualWidth); } } else { barData.rc.left = 0; barData.rc.right = (int)SystemParameters.PrimaryScreenWidth; if (barData.uEdge == (int)ABEdge.Top) { barData.rc.top = 0; barData.rc.bottom = (int)Math.Round(appbarWindow.ActualHeight); } else { barData.rc.bottom = (int)SystemParameters.PrimaryScreenHeight; barData.rc.top = barData.rc.bottom - (int)Math.Round(appbarWindow.ActualHeight); } } SHAppBarMessage((int)ABMsg.ABM_QUERYPOS, ref barData); SHAppBarMessage((int)ABMsg.ABM_SETPOS, ref barData); Rect rect = new Rect((double)barData.rc.left, (double)barData.rc.top, (double)(barData.rc.right - barData.rc.left), (double)(barData.rc.bottom - barData.rc.top)); //This is done async, because WPF will send a resize after a new appbar is added. //if we size right away, WPFs resize comes last and overrides us. appbarWindow.Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, new ResizeDelegate(DoResize), appbarWindow, rect); } } } ```
75,786
<p>(Eclipse 3.4, Ganymede)</p> <p>I have an existing Dynamic Web Application project in Eclipse. When I created the project, I specified 'Default configuration for Apache Tomcat v6' under the 'Configuration' drop down.</p> <p>It's a month or 2 down the line, and I would now like to change the configuration to Tomcat 'v5.5'. (This will be the version of Tomcat on the production server.)</p> <p>I have tried the following steps (without success):</p> <ul> <li>I selected <code>Targeted Runtimes</code> under the Project <code>Properties</code><br> The <code>Tomcat v5.5</code> option was disabled and The UI displayed this message:<br> <code>If the runtime you want to select is not displayed or is disabled you may need to uninstall one or more of the currently installed project facets.</code> </li> <li>I then clicked on the <code>Uninstall Facets...</code> link.<br> Under the <code>Runtimes</code> tab, only <code>Tomcat 6</code> displayed.<br> For <code>Dynamic Web Module</code>, I selected version <code>2.4</code> in place of <code>2.5</code>.<br> Under the <code>Runtimes</code> tab, <code>Tomcat 5.5</code> now displayed.<br> However, the UI now displayed this message:<br> <code>Cannot change version of project facet Dynamic Web Module to 2.4.</code><br> The <code>Finish</code> button was disabled - so I reached a dead-end.</li> </ul> <p>I CAN successfully create a NEW Project with a Tomcat v5.5 configuration. For some reason, though, it will not let me downgrade' an existing Project.</p> <p>As a work-around, I created a new Project and copied the source files from the old Project. Nonetheless, the work-around was fairly painful and somewhat clumsy.</p> <p>Can anyone explain how I can 'downgrade' the Project configuration from 'Tomcat 6' to 'Tomcat 5'? Or perhaps shed some light on why this happened?</p> <p>Thanks<br> Pete</p>
[ { "answer_id": 76205, "author": "William", "author_id": 9193, "author_profile": "https://Stackoverflow.com/users/9193", "pm_score": 7, "selected": true, "text": "<p>This is kind of hacking eclipse and you can get into trouble doing this but this should work:</p>\n\n<p>Open the navigator view and find that there is a .settings folder under your project expand it and then open the file: <code>org.eclipse.wst.common.project.facet.core.xml</code> you should see a line that says: \n<code>\n &lt;installed facet=\"jst.web\" version=\"2.5\"/&gt;\n</code>\nChange that to 2.4 and save.</p>\n\n<p>Just make sure that your project isn't using anything specific for 2.5 and you should be good.</p>\n\n<p>Also check your web.xml has the correct configuration:</p>\n\n<pre><code>&lt;web-app version=\"2.4\" \n 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 http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd\"&gt;\n</code></pre>\n" }, { "answer_id": 78299, "author": "William", "author_id": 9193, "author_profile": "https://Stackoverflow.com/users/9193", "pm_score": 0, "selected": false, "text": "<p>Sorry it seems I can't post a comment without enough Rep so...</p>\n\n<p>I think it's too difficult for eclipse to degrade safely to a lower standard because it can't really know if you've used something from the newer web standard. So if it just allows you do to that it could cause your program to fail on an older version.</p>\n\n<p>You can always be backward compatible but not forwards compatible.</p>\n" }, { "answer_id": 2356592, "author": "Venkat", "author_id": 194565, "author_profile": "https://Stackoverflow.com/users/194565", "pm_score": 3, "selected": false, "text": "<p>This may be old but I tried and found the following in eclipse Galilio. </p>\n\n<p>Open the navigator view and find that there is a .settings folder under your project expand it and then open the file: org.eclipse.wst.common.project.facet.core.Delete the content of this file and right click on the project and click on properties. Go to Project Facats in the popup window there you can click on runtime tabs and convert your project to the new facet you want.</p>\n" }, { "answer_id": 4051477, "author": "xgomez", "author_id": 59067, "author_profile": "https://Stackoverflow.com/users/59067", "pm_score": 0, "selected": false, "text": "<p>You can try to uncheck the facet, apply, change the value of the facet and check. It works for me in Eclipse Helios SR1.</p>\n\n<p>So the main difference is that I do it with 'Dynamic Web Module'.</p>\n\n<p>I hope it works for you too.</p>\n" }, { "answer_id": 4830219, "author": "Karthik", "author_id": 594073, "author_profile": "https://Stackoverflow.com/users/594073", "pm_score": 3, "selected": false, "text": "<p>if you are using Maven, then shutdown eclipse, then type <code>&gt;mvn eclipse:eclipse -Dwtpversion=2.0</code>, and restart the eclipse. </p>\n" }, { "answer_id": 5571788, "author": "sarabrab", "author_id": 695500, "author_profile": "https://Stackoverflow.com/users/695500", "pm_score": 0, "selected": false, "text": "<p>I saw the same thing, then I changed the web-app version value in the <code>web.xml</code>. Doing so could fix this for you.</p>\n" }, { "answer_id": 5956380, "author": "Dante", "author_id": 682844, "author_profile": "https://Stackoverflow.com/users/682844", "pm_score": -1, "selected": false, "text": "<p>If you are using maven you can generated the eclipse settings using the maven eclipse plugin. </p>\n\n<p>For the jst.web version the Maven eclipse pluging takes into account the dependencies of the project. If you have a servlet api dependency defined :</p>\n\n<pre><code>&lt;dependency&gt;\n &lt;groupId&gt;org.apache.tomcat&lt;/groupId&gt;\n &lt;artifactId&gt;servlet-api&lt;/artifactId&gt;\n &lt;version&gt;6.0.32&lt;/version&gt;\n&lt;/dependency&gt; \n</code></pre>\n\n<p>You jst.web parameter will be 6.0 </p>\n\n<pre><code>&lt;faceted-project&gt;\n ...\n &lt;installed facet=\"jst.web\" version=\"6.0\"/&gt;\n ...\n&lt;/faceted-project&gt;\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/75786", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13360/" ]
(Eclipse 3.4, Ganymede) I have an existing Dynamic Web Application project in Eclipse. When I created the project, I specified 'Default configuration for Apache Tomcat v6' under the 'Configuration' drop down. It's a month or 2 down the line, and I would now like to change the configuration to Tomcat 'v5.5'. (This will be the version of Tomcat on the production server.) I have tried the following steps (without success): * I selected `Targeted Runtimes` under the Project `Properties` The `Tomcat v5.5` option was disabled and The UI displayed this message: `If the runtime you want to select is not displayed or is disabled you may need to uninstall one or more of the currently installed project facets.` * I then clicked on the `Uninstall Facets...` link. Under the `Runtimes` tab, only `Tomcat 6` displayed. For `Dynamic Web Module`, I selected version `2.4` in place of `2.5`. Under the `Runtimes` tab, `Tomcat 5.5` now displayed. However, the UI now displayed this message: `Cannot change version of project facet Dynamic Web Module to 2.4.` The `Finish` button was disabled - so I reached a dead-end. I CAN successfully create a NEW Project with a Tomcat v5.5 configuration. For some reason, though, it will not let me downgrade' an existing Project. As a work-around, I created a new Project and copied the source files from the old Project. Nonetheless, the work-around was fairly painful and somewhat clumsy. Can anyone explain how I can 'downgrade' the Project configuration from 'Tomcat 6' to 'Tomcat 5'? Or perhaps shed some light on why this happened? Thanks Pete
This is kind of hacking eclipse and you can get into trouble doing this but this should work: Open the navigator view and find that there is a .settings folder under your project expand it and then open the file: `org.eclipse.wst.common.project.facet.core.xml` you should see a line that says: `<installed facet="jst.web" version="2.5"/>` Change that to 2.4 and save. Just make sure that your project isn't using anything specific for 2.5 and you should be good. Also check your web.xml has the correct configuration: ``` <web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> ```
75,809
<p>Given the case I made <strong>two independent changes</strong> in <em>one</em> file: eg. added a new method and changed another method.</p> <p>I often don't want to commit both changes as <strong>one</strong> commit, but as <strong>two</strong> independent commits.</p> <p>On a git repository I would use the <strong>Interactive Mode</strong> of <a href="http://linux.die.net/man/1/git-add" rel="noreferrer">git-add(1)</a> to split the <em>hunk</em> into smaller ones:</p> <pre><code> git add --patch </code></pre> <p>What's the easiest way to do this with Subversion? (Maybe even using an Eclipse plug-in)</p> <p><strong>Update:</strong><br/> In <a href="http://tomayko.com/writings/the-thing-about-git" rel="noreferrer">The Thing About Git</a>, Ryan calls it: <em>“The Tangled Working Copy Problem.”</em></p>
[ { "answer_id": 75881, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 3, "selected": false, "text": "<p>I used to do this:</p>\n\n<ul>\n<li>In my editor (I use vim), edit the file so that only one of the changes appear</li>\n<li>Save the file (but don't quit the editor)</li>\n<li>Commit the changed file to svn</li>\n<li>Hit \"undo\" in the editor enough times for the second set of changes reappear</li>\n<li>Save the file again</li>\n<li>Commit the second set of changes.</li>\n</ul>\n\n<p>This is a simplistic approach that assumes one set of changes is reasonably easy to undo. For more complex situations, I would give up and commit both changes without worrying about it.</p>\n\n<p>Now that I use git, this is something I hope I'll never have to do again!</p>\n" }, { "answer_id": 75901, "author": "Spike", "author_id": 13111, "author_profile": "https://Stackoverflow.com/users/13111", "pm_score": 5, "selected": false, "text": "<p>I have done this using <a href=\"http://tortoisesvn.tigris.org/\" rel=\"noreferrer\" title=\"TortoiseSVN\">TortoiseSVN</a>.</p>\n\n<p>The built in merge utility allows you to show a diff between the repository version and your working copy.</p>\n\n<p>Use the <em>create backup</em> function of the diff utility</p>\n\n<ol>\n<li>Go to commit your file as if you were going to commit all your changes.</li>\n<li>In the commit window, double click the file to show a diff.</li>\n<li>In the diff settings, click the option to <em>backup original file</em>. </li>\n<li>Right-click the changes you don't want, and use select <em>use other text block</em>.</li>\n<li>Save the diff <strong>exactly once</strong>. The backup will be overwritten each time you save. This is why you only want to save once.</li>\n<li>Commit the change.</li>\n<li>Overwrite the original with the created .bak file (which will have all your original changes).</li>\n<li>Commit your file.</li>\n</ol>\n\n<p>You should now have all your changes committed, using two separate commits.</p>\n" }, { "answer_id": 75918, "author": "Aeon", "author_id": 13289, "author_profile": "https://Stackoverflow.com/users/13289", "pm_score": 2, "selected": false, "text": "<p>I use either a local darcs repo, or just merge the changes in gradually. With merging (opendiff opens FileMerge, a merge program that comes with Xcode; replace with your favorite merge tool):</p>\n\n<pre><code>cp file file.new\nsvn revert file\nopendiff file.new file -merge file\n</code></pre>\n\n<p>merge the related changes, save the merge, quit the merge program</p>\n\n<pre><code>svn ci -m 'first hunk' file\nmv file.new file\nsvn ci -m 'second hunk' file\n</code></pre>\n\n<p>if more than one unrelated hunk in the file, rinse and repeat (but why would you wait so long before committing?!)</p>\n\n<p>Also, if you know git, you can use <a href=\"http://git.or.cz/course/svn.html\" rel=\"noreferrer\">git-svn</a> to maintain a local git repo and sync your commits to an svn master server; works great in my limited experience.</p>\n" }, { "answer_id": 75950, "author": "Chris", "author_id": 13488, "author_profile": "https://Stackoverflow.com/users/13488", "pm_score": 5, "selected": false, "text": "<p>Try using <code>svn diff &gt; out.patch</code> then copy the <code>out.patch</code> file to <code>out.patch.add</code> and <code>out.patch.modify</code> </p>\n\n<p><em>Only when you have a working patch file</em> revert the original file using <code>svn revert out.c</code>.</p>\n\n<p>Edit the patch files by hand so that they only contain the <em>hunks</em> for adding or modifying. Apply them to the original file using the <code>patch</code> command, test if the addition worked, then <code>svn commit</code> the addition.</p>\n\n<p>Wash rinse repeat for the <code>out.patch.modify</code> patch.</p>\n\n<p>If the changes are separate in the file as your initial question stated - added a new method, changed an existing method - this will work</p>\n\n<p>This is a very tedious solution - although I'm not convinced you should have any reason to separate your commits.</p>\n\n<p>You also could have checked out multiple working copies of the same source to apply your work against:</p>\n\n<blockquote>\n <p><code>svn co http://location/repository methodAdd</code></p>\n \n <p><code>svn co http://location/repository methodModify</code></p>\n</blockquote>\n\n<p>Be sure to <code>svn up</code> and test to make sure all is well.</p>\n" }, { "answer_id": 76088, "author": "jkramer", "author_id": 12523, "author_profile": "https://Stackoverflow.com/users/12523", "pm_score": 6, "selected": true, "text": "<p>With git-svn you can make a local GIT repository of the remote SVN repository, work with it using the full GIT feature set (including partial commits) and then push it all back to the SVN repository.</p>\n\n<p><a href=\"http://schacon.github.com/git/git-svn.html\" rel=\"noreferrer\">git-svn (1)</a></p>\n" }, { "answer_id": 462321, "author": "BCS", "author_id": 1343, "author_profile": "https://Stackoverflow.com/users/1343", "pm_score": 2, "selected": false, "text": "<ol>\n<li>Open all the files you want to split in editor-of-choice</li>\n<li>Using a different tool set (on Win, use Spike's suggestion (the old version)) back out the second set</li>\n<li>Commit</li>\n<li>go back to your editor-of-choice and save all the files</li>\n</ol>\n\n<p>It's a little riskier than Spike's full suggestion but can be easier to do. Also make sure you try it on something else first as some editors will refuse to save over a file that has changed out from under them unless you reload that file (losing all your changes)</p>\n" }, { "answer_id": 17538550, "author": "Casebash", "author_id": 165495, "author_profile": "https://Stackoverflow.com/users/165495", "pm_score": 6, "selected": false, "text": "<p>Tortoise SVN 1.8 <a href=\"https://tortoisesvn.net/tsvn_1.8_releasenotes.html#commitparts\" rel=\"noreferrer\">now supports</a> this with it's \"Restore after commit\" feature. This allow you to make edits to a file, with all of the edits being undone after the commit</p>\n\n<p><strong>Per the documentation:</strong></p>\n\n<blockquote>\n <p>To commit only the parts of the file that relate to one specific issue:</p>\n \n <ol>\n <li>in the commit dialog, right-click on file, choose \"restore after commit\"</li>\n <li>edit the file in e.g. TortoiseMerge: undo the changes that you don't want to commit yet</li>\n <li>save the file</li>\n <li>commit the file</li>\n </ol>\n</blockquote>\n" }, { "answer_id": 19255703, "author": "parvus", "author_id": 911550, "author_profile": "https://Stackoverflow.com/users/911550", "pm_score": 4, "selected": false, "text": "<p>This is possible using TortoiseSvn (Windows) since v1.8.</p>\n<blockquote>\n<p>4.4.1. The Commit Dialog</p>\n<p>If your working copy is up to date and there are no conflicts, you are ready to commit your changes. Select any\nfile and/or folders you want to commit, then TortoiseSVN → Commit....</p>\n<p>&lt;snip&gt;</p>\n<p>4.4.3. Commit only parts of files</p>\n<p>Sometimes you want to only commit parts of the changes you made to a file. Such a situation usually\nhappens when you're working on something but then an urgent fix needs\nto be committed, and that fix happens to be in the same file you're\nworking on.</p>\n<p>right click on the file and use Context Menu → Restore after commit.\nThis will create a copy of the file as it is. Then you can edit the\nfile, e.g. in TortoiseMerge and undo all the changes you don't want to\ncommit. After saving those changes you can commit the file.</p>\n<p>After the commit is done, the copy of the file is restored\nautomatically, and you have the file with all your modifications that\nwere not committed back.</p>\n</blockquote>\n<p>On Linux, I would give <a href=\"http://webstaff.itn.liu.se/%7Ekarlu20/div/blog/2013-05-31_SVNPartialCommit.php\" rel=\"noreferrer\">http://webstaff.itn.liu.se/~karlu20/div/blog/2013-05-31_SVNPartialCommit.php</a> a try. Haven't tried it out myself, though.</p>\n" }, { "answer_id": 35370831, "author": "Ian Dunn", "author_id": 450127, "author_profile": "https://Stackoverflow.com/users/450127", "pm_score": 0, "selected": false, "text": "<p>I think an easier option than generating diff files, reverting, etc, would be to have two copies of the repository checked out, and use a visual diff tool like DeltaWalker to copy hunks from one to the other.</p>\n\n<p>The first copy would be the one you actually work off of, and the second would just be for this purpose. Once you've made a ton of changes to the first, you can copy one section over to the second, commit it, copy another section, commit it, etc.</p>\n" }, { "answer_id": 46731868, "author": "michaeljt", "author_id": 213180, "author_profile": "https://Stackoverflow.com/users/213180", "pm_score": 0, "selected": false, "text": "<ol>\n<li>Copy all modified files concerned to back-up copies.</li>\n<li>Create a patch of the working state using <code>svn diff</code>.</li>\n<li>Revert the files using <code>svn revert</code>.</li>\n<li>Re-apply the parts of the patch which you wish to commit, either using the <code>patch</code> tool, or by manual editing, or whatever.</li>\n<li>Run <code>diff</code> afterwards to compare your working copy with your back-up to be sure you applied the patch-parts correctly.</li>\n<li>Build and test.</li>\n<li>Commit.</li>\n<li>Copy your back-up copies back to your repository check-out.</li>\n<li>Repeat at 2. (not at 1.!) until done.</li>\n</ol>\n" }, { "answer_id": 49452436, "author": "bahrep", "author_id": 761095, "author_profile": "https://Stackoverflow.com/users/761095", "pm_score": 2, "selected": false, "text": "<p>Try <a href=\"https://www.visualsvn.com/visualsvn/\" rel=\"nofollow noreferrer\">VisualSVN for Visual Studio</a>. The <a href=\"https://www.visualsvn.com/company/news/visualsvn-6.1\" rel=\"nofollow noreferrer\">latest 6.1 release</a> introduces the QuickCommit feature. You can partially commit selected changes in a file using the new <strong>Commit this Block</strong> and <strong>Commit Selection</strong> context menu commands in the Visual Studio editor.</p>\n\n<p><a href=\"https://i.stack.imgur.com/hV92h.gif\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/hV92h.gif\" alt=\"enter image description here\"></a></p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/75809", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4308/" ]
Given the case I made **two independent changes** in *one* file: eg. added a new method and changed another method. I often don't want to commit both changes as **one** commit, but as **two** independent commits. On a git repository I would use the **Interactive Mode** of [git-add(1)](http://linux.die.net/man/1/git-add) to split the *hunk* into smaller ones: ``` git add --patch ``` What's the easiest way to do this with Subversion? (Maybe even using an Eclipse plug-in) **Update:** In [The Thing About Git](http://tomayko.com/writings/the-thing-about-git), Ryan calls it: *“The Tangled Working Copy Problem.”*
With git-svn you can make a local GIT repository of the remote SVN repository, work with it using the full GIT feature set (including partial commits) and then push it all back to the SVN repository. [git-svn (1)](http://schacon.github.com/git/git-svn.html)
75,819
<p>I'm having an issue with a query that currently uses </p> <pre><code>LEFT JOIN weblog_data AS pwd ON (pwd.field_id_41 != '' AND pwd.field_id_41 LIKE CONCAT('%', ewd.field_id_32, '%')) </code></pre> <p>However I'm discovering that I need it to only use that if there is no exact match first. What's happening is that the query is double dipping due to the use of <code>LIKE</code>, so if it tests for an exact match first then it will avoid the double dipping issue. Can anyone provide me with any further guidance?</p>
[ { "answer_id": 75861, "author": "Sam", "author_id": 9406, "author_profile": "https://Stackoverflow.com/users/9406", "pm_score": 1, "selected": false, "text": "<p>you're talking about short circuit evaluation.</p>\n\n<p>Take a look at this article it might help you:\n<a href=\"http://beingmarkcohen.com/?p=62\" rel=\"nofollow noreferrer\">http://beingmarkcohen.com/?p=62</a></p>\n" }, { "answer_id": 75884, "author": "Chris Ballance", "author_id": 1551, "author_profile": "https://Stackoverflow.com/users/1551", "pm_score": 1, "selected": false, "text": "<p>using TSQL, run an exact match, check for num of rows == 0, if so, run the like, otherwise don't run the like or add the like results below the exact matches.</p>\n" }, { "answer_id": 75899, "author": "Mostlyharmless", "author_id": 12881, "author_profile": "https://Stackoverflow.com/users/12881", "pm_score": 0, "selected": false, "text": "<p>I can only think of doing it in code. Look for an exact match, if the result is empty, look for a LIKE. \nOne other option is a WHERE within this query such that WHERE ({count from exact match}=0), in which case, it wont go through the comparison with LIKE if the exact match returns more than 0 results. But its terribly inefficient... not to mention the fact that using it meaningfully in code is rather difficult.</p>\n\n<p>i'd go for a If(count from exact match = 0) then do like query, else just use the result from exact match.</p>\n" }, { "answer_id": 75973, "author": "Jonathan Rupp", "author_id": 12502, "author_profile": "https://Stackoverflow.com/users/12502", "pm_score": 3, "selected": true, "text": "<p>It sounds like you want to join the tables aliased as pwd and ewd in your snippet based first on an exact match, and if that fails, then on the like comparison you have now.</p>\n\n<p>Try this:</p>\n\n<pre><code>LEFT JOIN weblog_data AS pwd1 ON (pwd.field_id_41 != '' AND pwd.field_id_41 = ewd.field_id_32)\nLEFT JOIN weblog_data AS pwd2 ON (pwd.field_id_41 != '' AND pwd.field_id_41 LIKE CONCAT('%', ewd.field_id_32, '%'))\n</code></pre>\n\n<p>Then, in your select clause, use something like this:</p>\n\n<pre><code>select\n isnull(pwd1.field, pwd2.field)\n</code></pre>\n\n<p>however, if you are dealing with a field that can be null in pwd, that will cause problems, this should work though:</p>\n\n<pre><code>select\n case pwd1.nonnullfield is null then pwd2.field else pwd1.field end\n</code></pre>\n\n<p>You'll also have to make sure to do a group by, as the join to pwd2 will still add rows to your result set, even if you end up ignoring the data in it.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/75819", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12073/" ]
I'm having an issue with a query that currently uses ``` LEFT JOIN weblog_data AS pwd ON (pwd.field_id_41 != '' AND pwd.field_id_41 LIKE CONCAT('%', ewd.field_id_32, '%')) ``` However I'm discovering that I need it to only use that if there is no exact match first. What's happening is that the query is double dipping due to the use of `LIKE`, so if it tests for an exact match first then it will avoid the double dipping issue. Can anyone provide me with any further guidance?
It sounds like you want to join the tables aliased as pwd and ewd in your snippet based first on an exact match, and if that fails, then on the like comparison you have now. Try this: ``` LEFT JOIN weblog_data AS pwd1 ON (pwd.field_id_41 != '' AND pwd.field_id_41 = ewd.field_id_32) LEFT JOIN weblog_data AS pwd2 ON (pwd.field_id_41 != '' AND pwd.field_id_41 LIKE CONCAT('%', ewd.field_id_32, '%')) ``` Then, in your select clause, use something like this: ``` select isnull(pwd1.field, pwd2.field) ``` however, if you are dealing with a field that can be null in pwd, that will cause problems, this should work though: ``` select case pwd1.nonnullfield is null then pwd2.field else pwd1.field end ``` You'll also have to make sure to do a group by, as the join to pwd2 will still add rows to your result set, even if you end up ignoring the data in it.
75,829
<p>All the docs for SQLAlchemy give <code>INSERT</code> and <code>UPDATE</code> examples using the local table instance (e.g. <code>tablename.update()</code>... )</p> <p>Doing this seems difficult with the declarative syntax, I need to reference <code>Base.metadata.tables["tablename"]</code> to get the table reference.</p> <p>Am I supposed to do this another way? Is there a different syntax for <code>INSERT</code> and <code>UPDATE</code> recommended when using the declarative syntax? Should I just switch to the old way?</p>
[ { "answer_id": 77962, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>via the <code>__table__</code> attribute on your declarative class</p>\n" }, { "answer_id": 156968, "author": "GHZ", "author_id": 18138, "author_profile": "https://Stackoverflow.com/users/18138", "pm_score": 3, "selected": false, "text": "<p>well it works for me:</p>\n\n<pre><code>class Users(Base):\n __tablename__ = 'users'\n __table_args__ = {'autoload':True}\n\nusers = Users()\nprint users.__table__.select()\n</code></pre>\n\n<p>...SELECT users.......</p>\n" }, { "answer_id": 315406, "author": "Paul Harrington", "author_id": 40387, "author_profile": "https://Stackoverflow.com/users/40387", "pm_score": 0, "selected": false, "text": "<p>There may be some confusion between <strong>table</strong> (the object) and <strong>tablename</strong> (the name of the table, a string). Using the <strong>table</strong> class attribute works fine for me.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/75829", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
All the docs for SQLAlchemy give `INSERT` and `UPDATE` examples using the local table instance (e.g. `tablename.update()`... ) Doing this seems difficult with the declarative syntax, I need to reference `Base.metadata.tables["tablename"]` to get the table reference. Am I supposed to do this another way? Is there a different syntax for `INSERT` and `UPDATE` recommended when using the declarative syntax? Should I just switch to the old way?
well it works for me: ``` class Users(Base): __tablename__ = 'users' __table_args__ = {'autoload':True} users = Users() print users.__table__.select() ``` ...SELECT users.......
75,848
<p>I'm trying to insert a <a href="http://en.wikipedia.org/wiki/Spry_framework" rel="nofollow noreferrer">Spry</a> <a href="http://en.wikipedia.org/wiki/Accordion_(GUI)" rel="nofollow noreferrer">accordion</a> into an already existing <a href="http://en.wikipedia.org/wiki/JavaServer_Faces" rel="nofollow noreferrer">JSF</a> page using <a href="http://en.wikipedia.org/wiki/Adobe_Dreamweaver" rel="nofollow noreferrer">Dreamweaver</a>. Is this possible? </p> <p>I've already tried several things, and only the labels show up.</p>
[ { "answer_id": 81534, "author": "Dave Smylie", "author_id": 1505600, "author_profile": "https://Stackoverflow.com/users/1505600", "pm_score": 3, "selected": true, "text": "<p>I'm not a Dreamweaver expert, but all Spry Accordian requires is the correct HTML structure. E.g.: </p>\n\n<pre><code> &lt;div id=\"Accordion1\" class=\"Accordion\"&gt;\n &lt;div class=\"AccordionPanel\"&gt;\n &lt;div class=\"AccordionPanelTab\"&gt;Panel 1&lt;/div&gt;\n &lt;div class=\"AccordionPanelContent\"&gt;\n Panel 1 Content&lt;br/&gt;\n Panel 1 Content&lt;br/&gt;\n Panel 1 Content&lt;br/&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n</code></pre>\n\n<p>Provided you have the <a href=\"http://en.wikipedia.org/wiki/JavaScript\" rel=\"nofollow noreferrer\">JavaScript</a> library loaded correctly, that should pretty much be all you need to do.</p>\n" }, { "answer_id": 123868, "author": "Mike Cornell", "author_id": 419788, "author_profile": "https://Stackoverflow.com/users/419788", "pm_score": 0, "selected": false, "text": "<p>The only other thing you might check is if your ids are getting munged by JSF. Obviously that could impact the ability of Spry to wire itself to your accordion html structure.</p>\n\n<p>+1 to Dave's answer.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/75848", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1459442/" ]
I'm trying to insert a [Spry](http://en.wikipedia.org/wiki/Spry_framework) [accordion](http://en.wikipedia.org/wiki/Accordion_(GUI)) into an already existing [JSF](http://en.wikipedia.org/wiki/JavaServer_Faces) page using [Dreamweaver](http://en.wikipedia.org/wiki/Adobe_Dreamweaver). Is this possible? I've already tried several things, and only the labels show up.
I'm not a Dreamweaver expert, but all Spry Accordian requires is the correct HTML structure. E.g.: ``` <div id="Accordion1" class="Accordion"> <div class="AccordionPanel"> <div class="AccordionPanelTab">Panel 1</div> <div class="AccordionPanelContent"> Panel 1 Content<br/> Panel 1 Content<br/> Panel 1 Content<br/> </div> </div> </div> ``` Provided you have the [JavaScript](http://en.wikipedia.org/wiki/JavaScript) library loaded correctly, that should pretty much be all you need to do.
75,943
<p>I'm working on a web page where I'm making an AJAX call that returns a chunk of HTML like: </p> <pre><code>&lt;div&gt; &lt;!-- some html --&gt; &lt;script type="text/javascript"&gt; /** some javascript */ &lt;/script&gt; &lt;/div&gt; </code></pre> <p>I'm inserting the whole thing into the DOM, but the JavaScript isn't being run. Is there a way to run it? </p> <p>Some details: I can't control what's in the script block (so I can't change it to a function that could be called), I just need the whole block to be executed. I can't call eval on the response because the JavaScript is within a larger block of HTML. I could do some kind of regex to separate out the JavaScript and then call eval on it, but that's pretty yucky. Anyone know a better way?</p>
[ { "answer_id": 76003, "author": "Scott Nichols", "author_id": 4299, "author_profile": "https://Stackoverflow.com/users/4299", "pm_score": 4, "selected": false, "text": "<p>You don't have to use regex if you are using the response to fill a div or something. You can use getElementsByTagName. </p>\n\n<pre><code>div.innerHTML = response;\nvar scripts = div.getElementsByTagName('script');\nfor (var ix = 0; ix &lt; scripts.length; ix++) {\n eval(scripts[ix].text);\n}\n</code></pre>\n" }, { "answer_id": 76054, "author": "Quintin Robinson", "author_id": 12707, "author_profile": "https://Stackoverflow.com/users/12707", "pm_score": 1, "selected": false, "text": "<p>The best method would probably be to identify and eval the contents of the script block directly via the DOM.</p>\n\n<p>I would be careful though.. if you are implementing this to overcome a limitation of some off site call you are opening up a security hole.</p>\n\n<p>Whatever you implement could be exploited for XSS.</p>\n" }, { "answer_id": 76068, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 2, "selected": false, "text": "<p>An alternative is to not just dump the return from the Ajax call into the DOM using InnerHTML.</p>\n\n<p>You can insert each node dynamically, and then the script will run.</p>\n\n<p>Otherwise, the browser just assumes you are inserting a text node, and ignores the scripts.</p>\n\n<p>Using Eval is rather evil, because it requires another instance of the Javascript VM to be fired up and JIT the passed string.</p>\n" }, { "answer_id": 76100, "author": "Ed.", "author_id": 12257, "author_profile": "https://Stackoverflow.com/users/12257", "pm_score": 5, "selected": true, "text": "<p>Script added by setting the innerHTML property of an element doesn't get executed. Try creating a new div, setting its innerHTML, then adding this new div to the DOM. For example:</p>\n\n<pre>\n&lt;html&gt;\n&lt;head&gt;\n&lt;script type='text/javascript'&gt;\nfunction addScript()\n{\n var str = &quot;&lt;script&gt;alert('i am here');&lt;\\/script&gt;&quot;;\n var newdiv = document.createElement('div');\n newdiv.innerHTML = str;\n document.getElementById('target').appendChild(newdiv);\n}\n&lt;/script&gt;\n&lt;/head&gt;\n&lt;body&gt;\n&lt;input type=&quot;button&quot; value=&quot;add script&quot; onclick=&quot;addScript()&quot;/&gt;\n&lt;div&gt;hello world&lt;/div&gt;\n&lt;div id=&quot;target&quot;&gt;&lt;/div&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</pre>\n" }, { "answer_id": 76387, "author": "Diodeus - James MacFarlane", "author_id": 12579, "author_profile": "https://Stackoverflow.com/users/12579", "pm_score": 0, "selected": false, "text": "<p>You can use one of the popular Ajax libraries that do this for you natively. I like <a href=\"http://www.prototypejs.org/\" rel=\"nofollow noreferrer\">Prototype</a>. You can just add evalScripts:true as part of your Ajax call and it happens automagically.</p>\n" }, { "answer_id": 35462561, "author": "Roman Vottner", "author_id": 1377895, "author_profile": "https://Stackoverflow.com/users/1377895", "pm_score": 3, "selected": false, "text": "<p>While the accepted answer from @Ed. does not work on current versions of Firefox, Google Chrome or Safari browsers I managed to adept his example in order to invoke dynamically added scripts.</p>\n\n<p>The necessary changes are only in the way scripts are added to DOM. Instead of adding it as <code>innerHTML</code> the trick was to create a new script element and add the actual script content as <code>innerHTML</code> to the created element and then append the script element to the actual target.</p>\n\n<pre><code>&lt;html&gt;\n&lt;head&gt;\n&lt;script type='text/javascript'&gt;\nfunction addScript()\n{\n var newdiv = document.createElement('div');\n\n var p = document.createElement('p');\n p.innerHTML = \"Dynamically added text\";\n newdiv.appendChild(p);\n\n var script = document.createElement('script');\n script.innerHTML = \"alert('i am here');\";\n newdiv.appendChild(script);\n\n document.getElementById('target').appendChild(newdiv);\n}\n&lt;/script&gt;\n&lt;/head&gt;\n&lt;body&gt;\n&lt;input type=\"button\" value=\"add script\" onclick=\"addScript()\"/&gt;\n&lt;div&gt;hello world&lt;/div&gt;\n&lt;div id=\"target\"&gt;&lt;/div&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>This works for me on Firefox 42, Google Chrome 48 and Safari 9.0.3</p>\n" }, { "answer_id": 63677480, "author": "Matthew Beck", "author_id": 2413712, "author_profile": "https://Stackoverflow.com/users/2413712", "pm_score": 0, "selected": false, "text": "<p>For those who like to live dangerously:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>// This is the HTML with script element(s) we want to inject\nvar newHtml = '&lt;b&gt;After!&lt;/b&gt;\\r\\n&lt;' +\n 'script&gt;\\r\\nchangeColorEverySecond();\\r\\n&lt;/' +\n 'script&gt;';\n \n// Here, we separate the script tags from the non-script HTML\nvar parts = separateScriptElementsFromHtml(newHtml);\n\nfunction separateScriptElementsFromHtml(fullHtmlString) {\n var inner = [], outer = [], m;\n while (m = /&lt;script&gt;([^&lt;]*)&lt;\\/script&gt;/gi.exec(fullHtmlString)) {\n outer.push(fullHtmlString.substr(0, m.index));\n inner.push(m[1]);\n fullHtmlString = fullHtmlString.substr(m.index + m[0].length);\n }\n outer.push(fullHtmlString);\n return {\n html: outer.join('\\r\\n'),\n js: inner.join('\\r\\n')\n };\n}\n\n// In 2 seconds, inject the new HTML, and run the JS\nsetTimeout(function(){\n document.getElementsByTagName('P')[0].innerHTML = parts.html;\n eval(parts.js);\n}, 2000);\n\n\n// This is the function inside the script tag\nfunction changeColorEverySecond() {\n document.getElementsByTagName('p')[0].style.color = getRandomColor();\n setTimeout(changeColorEverySecond, 1000);\n}\n\n// Here is a fun fun function copied from:\n// https://stackoverflow.com/a/1484514/2413712\nfunction getRandomColor() {\n var letters = '0123456789ABCDEF';\n var color = '#';\n for (var i = 0; i &lt; 6; i++) {\n color += letters[Math.floor(Math.random() * 16)];\n }\n return color;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;p&gt;Before&lt;/p&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/75943", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4243/" ]
I'm working on a web page where I'm making an AJAX call that returns a chunk of HTML like: ``` <div> <!-- some html --> <script type="text/javascript"> /** some javascript */ </script> </div> ``` I'm inserting the whole thing into the DOM, but the JavaScript isn't being run. Is there a way to run it? Some details: I can't control what's in the script block (so I can't change it to a function that could be called), I just need the whole block to be executed. I can't call eval on the response because the JavaScript is within a larger block of HTML. I could do some kind of regex to separate out the JavaScript and then call eval on it, but that's pretty yucky. Anyone know a better way?
Script added by setting the innerHTML property of an element doesn't get executed. Try creating a new div, setting its innerHTML, then adding this new div to the DOM. For example: ``` <html> <head> <script type='text/javascript'> function addScript() { var str = "<script>alert('i am here');<\/script>"; var newdiv = document.createElement('div'); newdiv.innerHTML = str; document.getElementById('target').appendChild(newdiv); } </script> </head> <body> <input type="button" value="add script" onclick="addScript()"/> <div>hello world</div> <div id="target"></div> </body> </html> ```
75,978
<p>In a .NET Win console application, I would like to access an App.config file in a location different from the console application binary. For example, how can C:\bin\Text.exe get its settings from C:\Test.exe.config?</p>
[ { "answer_id": 76067, "author": "Santiago Palladino", "author_id": 12791, "author_profile": "https://Stackoverflow.com/users/12791", "pm_score": 3, "selected": false, "text": "<p>Use the following (remember to include System.Configuration assembly)</p>\n\n<pre><code>ConfigurationManager.OpenExeConfiguration(exePath)\n</code></pre>\n" }, { "answer_id": 76071, "author": "Michael Meadows", "author_id": 7643, "author_profile": "https://Stackoverflow.com/users/7643", "pm_score": 2, "selected": false, "text": "<p>You can set it by creating a new app domain:</p>\n\n<pre><code>AppDomainSetup domainSetup = new AppDomainSetup();\ndomainSetup.ConfigurationFile = fileLocation;\nAppDomain add = AppDomain.CreateDomain(\"myNewAppDomain\", securityInfo, domainSetup);\n</code></pre>\n" }, { "answer_id": 76085, "author": "jeff.willis", "author_id": 9829, "author_profile": "https://Stackoverflow.com/users/9829", "pm_score": 5, "selected": true, "text": "<pre><code>using System.Configuration; \n\nConfiguration config =\nConfigurationManager.OpenExeConfiguration(\"C:\\Test.exe\");\n</code></pre>\n\n<p>You can then access the app settings, connection strings, etc from the config instance. This assumes of course that the config file is properly formatted and your app has read access to the directory. Notice the path is <strong><em>not</em></strong> \"C:\\Test.exe.config\" The method looks for a config file associated with the file you specify. If you specify \"C:\\Test.exe.config\" it will look for \"C:\\Test.exe.config.config\" Kinda lame, but understandable, I guess.</p>\n\n<p>Reference here: <a href=\"http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.openexeconfiguration.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.openexeconfiguration.aspx</a></p>\n" }, { "answer_id": 18218068, "author": "CodeNaked", "author_id": 142794, "author_profile": "https://Stackoverflow.com/users/142794", "pm_score": 3, "selected": false, "text": "<p>It appears that you can use the <a href=\"http://msdn.microsoft.com/en-us/library/37z40s1c.aspx\" rel=\"nofollow noreferrer\"><code>AppDomain.SetData</code></a> method to achieve this. The documentation states:</p>\n\n<blockquote>\n <p>You cannot insert or modify system entries with this method.</p>\n</blockquote>\n\n<p>Regardless, doing so does appear to work. The documentation for the <a href=\"http://msdn.microsoft.com/en-us/library/system.appdomain.getdata.aspx\" rel=\"nofollow noreferrer\"><code>AppDomain.GetData</code></a> method lists the system entries available, of interest is the <code>\"APP_CONFIG_FILE\"</code> entry.</p>\n\n<p>If we set the <code>\"APP_CONFIG_FILE\"</code> before any application settings are used, we can modify where the <code>app.config</code> is loaded from. For example:</p>\n\n<pre><code>public class Program\n{\n public static void Main()\n {\n AppDomain.CurrentDomain.SetData(\"APP_CONFIG_FILE\", @\"C:\\Temp\\test.config\");\n //...\n }\n}\n</code></pre>\n\n<p>I found this solution documented in <a href=\"http://weblogs.asp.net/israelio/archive/2005/01/10/349825.aspx\" rel=\"nofollow noreferrer\">this blog</a> and a more complete answer (to a related question) can be found <a href=\"https://stackoverflow.com/a/6151688/142794\">here</a>.</p>\n" }, { "answer_id": 62144686, "author": "Balaji Dinakaran", "author_id": 4890791, "author_profile": "https://Stackoverflow.com/users/4890791", "pm_score": 0, "selected": false, "text": "<pre><code>AppDomainSetup domainSetup = new AppDomainSetup();\n domainSetup.ConfigurationFile = @\"D:\\Mine\\Company\\\";\n string browserName = ConfigurationManager.AppSettings[\"browser\"];\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/75978", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2748/" ]
In a .NET Win console application, I would like to access an App.config file in a location different from the console application binary. For example, how can C:\bin\Text.exe get its settings from C:\Test.exe.config?
``` using System.Configuration; Configuration config = ConfigurationManager.OpenExeConfiguration("C:\Test.exe"); ``` You can then access the app settings, connection strings, etc from the config instance. This assumes of course that the config file is properly formatted and your app has read access to the directory. Notice the path is ***not*** "C:\Test.exe.config" The method looks for a config file associated with the file you specify. If you specify "C:\Test.exe.config" it will look for "C:\Test.exe.config.config" Kinda lame, but understandable, I guess. Reference here: <http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.openexeconfiguration.aspx>
75,980
<p>When encoding a query string to be sent to a web server - when do you use <code>escape()</code> and when do you use <code>encodeURI()</code> or <code>encodeURIComponent()</code>:</p> <p>Use escape:</p> <pre><code>escape("% +&amp;="); </code></pre> <p>OR</p> <p>use encodeURI() / encodeURIComponent()</p> <pre><code>encodeURI("http://www.google.com?var1=value1&amp;var2=value2"); encodeURIComponent("var1=value1&amp;var2=value2"); </code></pre>
[ { "answer_id": 75989, "author": "Daniel Papasian", "author_id": 7548, "author_profile": "https://Stackoverflow.com/users/7548", "pm_score": 5, "selected": false, "text": "<p>encodeURI() - the escape() function is for javascript escaping, not HTTP.</p>\n" }, { "answer_id": 76119, "author": "Pseudo Masochist", "author_id": 8529, "author_profile": "https://Stackoverflow.com/users/8529", "pm_score": 3, "selected": false, "text": "<p>Also remember that they all encode different sets of characters, and select the one you need appropriately. encodeURI() encodes fewer characters than encodeURIComponent(), which encodes fewer (and also different, to dannyp's point) characters than escape().</p>\n" }, { "answer_id": 3608791, "author": "Arne Evertsson", "author_id": 16686, "author_profile": "https://Stackoverflow.com/users/16686", "pm_score": 12, "selected": true, "text": "<h1>escape()</h1>\n<p>Don't use it!\n<code>escape()</code> is defined in section <a href=\"https://www.ecma-international.org/ecma-262/9.0/index.html#sec-escape-string\" rel=\"noreferrer\">B.2.1.2 escape</a> and the <a href=\"https://www.ecma-international.org/ecma-262/9.0/index.html#sec-additional-ecmascript-features-for-web-browsers\" rel=\"noreferrer\">introduction text of Annex B</a> says:</p>\n<blockquote>\n<p>... All of the language features and behaviours specified in this annex have one or more undesirable characteristics and in the absence of legacy usage would be removed from this specification. ...<br />\n... Programmers should not use or assume the existence of these features and behaviours when writing new ECMAScript code....</p>\n</blockquote>\n<p>Behaviour:</p>\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/escape\" rel=\"noreferrer\">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/escape</a></p>\n<p>Special characters are encoded with the exception of: @*_+-./</p>\n<p>The hexadecimal form for characters, whose code unit value is 0xFF or less, is a two-digit escape sequence: <code>%xx</code>.</p>\n<p>For characters with a greater code unit, the four-digit format <code>%uxxxx</code> is used. This is not allowed within a query string (as defined in <a href=\"https://www.rfc-editor.org/rfc/rfc3986#section-3.4\" rel=\"noreferrer\">RFC3986</a>):</p>\n<pre><code>query = *( pchar / &quot;/&quot; / &quot;?&quot; )\npchar = unreserved / pct-encoded / sub-delims / &quot;:&quot; / &quot;@&quot;\nunreserved = ALPHA / DIGIT / &quot;-&quot; / &quot;.&quot; / &quot;_&quot; / &quot;~&quot;\npct-encoded = &quot;%&quot; HEXDIG HEXDIG\nsub-delims = &quot;!&quot; / &quot;$&quot; / &quot;&amp;&quot; / &quot;'&quot; / &quot;(&quot; / &quot;)&quot;\n / &quot;*&quot; / &quot;+&quot; / &quot;,&quot; / &quot;;&quot; / &quot;=&quot;\n</code></pre>\n<p>A percent sign is only allowed if it is directly followed by two hexdigits, percent followed by <code>u</code> is not allowed.</p>\n<h1>encodeURI()</h1>\n<p>Use encodeURI when you want a working URL. Make this call:</p>\n<pre><code>encodeURI(&quot;http://www.example.org/a file with spaces.html&quot;)\n</code></pre>\n<p>to get:</p>\n<pre><code>http://www.example.org/a%20file%20with%20spaces.html\n</code></pre>\n<p>Don't call encodeURIComponent since it would destroy the URL and return</p>\n<pre><code>http%3A%2F%2Fwww.example.org%2Fa%20file%20with%20spaces.html\n</code></pre>\n<p>Note that encodeURI, like encodeURIComponent, does not escape the ' character.</p>\n<h1>encodeURIComponent()</h1>\n<p>Use encodeURIComponent when you want to encode the value of a URL parameter.</p>\n<pre><code>var p1 = encodeURIComponent(&quot;http://example.org/?a=12&amp;b=55&quot;)\n</code></pre>\n<p>Then you may create the URL you need:</p>\n<pre><code>var url = &quot;http://example.net/?param1=&quot; + p1 + &quot;&amp;param2=99&quot;;\n</code></pre>\n<p>And you will get this complete URL:</p>\n<p><code>http://example.net/?param1=http%3A%2F%2Fexample.org%2F%Ffa%3D12%26b%3D55&amp;param2=99</code></p>\n<p>Note that encodeURIComponent does not escape the <code>'</code> character. A common bug is to use it to create html attributes such as <code>href='MyUrl'</code>, which could suffer an injection bug. If you are constructing html from strings, either use <code>&quot;</code> instead of <code>'</code> for attribute quotes, or add an extra layer of encoding (<code>'</code> can be encoded as %27).</p>\n<p>For more information on this type of encoding you can check: <a href=\"http://en.wikipedia.org/wiki/Percent-encoding\" rel=\"noreferrer\">http://en.wikipedia.org/wiki/Percent-encoding</a></p>\n" }, { "answer_id": 12796866, "author": "Damien", "author_id": 438970, "author_profile": "https://Stackoverflow.com/users/438970", "pm_score": 6, "selected": false, "text": "<p>I found this article enlightening :\n<a href=\"http://unixpapa.com/js/querystring.html\" rel=\"noreferrer\">Javascript Madness: Query String Parsing</a></p>\n\n<p>I found it when I was trying to undersand why decodeURIComponent was not decoding '+' correctly. Here is an extract:</p>\n\n<pre><code>String: \"A + B\"\nExpected Query String Encoding: \"A+%2B+B\"\nescape(\"A + B\") = \"A%20+%20B\" Wrong!\nencodeURI(\"A + B\") = \"A%20+%20B\" Wrong!\nencodeURIComponent(\"A + B\") = \"A%20%2B%20B\" Acceptable, but strange\n\nEncoded String: \"A+%2B+B\"\nExpected Decoding: \"A + B\"\nunescape(\"A+%2B+B\") = \"A+++B\" Wrong!\ndecodeURI(\"A+%2B+B\") = \"A+++B\" Wrong!\ndecodeURIComponent(\"A+%2B+B\") = \"A+++B\" Wrong!\n</code></pre>\n" }, { "answer_id": 16435373, "author": "Kirankumar Sripati", "author_id": 2191887, "author_profile": "https://Stackoverflow.com/users/2191887", "pm_score": 5, "selected": false, "text": "<p>encodeURIComponent doesn't encode <code>-_.!~*'()</code>, causing problem in posting data to php in xml string.</p>\n\n<p>For example:<br/>\n<code>&lt;xml&gt;&lt;text x=\"100\" y=\"150\" value=\"It's a value with single quote\" /&gt;\n&lt;/xml&gt;</code></p>\n\n<p>General escape with <code>encodeURI</code><br/>\n<code>%3Cxml%3E%3Ctext%20x=%22100%22%20y=%22150%22%20value=%22It's%20a%20value%20with%20single%20quote%22%20/%3E%20%3C/xml%3E</code></p>\n\n<p>You can see, single quote is not encoded.\nTo resolve issue I created two functions to solve issue in my project, for Encoding URL:</p>\n\n<pre><code>function encodeData(s:String):String{\n return encodeURIComponent(s).replace(/\\-/g, \"%2D\").replace(/\\_/g, \"%5F\").replace(/\\./g, \"%2E\").replace(/\\!/g, \"%21\").replace(/\\~/g, \"%7E\").replace(/\\*/g, \"%2A\").replace(/\\'/g, \"%27\").replace(/\\(/g, \"%28\").replace(/\\)/g, \"%29\");\n}\n</code></pre>\n\n<p>For Decoding URL:</p>\n\n<pre><code>function decodeData(s:String):String{\n try{\n return decodeURIComponent(s.replace(/\\%2D/g, \"-\").replace(/\\%5F/g, \"_\").replace(/\\%2E/g, \".\").replace(/\\%21/g, \"!\").replace(/\\%7E/g, \"~\").replace(/\\%2A/g, \"*\").replace(/\\%27/g, \"'\").replace(/\\%28/g, \"(\").replace(/\\%29/g, \")\"));\n }catch (e:Error) {\n }\n return \"\";\n}\n</code></pre>\n" }, { "answer_id": 17235463, "author": "molokoloco", "author_id": 174449, "author_profile": "https://Stackoverflow.com/users/174449", "pm_score": 1, "selected": false, "text": "<p>I have this function...</p>\n\n<pre><code>var escapeURIparam = function(url) {\n if (encodeURIComponent) url = encodeURIComponent(url);\n else if (encodeURI) url = encodeURI(url);\n else url = escape(url);\n url = url.replace(/\\+/g, '%2B'); // Force the replacement of \"+\"\n return url;\n};\n</code></pre>\n" }, { "answer_id": 18126158, "author": "veeTrain", "author_id": 469643, "author_profile": "https://Stackoverflow.com/users/469643", "pm_score": 2, "selected": false, "text": "<p>I've found that experimenting with the various methods is a good sanity check even after having a good handle of what their various uses and capabilities are.</p>\n\n<p>Towards that end I have found <a href=\"http://www.the-art-of-web.com/javascript/escape/\" rel=\"nofollow\">this website</a> extremely useful to confirm my suspicions that I am doing something appropriately. It has also proven useful for decoding an encodeURIComponent'ed string which can be rather challenging to interpret. A great bookmark to have:</p>\n\n<p><a href=\"http://www.the-art-of-web.com/javascript/escape/\" rel=\"nofollow\">http://www.the-art-of-web.com/javascript/escape/</a></p>\n" }, { "answer_id": 23250699, "author": "Jerry Joseph", "author_id": 1001217, "author_profile": "https://Stackoverflow.com/users/1001217", "pm_score": 4, "selected": false, "text": "<p>I recommend not to use one of those methods as is. Write your own function which does the right thing.</p>\n\n<p>MDN has given a good example on url encoding shown below.</p>\n\n<pre><code>var fileName = 'my file(2).txt';\nvar header = \"Content-Disposition: attachment; filename*=UTF-8''\" + encodeRFC5987ValueChars(fileName);\n\nconsole.log(header); \n// logs \"Content-Disposition: attachment; filename*=UTF-8''my%20file%282%29.txt\"\n\n\nfunction encodeRFC5987ValueChars (str) {\n return encodeURIComponent(str).\n // Note that although RFC3986 reserves \"!\", RFC5987 does not,\n // so we do not need to escape it\n replace(/['()]/g, escape). // i.e., %27 %28 %29\n replace(/\\*/g, '%2A').\n // The following are not required for percent-encoding per RFC5987, \n // so we can allow for a little better readability over the wire: |`^\n replace(/%(?:7C|60|5E)/g, unescape);\n}\n</code></pre>\n\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent\" rel=\"noreferrer\">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent</a></p>\n" }, { "answer_id": 23842171, "author": "Johann Echavarria", "author_id": 2391782, "author_profile": "https://Stackoverflow.com/users/2391782", "pm_score": 9, "selected": false, "text": "<p>The difference between <code>encodeURI()</code> and <code>encodeURIComponent()</code> are exactly 11 characters encoded by encodeURIComponent but not by encodeURI:</p>\n\n<p><img src=\"https://i.imgur.com/rHWC1r1.png\" alt=\"Table with the ten differences between encodeURI and encodeURIComponent\"></p>\n\n<p>I generated this table easily with <strong>console.table</strong> in Google Chrome with this code:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var arr = [];\r\nfor(var i=0;i&lt;256;i++) {\r\n var char=String.fromCharCode(i);\r\n if(encodeURI(char)!==encodeURIComponent(char)) {\r\n arr.push({\r\n character:char,\r\n encodeURI:encodeURI(char),\r\n encodeURIComponent:encodeURIComponent(char)\r\n });\r\n }\r\n}\r\nconsole.table(arr);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 33019871, "author": "30thh", "author_id": 608164, "author_profile": "https://Stackoverflow.com/users/608164", "pm_score": 4, "selected": false, "text": "<p>Small comparison table Java vs. JavaScript vs. PHP.</p>\n\n<pre><code>1. Java URLEncoder.encode (using UTF8 charset)\n2. JavaScript encodeURIComponent\n3. JavaScript escape\n4. PHP urlencode\n5. PHP rawurlencode\n\nchar JAVA JavaScript --PHP---\n[ ] + %20 %20 + %20\n[!] %21 ! %21 %21 %21\n[*] * * * %2A %2A\n['] %27 ' %27 %27 %27 \n[(] %28 ( %28 %28 %28\n[)] %29 ) %29 %29 %29\n[;] %3B %3B %3B %3B %3B\n[:] %3A %3A %3A %3A %3A\n[@] %40 %40 @ %40 %40\n[&amp;] %26 %26 %26 %26 %26\n[=] %3D %3D %3D %3D %3D\n[+] %2B %2B + %2B %2B\n[$] %24 %24 %24 %24 %24\n[,] %2C %2C %2C %2C %2C\n[/] %2F %2F / %2F %2F\n[?] %3F %3F %3F %3F %3F\n[#] %23 %23 %23 %23 %23\n[[] %5B %5B %5B %5B %5B\n[]] %5D %5D %5D %5D %5D\n----------------------------------------\n[~] %7E ~ %7E %7E ~\n[-] - - - - -\n[_] _ _ _ _ _\n[%] %25 %25 %25 %25 %25\n[\\] %5C %5C %5C %5C %5C\n----------------------------------------\nchar -JAVA- --JavaScript-- -----PHP------\n[ä] %C3%A4 %C3%A4 %E4 %C3%A4 %C3%A4\n[ф] %D1%84 %D1%84 %u0444 %D1%84 %D1%84\n</code></pre>\n" }, { "answer_id": 43537042, "author": "Gaurav Tiwari", "author_id": 7220283, "author_profile": "https://Stackoverflow.com/users/7220283", "pm_score": 3, "selected": false, "text": "<p>For the purpose of encoding javascript has given three inbuilt functions -</p>\n\n<ol>\n<li><p><code>escape()</code> - does not encode <code>@*/+</code>\nThis method is deprecated after the ECMA 3 so it should be avoided.</p></li>\n<li><p><code>encodeURI()</code> - does not encode <code>~!@#$&amp;*()=:/,;?+'</code>\nIt assumes that the URI is a complete URI, so does not encode reserved characters that have special meaning in the URI.\nThis method is used when the intent is to convert the complete URL instead of some special segment of URL.\nExample - <code>encodeURI('http://stackoverflow.com');</code>\nwill give - <a href=\"http://stackoverflow.com\">http://stackoverflow.com</a></p></li>\n<li><p><code>encodeURIComponent()</code> - does not encode <code>- _ . ! ~ * ' ( )</code>\nThis function encodes a Uniform Resource Identifier (URI) component by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character. This method should be used to convert a component of URL. For instance some user input needs to be appended\nExample - <code>encodeURIComponent('http://stackoverflow.com');</code>\nwill give - http%3A%2F%2Fstackoverflow.com</p></li>\n</ol>\n\n<p><em>All this encoding is performed in UTF 8 i.e the characters will be converted in UTF-8 format.</em> </p>\n\n<p><strong><em>encodeURIComponent differ from encodeURI in that it encode reserved characters and Number sign # of encodeURI</em></strong></p>\n" }, { "answer_id": 46441344, "author": "Michael", "author_id": 599912, "author_profile": "https://Stackoverflow.com/users/599912", "pm_score": 2, "selected": false, "text": "<p>The accepted answer is good.\nTo extend on the last part:</p>\n\n<blockquote>\n <p>Note that encodeURIComponent does not escape the ' character. A common\n bug is to use it to create html attributes such as href='MyUrl', which\n could suffer an injection bug. If you are constructing html from\n strings, either use \" instead of ' for attribute quotes, or add an\n extra layer of encoding (' can be encoded as %27).</p>\n</blockquote>\n\n<p>If you want to be on the safe side, <a href=\"https://en.wikipedia.org/wiki/Percent-encoding#Percent-encoding_unreserved_characters\" rel=\"nofollow noreferrer\">percent encoding unreserved characters</a> should be encoded as well. </p>\n\n<p>You can use this method to escape them (source <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent\" rel=\"nofollow noreferrer\">Mozilla</a>)</p>\n\n<pre><code>function fixedEncodeURIComponent(str) {\n return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {\n return '%' + c.charCodeAt(0).toString(16);\n });\n}\n\n// fixedEncodeURIComponent(\"'\") --&gt; \"%27\"\n</code></pre>\n" }, { "answer_id": 48697555, "author": "ryanpcmcquen", "author_id": 2662028, "author_profile": "https://Stackoverflow.com/users/2662028", "pm_score": 2, "selected": false, "text": "<p>Modern rewrite of @johann-echavarria's answer:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>console.log(\r\n Array(256)\r\n .fill()\r\n .map((ignore, i) =&gt; String.fromCharCode(i))\r\n .filter(\r\n (char) =&gt;\r\n encodeURI(char) !== encodeURIComponent(char)\r\n ? {\r\n character: char,\r\n encodeURI: encodeURI(char),\r\n encodeURIComponent: encodeURIComponent(char)\r\n }\r\n : false\r\n )\r\n)</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Or if you can use a table, replace <code>console.log</code> with <code>console.table</code> (for the prettier output).</p>\n" }, { "answer_id": 54630088, "author": "akinuri", "author_id": 2202732, "author_profile": "https://Stackoverflow.com/users/2202732", "pm_score": 2, "selected": false, "text": "<p>Inspired by <a href=\"https://stackoverflow.com/questions/75980/when-are-you-supposed-to-use-escape-instead-of-encodeuri-encodeuricomponent/23842171#23842171\">Johann's table</a>, I've decided to extend the table. I wanted to see which ASCII characters get encoded.</p>\n\n<p><a href=\"https://i.stack.imgur.com/gjKxF.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/gjKxF.png\" alt=\"screenshot of console.table\"></a></p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var ascii = \" !\\\"#$%&amp;'()*+,-./0123456789:;&lt;=&gt;?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\";\r\n\r\nvar encoded = [];\r\n\r\nascii.split(\"\").forEach(function (char) {\r\n var obj = { char };\r\n if (char != encodeURI(char))\r\n obj.encodeURI = encodeURI(char);\r\n if (char != encodeURIComponent(char))\r\n obj.encodeURIComponent = encodeURIComponent(char);\r\n if (obj.encodeURI || obj.encodeURIComponent)\r\n encoded.push(obj);\r\n});\r\n\r\nconsole.table(encoded);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Table shows only the encoded characters. Empty cells mean that the original and the encoded characters are the same.</p>\n\n<hr>\n\n<p>Just to be extra, I'm adding another table for <a href=\"http://php.net/manual/en/function.urlencode.php\" rel=\"nofollow noreferrer\"><code>urlencode()</code></a> vs <a href=\"http://php.net/manual/en/function.rawurlencode.php\" rel=\"nofollow noreferrer\"><code>rawurlencode()</code></a>. The only difference seems to be the encoding of space character.</p>\n\n<p><a href=\"https://i.stack.imgur.com/gJnmU.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/gJnmU.png\" alt=\"screenshot of console.table\"></a></p>\n\n<pre><code>&lt;script&gt;\n&lt;?php\n$ascii = str_split(\" !\\\"#$%&amp;'()*+,-./0123456789:;&lt;=&gt;?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\", 1);\n$encoded = [];\nforeach ($ascii as $char) {\n $obj = [\"char\" =&gt; $char];\n if ($char != urlencode($char))\n $obj[\"urlencode\"] = urlencode($char);\n if ($char != rawurlencode($char))\n $obj[\"rawurlencode\"] = rawurlencode($char);\n if (isset($obj[\"rawurlencode\"]) || isset($obj[\"rawurlencode\"]))\n $encoded[] = $obj;\n}\necho \"var encoded = \" . json_encode($encoded) . \";\";\n?&gt;\nconsole.table(encoded);\n&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 62436236, "author": "HoldOffHunger", "author_id": 2430549, "author_profile": "https://Stackoverflow.com/users/2430549", "pm_score": 3, "selected": false, "text": "<p>Just try <code>encodeURI()</code> and <code>encodeURIComponent()</code> yourself...</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>console.log(encodeURIComponent('@#$%^&amp;*'));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Input: <code>@#$%^&amp;*</code>. Output: <code>%40%23%24%25%5E%26*</code>. So, wait, what happened to <code>*</code>? Why wasn't this converted? It could definitely cause problems if you tried to do <code>linux command &quot;$string&quot;</code>. TLDR: You actually want <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent\" rel=\"nofollow noreferrer\"><code>fixedEncodeURIComponent()</code></a> and <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI\" rel=\"nofollow noreferrer\"><code>fixedEncodeURI()</code></a>. Long-story...</p>\n<p><em><strong>When to use <code>encodeURI()</code>?</strong></em> Never. <code>encodeURI()</code> fails to adhere to RFC3986 with regard to bracket-encoding. Use <code>fixedEncodeURI()</code>, as defined and further explained at the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI\" rel=\"nofollow noreferrer\"><strong>MDN encodeURI() Documentation</strong></a>...</p>\n<blockquote>\n<pre><code>function fixedEncodeURI(str) {\n return encodeURI(str).replace(/%5B/g, '[').replace(/%5D/g, ']');\n}\n</code></pre>\n</blockquote>\n<p><em><strong>When to use <code>encodeURIComponent()</code>?</strong></em> Never. <code>encodeURIComponent()</code> fails to adhere to RFC3986 with regard to encoding: <code>!'()*</code>. Use <code>fixedEncodeURIComponent()</code>, as defined and further explained at the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent\" rel=\"nofollow noreferrer\"><strong>MDN encodeURIComponent() Documentation</strong></a>...</p>\n<blockquote>\n<pre><code>function fixedEncodeURIComponent(str) {\n return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {\n return '%' + c.charCodeAt(0).toString(16);\n });\n}\n</code></pre>\n</blockquote>\n<p>Then you can use <code>fixedEncodeURI()</code> to encode a single URL piece, whereas <code>fixedEncodeURIComponent()</code> will encode URL pieces and connectors; or, simply, <code>fixedEncodeURI()</code> will not encode <code>+@?=:#;,$&amp;</code> (as <code>&amp;</code> and <code>+</code> are common URL operators), but <code>fixedEncodeURIComponent()</code> will.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/75980", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1341/" ]
When encoding a query string to be sent to a web server - when do you use `escape()` and when do you use `encodeURI()` or `encodeURIComponent()`: Use escape: ``` escape("% +&="); ``` OR use encodeURI() / encodeURIComponent() ``` encodeURI("http://www.google.com?var1=value1&var2=value2"); encodeURIComponent("var1=value1&var2=value2"); ```
escape() ======== Don't use it! `escape()` is defined in section [B.2.1.2 escape](https://www.ecma-international.org/ecma-262/9.0/index.html#sec-escape-string) and the [introduction text of Annex B](https://www.ecma-international.org/ecma-262/9.0/index.html#sec-additional-ecmascript-features-for-web-browsers) says: > > ... All of the language features and behaviours specified in this annex have one or more undesirable characteristics and in the absence of legacy usage would be removed from this specification. ... > > ... Programmers should not use or assume the existence of these features and behaviours when writing new ECMAScript code.... > > > Behaviour: <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/escape> Special characters are encoded with the exception of: @\*\_+-./ The hexadecimal form for characters, whose code unit value is 0xFF or less, is a two-digit escape sequence: `%xx`. For characters with a greater code unit, the four-digit format `%uxxxx` is used. This is not allowed within a query string (as defined in [RFC3986](https://www.rfc-editor.org/rfc/rfc3986#section-3.4)): ``` query = *( pchar / "/" / "?" ) pchar = unreserved / pct-encoded / sub-delims / ":" / "@" unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" pct-encoded = "%" HEXDIG HEXDIG sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "=" ``` A percent sign is only allowed if it is directly followed by two hexdigits, percent followed by `u` is not allowed. encodeURI() =========== Use encodeURI when you want a working URL. Make this call: ``` encodeURI("http://www.example.org/a file with spaces.html") ``` to get: ``` http://www.example.org/a%20file%20with%20spaces.html ``` Don't call encodeURIComponent since it would destroy the URL and return ``` http%3A%2F%2Fwww.example.org%2Fa%20file%20with%20spaces.html ``` Note that encodeURI, like encodeURIComponent, does not escape the ' character. encodeURIComponent() ==================== Use encodeURIComponent when you want to encode the value of a URL parameter. ``` var p1 = encodeURIComponent("http://example.org/?a=12&b=55") ``` Then you may create the URL you need: ``` var url = "http://example.net/?param1=" + p1 + "&param2=99"; ``` And you will get this complete URL: `http://example.net/?param1=http%3A%2F%2Fexample.org%2F%Ffa%3D12%26b%3D55&param2=99` Note that encodeURIComponent does not escape the `'` character. A common bug is to use it to create html attributes such as `href='MyUrl'`, which could suffer an injection bug. If you are constructing html from strings, either use `"` instead of `'` for attribute quotes, or add an extra layer of encoding (`'` can be encoded as %27). For more information on this type of encoding you can check: <http://en.wikipedia.org/wiki/Percent-encoding>
76,065
<p>I know that with mysql you can write SQL statements into a .sql file and run the file from the mysql command line like this:</p> <pre><code>mysql&gt; source script.sql </code></pre> <p>How do I pass a variable to the script? For example, if I want to run a script that retrieves all the employees in a department, I want to be able to pass in the number of the department as a variable.</p> <p>I am not trying to run queries through a shell script. There are simple queries I run from the mysql command line. I'm tired of retyping them all the time, and writing a shell script for them would be overkill.</p>
[ { "answer_id": 76124, "author": "Brad Choate", "author_id": 553, "author_profile": "https://Stackoverflow.com/users/553", "pm_score": 6, "selected": true, "text": "<p>Like this:</p>\n\n<pre><code>set @department := 'Engineering';\n</code></pre>\n\n<p>Then, reference <code>@department</code> wherever you need to in script.sql:</p>\n\n<pre><code>update employee set salary = salary + 10000 where department = @department;\n</code></pre>\n" }, { "answer_id": 76287, "author": "longneck", "author_id": 8250, "author_profile": "https://Stackoverflow.com/users/8250", "pm_score": -1, "selected": false, "text": "<p>you really should be looking at a more appropriate way of doing this. i'm going to guess that you're trying to run mysql queries via a shell script. you should instead be using something like PERL or PHP.</p>\n" }, { "answer_id": 25109187, "author": "Yordan Georgiev", "author_id": 65706, "author_profile": "https://Stackoverflow.com/users/65706", "pm_score": 5, "selected": false, "text": "<pre><code> #!/bin/bash\n\n #verify the passed params\n echo 1 cmd arg : $1\n echo 2 cmd arg : $2\n\n export db=$1\n export tbl=$2\n\n #set the params ... Note the quotes ( needed for non-numeric values )\n mysql -uroot -pMySecretPaassword \\\n -e \"set @db='${db}';set @tbl='${tbl}';source run.sql ;\" ;\n\n #usage: bash run.sh my_db my_table\n #\n #eof file: run.sh\n\n --file:run.sql\n\n SET @query = CONCAT('Select * FROM ', @db , '.' , @tbl ) ;\n SELECT 'RUNNING THE FOLLOWING query : ' , @query ;\n PREPARE stmt FROM @query;\n EXECUTE stmt;\n DEALLOCATE PREPARE stmt;\n\n --eof file: run.sql\n</code></pre>\n\n<p>you can re-use the whole concept from <a href=\"https://github.com/YordanGeorgiev/mysql-starter\" rel=\"noreferrer\">from the following project</a></p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/76065", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13519/" ]
I know that with mysql you can write SQL statements into a .sql file and run the file from the mysql command line like this: ``` mysql> source script.sql ``` How do I pass a variable to the script? For example, if I want to run a script that retrieves all the employees in a department, I want to be able to pass in the number of the department as a variable. I am not trying to run queries through a shell script. There are simple queries I run from the mysql command line. I'm tired of retyping them all the time, and writing a shell script for them would be overkill.
Like this: ``` set @department := 'Engineering'; ``` Then, reference `@department` wherever you need to in script.sql: ``` update employee set salary = salary + 10000 where department = @department; ```
76,074
<p>I have a couple old services that I want to completely uninstall. How can I do this?</p>
[ { "answer_id": 76101, "author": "Mark Schill", "author_id": 9482, "author_profile": "https://Stackoverflow.com/users/9482", "pm_score": 6, "selected": false, "text": "<p>Click <em>Start</em> | <strong>Run</strong> and type <code>regedit</code> in the Open: line. Click OK.</p>\n\n<p>Navigate to <code>HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services</code></p>\n\n<p>Scroll down the left pane, locate the service name, right click it and <strong>select Delete</strong>.</p>\n\n<p>Reboot the system.</p>\n" }, { "answer_id": 76127, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 11, "selected": true, "text": "<p>Use the <em>SC</em> command, like this (you need to be on a command prompt to execute the commands in this post):</p>\n\n<pre><code>SC STOP shortservicename\nSC DELETE shortservicename\n</code></pre>\n\n<hr>\n\n<p><strong>Note:</strong> You need to run the command prompt as an administrator, not just logged in as the administrator, but also with administrative rights. If you get errors above about not having the necessary access rights to stop and/or delete the service, run the command prompt as an administrator. You can do this by searching for the command prompt on your start menu and then right-clicking and selecting \"Run as administrator\". <strong>Note to PowerShell users:</strong> <code>sc</code> is aliased to <code>set-content</code>. So <code>sc delete service</code> will actually create a file called <code>delete</code> with the content <code>service</code>. To do this in Powershell, use <code>sc.exe delete service</code> instead</p>\n\n<hr>\n\n<p>If you need to find the short service name of a service, use the following command to generate a text file containing a list of services and their statuses:</p>\n\n<pre><code>SC QUERY state= all &gt;\"C:\\Service List.txt\"\n</code></pre>\n\n<p>For a more concise list, execute this command:</p>\n\n<pre><code>SC QUERY state= all | FIND \"_NAME\"\n</code></pre>\n\n<p>The short service name will be listed just above the display name, like this:</p>\n\n<pre><code>SERVICE_NAME: MyService\nDISPLAY_NAME: My Special Service\n</code></pre>\n\n<p>And thus to delete that service:</p>\n\n<pre><code>SC STOP MyService\nSC DELETE MyService\n</code></pre>\n" }, { "answer_id": 76138, "author": "Mariano", "author_id": 12514, "author_profile": "https://Stackoverflow.com/users/12514", "pm_score": 1, "selected": false, "text": "<p>sc delete name</p>\n" }, { "answer_id": 76158, "author": "asquithea", "author_id": 13530, "author_profile": "https://Stackoverflow.com/users/13530", "pm_score": 5, "selected": false, "text": "<p>Use <strong>services.msc</strong> or (Start > Control Panel > Administrative Tools > Services) to find the service in question. Double-click to see the service name and the path to the executable.</p>\n\n<p>Check the exe version information for a clue as to the owner of the service, and use Add/Remove programs to do a clean uninstall if possible.</p>\n\n<p>Failing that, from the command prompt:</p>\n\n<pre><code>sc stop servicexyz\nsc delete servicexyz\n</code></pre>\n\n<p>No restart should be required.</p>\n" }, { "answer_id": 76239, "author": "Lucas", "author_id": 5966, "author_profile": "https://Stackoverflow.com/users/5966", "pm_score": 2, "selected": false, "text": "<p>Here is a vbs script that was passed down to me:</p>\n\n<pre><code>Set servicelist = GetObject(\"winmgmts:\").InstancesOf (\"Win32_Service\")\n\nfor each service in servicelist\n sname = lcase(service.name)\n If sname = \"NameOfMyService\" Then \n msgbox(sname)\n service.delete ' the internal name of your service\n end if\nnext\n</code></pre>\n" }, { "answer_id": 242268, "author": "CPU_BUSY", "author_id": 27688, "author_profile": "https://Stackoverflow.com/users/27688", "pm_score": 3, "selected": false, "text": "<p>If they are .NET created services you can use the installutil.exe with the /u switch\nits in the .net framework folder like\nC:\\Windows\\Microsoft.NET\\Framework64\\v2.0.50727</p>\n" }, { "answer_id": 15275825, "author": "user2145033", "author_id": 2145033, "author_profile": "https://Stackoverflow.com/users/2145033", "pm_score": 3, "selected": false, "text": "<p>If you have Windows Vista or above please run this from a command prompt as Administrator:</p>\n\n<pre><code>sc delete [your service name as shown in service.msc e.g moneytransfer]\n</code></pre>\n\n<p>For example: <code>sc delete moneytransfer</code></p>\n\n<p>Delete the folder <code>C:\\Program Files\\BBRTL\\moneytransfer\\</code></p>\n\n<p>Find moneytransfer registry keys and delete them:</p>\n\n<pre><code> HKEY_CLASSES_ROOT\\Installer\\Products\\\n HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\\n HKEY_LOCAL_MACHINE\\System\\CurrentControlSet\\Services\\EventLog\\\n HKEY_LOCAL_MACHINE\\System\\CurrentControlSet002\\Services\\\n HKEY_LOCAL_MACHINE\\System\\CurrentControlSet002\\Services\\EventLog\\\n HKEY_LOCAL_MACHINE\\Software\\Classes\\Installer\\Assemblies\\ [remove .exe references]\n HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Windows\\CurrentVersion\\Installer\\Folders\n</code></pre>\n\n<p>These steps have been tested on Windows XP, Windows 7, Windows Vista, Windows Server 2003, and Windows Server 2008.</p>\n" }, { "answer_id": 18865199, "author": "Sachidananda naik", "author_id": 1664913, "author_profile": "https://Stackoverflow.com/users/1664913", "pm_score": 4, "selected": false, "text": "<pre><code>SC DELETE \"service name\"\n</code></pre>\n\n<p>Run the command on cmd as Administrator otherwise you will get this error :- </p>\n\n<blockquote>\n <p>openservice failed 5 access is denied</p>\n</blockquote>\n" }, { "answer_id": 18964681, "author": "Kevin M", "author_id": 1838481, "author_profile": "https://Stackoverflow.com/users/1838481", "pm_score": 3, "selected": false, "text": "<p>We can do it in two different ways</p>\n<p><strong>Remove Windows Service via Registry</strong></p>\n<p>Its very easy to remove a service from registry if you know the right path. Here is how I did that:</p>\n<ol>\n<li><p>Run <strong>Regedit</strong> or <strong>Regedt32</strong></p>\n</li>\n<li><p>Go to the registry entry &quot;HKEY_LOCAL_MACHINE/SYSTEM/CurrentControlSet/Services&quot;</p>\n</li>\n<li><p>Look for the service that you want delete and delete it. You can look at the keys to know what files the service was using and delete them as well (if necessary).</p>\n</li>\n</ol>\n<p><strong>Delete Windows Service via Command Window</strong></p>\n<p>Alternatively, you can also use command prompt and delete a service using following command:</p>\n<p><strong>sc delete</strong> </p>\n<p>You can also create service by using following command</p>\n<p>sc create &quot;MorganTechService&quot; binpath= &quot;C:\\Program Files\\MorganTechSPace\\myservice.exe&quot;</p>\n<p>Note: You may have to reboot the system to get the list updated in service manager.</p>\n" }, { "answer_id": 33136790, "author": "Demodave", "author_id": 953496, "author_profile": "https://Stackoverflow.com/users/953496", "pm_score": 0, "selected": false, "text": "<p>For me my service that I created had to be uninstalled in Control Panel > Programs and Features</p>\n" }, { "answer_id": 36133683, "author": "Dilmasegure", "author_id": 6094055, "author_profile": "https://Stackoverflow.com/users/6094055", "pm_score": 1, "selected": false, "text": "<p>Before removing the service you should review the dependencies.</p>\n\n<p>You can check it:</p>\n\n<p>Open <code>services.msc</code> and find the service name, switch to the \"Dependencies\" tab.</p>\n\n<p>Source: <a href=\"http://www.sysadmit.com/2016/03/windows-eliminar-un-servicio.html\" rel=\"nofollow\">http://www.sysadmit.com/2016/03/windows-eliminar-un-servicio.html</a></p>\n" }, { "answer_id": 49165398, "author": "Nic", "author_id": 2450507, "author_profile": "https://Stackoverflow.com/users/2450507", "pm_score": 5, "selected": false, "text": "<p>As described above I executed:</p>\n\n<pre><code>sc delete ServiceName\n</code></pre>\n\n<p>However this didn't work as I was executing it from PowerShell.</p>\n\n<p>When using PowerShell you must specify the full path to <code>sc.exe</code> because PowerShell has a default alias for <code>sc</code> assigning it to <code>Set-Content</code>. Since it's a valid command it doesn't actually show an error message.</p>\n\n<p>To resolve this I executed it as follows:</p>\n\n<pre><code>C:\\Windows\\System32\\sc.exe delete ServiceName\n</code></pre>\n" }, { "answer_id": 60429951, "author": "Sergey Vaulin", "author_id": 3556088, "author_profile": "https://Stackoverflow.com/users/3556088", "pm_score": 1, "selected": false, "text": "<p>You can use my small service list editor utility <strong>Service Manager</strong></p>\n\n<p><a href=\"https://i.stack.imgur.com/Kw4Lc.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Kw4Lc.png\" alt=\"Preview\"></a></p>\n\n<p>You can choose any service > Modify > Delete. Method works immediately, no reboot required.</p>\n\n<p>Executable file: <a href=\"https://drive.google.com/drive/folders/1NXu810HDv3KYe3LcT8q2gZxQ9zLwuI_n\" rel=\"nofollow noreferrer\">[Download]</a></p>\n\n<p>Source code: <a href=\"https://github.com/devowl/winservicemanager\" rel=\"nofollow noreferrer\">[Download]</a></p>\n\n<p>Blog post: <a href=\"http://www.devowl.net/2019/08/windows-service-create-edit-delete-servicesmsc.html\" rel=\"nofollow noreferrer\">[BlogLink]</a></p>\n\n<p>Service editor class: <a href=\"https://github.com/devowl/winservicemanager/blob/master/WS.Manager/WinService/WinServiceUtils.cs\" rel=\"nofollow noreferrer\">WinServiceUtils.cs</a></p>\n" }, { "answer_id": 68771818, "author": "4F2E4A2E", "author_id": 543426, "author_profile": "https://Stackoverflow.com/users/543426", "pm_score": 2, "selected": false, "text": "<p>This did the job for me on Windows 10:</p>\n<ul>\n<li>start the cmd.exe as admin</li>\n<li>run SC DELETE &quot;com.docker.service&quot;</li>\n<li>reinstall docker</li>\n</ul>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/76074", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1204/" ]
I have a couple old services that I want to completely uninstall. How can I do this?
Use the *SC* command, like this (you need to be on a command prompt to execute the commands in this post): ``` SC STOP shortservicename SC DELETE shortservicename ``` --- **Note:** You need to run the command prompt as an administrator, not just logged in as the administrator, but also with administrative rights. If you get errors above about not having the necessary access rights to stop and/or delete the service, run the command prompt as an administrator. You can do this by searching for the command prompt on your start menu and then right-clicking and selecting "Run as administrator". **Note to PowerShell users:** `sc` is aliased to `set-content`. So `sc delete service` will actually create a file called `delete` with the content `service`. To do this in Powershell, use `sc.exe delete service` instead --- If you need to find the short service name of a service, use the following command to generate a text file containing a list of services and their statuses: ``` SC QUERY state= all >"C:\Service List.txt" ``` For a more concise list, execute this command: ``` SC QUERY state= all | FIND "_NAME" ``` The short service name will be listed just above the display name, like this: ``` SERVICE_NAME: MyService DISPLAY_NAME: My Special Service ``` And thus to delete that service: ``` SC STOP MyService SC DELETE MyService ```
76,076
<p>I am trying to solve numerically a set of partial differential equations in three dimensions. In each of the equations the next value of the unknown in a point depends on the current value of each unknown in the closest points.</p> <p>To write an efficient code I need to keep the points close in the three dimensions close in the (one-dimensional) memory space, so that each value is called from memory just once.</p> <p>I was thinking of using octtrees, but I was wondering if someone knows a better method.</p>
[ { "answer_id": 76185, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 4, "selected": true, "text": "<p>Octtrees are the way to go. You subdivide the array into 8 octants:</p>\n\n<pre>\n1 2\n3 4\n\n---\n\n5 6\n7 8\n</pre>\n\n<p>And then lay them out in memory in the order 1, 2, 3, 4, 5, 6, 7, 8 as above. You repeat this recursively within each octant until you get down to some base size, probably around 128 bytes or so (this is just a guess -- make sure to profile to determine the optimal cutoff point). This has much, much better cache coherency and locality of reference than the naive layout.</p>\n" }, { "answer_id": 76767, "author": "palm3D", "author_id": 2686, "author_profile": "https://Stackoverflow.com/users/2686", "pm_score": 2, "selected": false, "text": "<p>The book <a href=\"https://rads.stackoverflow.com/amzn/click/com/0123694469\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Foundations of Multidimensional and Metric Data Structures</a> can help you decide which data structure is fastest for range queries: octrees, kd-trees, R-trees, ...\nIt also describes data layouts for keeping points together in memory.</p>\n" }, { "answer_id": 83362, "author": "Nils Pipenbrinck", "author_id": 15955, "author_profile": "https://Stackoverflow.com/users/15955", "pm_score": 3, "selected": false, "text": "<p>One alternative to the tree-method: Use the Morton-Order to encode your data.</p>\n\n<p>In three dimension it goes like this: Take the coordinate components and interleave each bit two zero bits. Here shown in binary: 11111b becomes 1001001001b</p>\n\n<p>A C-function to do this looks like this (shown for clarity and only for 11 bits):</p>\n\n<pre><code>int morton3 (int a)\n{\n int result = 0;\n int i;\n for (i=0; i&lt;11; i++)\n {\n // check if the i'th bit is set.\n int bit = a&amp;(1&lt;&lt;i);\n if (bit)\n {\n // if so set the 3*i'th bit in the result:\n result |= 1&lt;&lt;(i*3);\n }\n }\n return result;\n}\n</code></pre>\n\n<p>You can use this function to combine your positions like this:</p>\n\n<pre><code>index = morton3 (position.x) + \n morton3 (position.y)*2 +\n morton3 (position.z)*4;\n</code></pre>\n\n<p>This turns your three dimensional index into a one dimensional one. Best part of it: Values that are close in 3D space are close in 1D space as well. If you access values close to each other frequently you will also get a very nice speed-up because the morton-order encoding is optimal in terms of cache locality.</p>\n\n<p>For morton3 you better not use the code above. Use a small table to look up 4 or 8 bits at a time and combine them together. </p>\n\n<p>Hope it helps,\n Nils</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/76076", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13405/" ]
I am trying to solve numerically a set of partial differential equations in three dimensions. In each of the equations the next value of the unknown in a point depends on the current value of each unknown in the closest points. To write an efficient code I need to keep the points close in the three dimensions close in the (one-dimensional) memory space, so that each value is called from memory just once. I was thinking of using octtrees, but I was wondering if someone knows a better method.
Octtrees are the way to go. You subdivide the array into 8 octants: ``` 1 2 3 4 --- 5 6 7 8 ``` And then lay them out in memory in the order 1, 2, 3, 4, 5, 6, 7, 8 as above. You repeat this recursively within each octant until you get down to some base size, probably around 128 bytes or so (this is just a guess -- make sure to profile to determine the optimal cutoff point). This has much, much better cache coherency and locality of reference than the naive layout.
76,079
<p>can anyone please suggest a <strong>good code example</strong> of vb.net/c# code to put the application in system tray when minized.</p>
[ { "answer_id": 76120, "author": "Phillip Wells", "author_id": 3012, "author_profile": "https://Stackoverflow.com/users/3012", "pm_score": 5, "selected": true, "text": "<p>Add a NotifyIcon control to your form, then use the following code:</p>\n\n<pre><code> private void frm_main_Resize(object sender, EventArgs e)\n {\n if (this.WindowState == FormWindowState.Minimized)\n {\n this.ShowInTaskbar = false;\n this.Hide();\n notifyIcon1.Visible = true;\n }\n }\n\n private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)\n {\n this.Show();\n this.WindowState = FormWindowState.Normal;\n this.ShowInTaskbar = true;\n notifyIcon1.Visible = false;\n }\n</code></pre>\n\n<p>You may not need to set the ShowInTaskbar property.</p>\n" }, { "answer_id": 76160, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 2, "selected": false, "text": "<p>You can leverage a built in control called NotifyIcon. This creates a tray icon when shown. @Phillip has a code example that is somewhat complete.</p>\n\n<p>There is a gotcha though:</p>\n\n<p>You must override your applications main form Dispose method to call Dispose on NotifyIcon, otherwise it will stay in your tray after application exits.</p>\n\n<pre><code>public void Form_Dispose(object sender, EventArgs e)\n{\n if (this.Disposing)\n notifyIcon1.Dispose();\n}\n</code></pre>\n\n<p>Something like that.</p>\n" }, { "answer_id": 76708, "author": "Sean Gough", "author_id": 12842, "author_profile": "https://Stackoverflow.com/users/12842", "pm_score": 0, "selected": false, "text": "<p>You can do this by adding a NotifyIcon to your form and handling the form's resize event. To get back from the tray handle the NotifyIcon's double-click event.</p>\n\n<p>If you want to add a little animation you can do this too...</p>\n\n<p>1) Add the following module:</p>\n\n<pre><code>Module AnimatedMinimizeToTray\nStructure RECT\n Public left As Integer\n Public top As Integer\n Public right As Integer\n Public bottom As Integer\nEnd Structure\n\nStructure APPBARDATA\n Public cbSize As Integer\n Public hWnd As IntPtr\n Public uCallbackMessage As Integer\n Public uEdge As ABEdge\n Public rc As RECT\n Public lParam As IntPtr\nEnd Structure\n\nEnum ABMsg\n ABM_NEW = 0\n ABM_REMOVE = 1\n ABM_QUERYPOS = 2\n ABM_SETPOS = 3\n ABM_GETSTATE = 4\n ABM_GETTASKBARPOS = 5\n ABM_ACTIVATE = 6\n ABM_GETAUTOHIDEBAR = 7\n ABM_SETAUTOHIDEBAR = 8\n ABM_WINDOWPOSCHANGED = 9\n ABM_SETSTATE = 10\nEnd Enum\n\nEnum ABNotify\n ABN_STATECHANGE = 0\n ABN_POSCHANGED\n ABN_FULLSCREENAPP\n ABN_WINDOWARRANGE\nEnd Enum\n\nEnum ABEdge\n ABE_LEFT = 0\n ABE_TOP\n ABE_RIGHT\n ABE_BOTTOM\nEnd Enum\n\nPublic Declare Function SHAppBarMessage Lib \"shell32.dll\" Alias \"SHAppBarMessage\" (ByVal dwMessage As Integer, ByRef pData As APPBARDATA) As Integer\nPublic Const ABM_GETTASKBARPOS As Integer = &amp;H5&amp;\nPublic Const WM_SYSCOMMAND As Integer = &amp;H112\nPublic Const SC_MINIMIZE As Integer = &amp;HF020\n\nPublic Sub AnimateWindow(ByVal ToTray As Boolean, ByRef frm As Form, ByRef icon As NotifyIcon)\n ' get the screen dimensions\n Dim screenRect As Rectangle = Screen.GetBounds(frm.Location)\n\n ' figure out where the taskbar is (and consequently the tray)\n Dim destPoint As Point\n Dim BarData As APPBARDATA\n BarData.cbSize = System.Runtime.InteropServices.Marshal.SizeOf(BarData)\n SHAppBarMessage(ABMsg.ABM_GETTASKBARPOS, BarData)\n Select Case BarData.uEdge\n Case ABEdge.ABE_BOTTOM, ABEdge.ABE_RIGHT\n ' Tray is to the Bottom Right\n destPoint = New Point(screenRect.Width, screenRect.Height)\n\n Case ABEdge.ABE_LEFT\n ' Tray is to the Bottom Left\n destPoint = New Point(0, screenRect.Height)\n\n Case ABEdge.ABE_TOP\n ' Tray is to the Top Right\n destPoint = New Point(screenRect.Width, 0)\n\n End Select\n\n ' setup our loop based on the direction\n Dim a, b, s As Single\n If ToTray Then\n a = 0\n b = 1\n s = 0.05\n Else\n a = 1\n b = 0\n s = -0.05\n End If\n\n ' \"animate\" the window\n Dim curPoint As Point, curSize As Size\n Dim startPoint As Point = frm.Location\n Dim dWidth As Integer = destPoint.X - startPoint.X\n Dim dHeight As Integer = destPoint.Y - startPoint.Y\n Dim startWidth As Integer = frm.Width\n Dim startHeight As Integer = frm.Height\n Dim i As Single\n For i = a To b Step s\n curPoint = New Point(startPoint.X + i * dWidth, startPoint.Y + i * dHeight)\n curSize = New Size((1 - i) * startWidth, (1 - i) * startHeight)\n ControlPaint.DrawReversibleFrame(New Rectangle(curPoint, curSize), frm.BackColor, FrameStyle.Thick)\n System.Threading.Thread.Sleep(15)\n ControlPaint.DrawReversibleFrame(New Rectangle(curPoint, curSize), frm.BackColor, FrameStyle.Thick)\n Next\n\n\n If ToTray Then\n ' hide the form and show the notifyicon\n frm.Hide()\n icon.Visible = True\n Else\n ' hide the notifyicon and show the form\n icon.Visible = False\n frm.Show()\n End If\n\nEnd Sub\nEnd Module\n</code></pre>\n\n<p>2) Add a NotifyIcon to your form an add the following:</p>\n\n<pre><code>Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)\n If m.Msg = WM_SYSCOMMAND AndAlso m.WParam.ToInt32() = SC_MINIMIZE Then\n AnimateWindow(True, Me, NotifyIcon1)\n Exit Sub\n End If\n MyBase.WndProc(m)\nEnd Sub\n\nPrivate Sub NotifyIcon1_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles NotifyIcon1.DoubleClick\n AnimateWindow(False, Me, NotifyIcon1)\nEnd Sub\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/76079", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13337/" ]
can anyone please suggest a **good code example** of vb.net/c# code to put the application in system tray when minized.
Add a NotifyIcon control to your form, then use the following code: ``` private void frm_main_Resize(object sender, EventArgs e) { if (this.WindowState == FormWindowState.Minimized) { this.ShowInTaskbar = false; this.Hide(); notifyIcon1.Visible = true; } } private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e) { this.Show(); this.WindowState = FormWindowState.Normal; this.ShowInTaskbar = true; notifyIcon1.Visible = false; } ``` You may not need to set the ShowInTaskbar property.
76,080
<p>We need to reliably get the Quick Launch folder for both All and Current users under both Vista and XP. I'm developing in C++, but this is probably more of a general Windows API question.</p> <p>For reference, here is code to get the Application Data folder under both systems:</p> <pre><code> HRESULT hres; CString basePath; hres = SHGetSpecialFolderPath(this-&gt;GetSafeHwnd(), basePath.GetBuffer(MAX_PATH), CSIDL_APPDATA, FALSE); basePath.ReleaseBuffer(); </code></pre> <p>I suspect this is just a matter of knowing which sub-folder Microsoft uses.</p> <p>Under Windows XP, the app data subfolder is:</p> <p>Microsoft\Internet Explorer\Quick Launch</p> <p>Under Vista, it appears that the sub-folder has been changed to:</p> <p>Roaming\Microsoft\Internet Explorer\Quick Launch</p> <p>but I'd like to make sure that this is the correct way to determine the correct location.</p> <p>Finding the <em>correct</em> way to determine this location is quite important, as relying on hard coded folder names almost always breaks as you move into international installs, etc... The fact that the folder is named 'Roaming' in Vista makes me wonder if there is some special handling related to that folder (akin to the Local Settings folder under XP).</p> <p>EDIT: The following msdn article: <a href="http://msdn.microsoft.com/en-us/library/bb762494.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/bb762494.aspx</a> indicates that CSIDL_APPDATA has an equivalent ID of FOLDERID_RoamingAppData, which does seem to support StocksR's assertion that CSIDL_APPDATA does return C:\Users\xxxx\AppData\Roaming, so it should be possible to use the same relative path for CSIDL_APPDATA to get to quick launch (\Microsoft\Internet Explorer\Quick Launch).</p> <p>So the following algorithm is correct per MS:</p> <pre><code>HRESULT hres; CString basePath; hres = SHGetSpecialFolderPath(this-&gt;GetSafeHwnd(), basePath.GetBuffer(MAX_PATH), CSIDL_APPDATA, FALSE); basePath.ReleaseBuffer(); CString qlPath = basePath + "\\Microsoft\\Internet Explorer\\Quick Launch"; </code></pre> <p>it would also be a good idea to check hres to ensure that the call to SHGetSpecialFolderPath was successful.</p>
[ { "answer_id": 76246, "author": "StocksR", "author_id": 6892, "author_profile": "https://Stackoverflow.com/users/6892", "pm_score": 3, "selected": true, "text": "<p>AppData on vista refers to C:\\Users\\xxxx\\AppData\\Roaming not the C:\\Users\\xxxx\\AppData folder it's self.</p>\n\n<p>Also this artical <a href=\"http://www.microsoft.com/technet/scriptcenter/resources/qanda/sept05/hey0901.mspx\" rel=\"nofollow noreferrer\">http://www.microsoft.com/technet/scriptcenter/resources/qanda/sept05/hey0901.mspx</a> on a microsoft site implies that you simply have to use the path relative to the appdata folder </p>\n" }, { "answer_id": 76323, "author": "Judah Gabriel Himango", "author_id": 536, "author_profile": "https://Stackoverflow.com/users/536", "pm_score": 1, "selected": false, "text": "<p>Great question! </p>\n\n<p>Whatever you do, <strong>don't</strong> give into the temptation to <a href=\"http://blogs.msdn.com/oldnewthing/archive/2003/11/03/55532.aspx\" rel=\"nofollow noreferrer\">dig into the registry</a> to find this info!</p>\n\n<p>Also, we must resist the temptation to hard code some path, even partially. If we get the special AppData path, then simply append a string onto the end, this may break under non-US installs of the software where the folder name is localized to that language. E.g. <code>GetSpecialFolderPath(APP_DATA) + \"\\\\Fonts\"</code> will not work on non-English versions of Windows.</p>\n\n<p>Hopefully someone has the proper answer to your question; I'm curious to know it myself!</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/76080", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10973/" ]
We need to reliably get the Quick Launch folder for both All and Current users under both Vista and XP. I'm developing in C++, but this is probably more of a general Windows API question. For reference, here is code to get the Application Data folder under both systems: ``` HRESULT hres; CString basePath; hres = SHGetSpecialFolderPath(this->GetSafeHwnd(), basePath.GetBuffer(MAX_PATH), CSIDL_APPDATA, FALSE); basePath.ReleaseBuffer(); ``` I suspect this is just a matter of knowing which sub-folder Microsoft uses. Under Windows XP, the app data subfolder is: Microsoft\Internet Explorer\Quick Launch Under Vista, it appears that the sub-folder has been changed to: Roaming\Microsoft\Internet Explorer\Quick Launch but I'd like to make sure that this is the correct way to determine the correct location. Finding the *correct* way to determine this location is quite important, as relying on hard coded folder names almost always breaks as you move into international installs, etc... The fact that the folder is named 'Roaming' in Vista makes me wonder if there is some special handling related to that folder (akin to the Local Settings folder under XP). EDIT: The following msdn article: <http://msdn.microsoft.com/en-us/library/bb762494.aspx> indicates that CSIDL\_APPDATA has an equivalent ID of FOLDERID\_RoamingAppData, which does seem to support StocksR's assertion that CSIDL\_APPDATA does return C:\Users\xxxx\AppData\Roaming, so it should be possible to use the same relative path for CSIDL\_APPDATA to get to quick launch (\Microsoft\Internet Explorer\Quick Launch). So the following algorithm is correct per MS: ``` HRESULT hres; CString basePath; hres = SHGetSpecialFolderPath(this->GetSafeHwnd(), basePath.GetBuffer(MAX_PATH), CSIDL_APPDATA, FALSE); basePath.ReleaseBuffer(); CString qlPath = basePath + "\\Microsoft\\Internet Explorer\\Quick Launch"; ``` it would also be a good idea to check hres to ensure that the call to SHGetSpecialFolderPath was successful.
AppData on vista refers to C:\Users\xxxx\AppData\Roaming not the C:\Users\xxxx\AppData folder it's self. Also this artical <http://www.microsoft.com/technet/scriptcenter/resources/qanda/sept05/hey0901.mspx> on a microsoft site implies that you simply have to use the path relative to the appdata folder
76,134
<p>I have 4 2D points in screen-space, and I need to reverse-project them back into 3D space. I know that each of the 4 points is a corner of a 3D-rotated rigid rectangle, and I know the size of the rectangle. How can I get 3D coordinates from this?</p> <p>I am not using any particular API, and I do not have an existing projection matrix. I'm just looking for basic math to do this. Of course there isn't enough data to convert a single 2D point to 3D with no other reference, but I imagine that if you have 4 points, you know that they're all at right-angles to each other on the same plane, and you know the distance between them, you should be able to figure it out from there. Unfortunately I can't quite work out how though.</p> <p>This might fall under the umbrella of photogrammetry, but google searches for that haven't led me to any helpful information. </p>
[ { "answer_id": 76282, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 2, "selected": false, "text": "<p>Assuming that the points are indeed part of a rectangle, I'm giving a generic idea :</p>\n\n<p>Find two points with max inter-distance: these most probably define a diagonal (exception: special cases where the rectangle is almost paralell to the YZ plane, left for the student). Call them A, C. Calculate the BAD, BCD angles. These, compared to right angles, give you orientation in 3d space. To find out about z distance, you need to correlate the projected sides to the known sides, and then, based on the 3d projection method (is it 1/z?) you're on the right track to know distances.</p>\n" }, { "answer_id": 76289, "author": "nlucaroni", "author_id": 157, "author_profile": "https://Stackoverflow.com/users/157", "pm_score": 1, "selected": false, "text": "<p>I'll get my linear Algebra book out when I get home if nobody answered. But @ D G, not all matrices are invertible. <a href=\"http://mathworld.wolfram.com/SingularMatrix.html\" rel=\"nofollow noreferrer\">Singular matrices aren't invertible</a> (when determinant = 0). This will actually happen all the time, since a projection matrix <em>must</em> have eigenvalues of 0 and 1, and be square (since it is idempotent, so p^2 = p).</p>\n\n<p>An easy example is, [[0 1][0 1]] since the determinant = 0, and that is a projection on the line x = y!</p>\n" }, { "answer_id": 76305, "author": "Rob Dickerson", "author_id": 7530, "author_profile": "https://Stackoverflow.com/users/7530", "pm_score": 1, "selected": false, "text": "<p>The projection you have onto the 2D surface has infinitely many 3D rectangles that will project to the same 2D shape.</p>\n\n<p>Think about it this way: you have four 3D points that make up the 3D rectangle. Call them (x0,y0,z0), (x1,y1,z1), (x2,y2,z2) and (x3,y3,z3). When you project these points onto the x-y plane, you drop the z coordinates: (x0,y0), (x1,y1), (x2,y2), (x3,y3).</p>\n\n<p>Now, you want to project back into 3D space, you need to reverse-engineer what z0,..,z3 were. But any set of z coordinates that a) keep the same x-y distance between the points, and b) keep the shape a rectangle will work. So, any member of this (infinite) set will do: {(z0+i, z1+i, z2+i, z3+i) | i &lt;- R}.</p>\n\n<p>Edit @Jarrett: Imagine you solved this and ended up with a rectangle in 3D space. Now, imagine sliding that rectangle up and down the z-axis. Those infinite amount of translated rectangles all have the same x-y projection. How do you know you found the \"right\" one?</p>\n\n<p>Edit #2: Alright, this is from a comment I made on this question -- a more intuitive approach to reasoning about this.</p>\n\n<p>Imagine holding a piece of paper above your desk. Pretend each corner of the paper has a weightless laser pointer attached to it that points down toward the desk. The paper is the 3D object, and the laser pointer dots on the desk are the 2D projection.</p>\n\n<p>Now, how can you tell how high off the desk the paper is by looking at <em>just</em> the laser pointer dots?</p>\n\n<p>You can't. Move the paper straight up and down. The laser pointers will still shine on the same spots on the desk regardless of the height of the paper.</p>\n\n<p>Finding the z-coordinates in the reverse-projection is like trying to find the height of the paper based on the laser pointer dots on the desk alone.</p>\n" }, { "answer_id": 76306, "author": "Jarrett Meyer", "author_id": 5834, "author_profile": "https://Stackoverflow.com/users/5834", "pm_score": 2, "selected": false, "text": "<p>From the 2-D space there will be 2 valid rectangles that can be built. Without knowing the original matrix projection, you won't know which one is correct. It's the same as the \"box\" problem: you see two squares, one inside the other, with the 4 inside vertices connected to the 4 respective outside vertices. Are you looking at a box from the top-down or the bottom-up?</p>\n\n<p>That being said, you are looking for a matrix transform T where...</p>\n\n<p>{{x1, y1, z1}, {x2, y2, z2}, {x3, y3, z3}, {x4, y4, z4}} x T = {{x1, y1}, {x2, y2}, {x3, y3}, {x4, y4}}</p>\n\n<p>(4 x 3) x T = (4 x 2)</p>\n\n<p>So T must be a (3 x 2) matrix. So we've got 6 unknowns.</p>\n\n<p>Now build a system of constraints on T and solve with Simplex. To build the constraints, you know that a line passing through the first two points must be parallel to the line passing to the second two points. You know a line passing through points 1 and 3 must be parallel to the lines passing through points 2 and 4. You know a line passing through 1 and 2 must be orthogonal to a line passing through points 2 and 3. You know that the length of the line from 1 and 2 must equal the length of the line from 3 and 4. You know that the length of the line from 1 and 3 must equal the length of the line from 2 and 4.</p>\n\n<p>To make this even easier, you know about the rectangle, so you know the length of all the sides.</p>\n\n<p>That should give you plenty of constraints to solve this problem.</p>\n\n<p>Of course, to get back, you can find T-inverse.</p>\n\n<p>@Rob: Yes, there are an infinite number of projections, but not an infinite number of projects where the points must satisfy the requirements of a rectangle.</p>\n\n<p>@nlucaroni: Yes, this is only solvable if you have four points in the projection. If the rectangle projects to just 2 points (i.e. the plane of the rectangle is orthogonal to the projection surface), then this cannot be solved.</p>\n\n<p>Hmmm... I should go home and write this little gem. This sounds like fun.</p>\n\n<p>Updates:</p>\n\n<ol>\n<li>There are an infinite number of projections unless you fix one of the points. If you fix on of the points of the original rectangle, then there are two possible original rectangles.</li>\n</ol>\n" }, { "answer_id": 77003, "author": "morechilli", "author_id": 5427, "author_profile": "https://Stackoverflow.com/users/5427", "pm_score": 1, "selected": false, "text": "<p>When you project from 3D to 2D you lose information.</p>\n\n<p>In the simple case of a single point the inverse projection would give you an infinite ray through 3d space.</p>\n\n<p>Stereoscopic reconstruction will typically start with two 2d images and project both back to 3D. Then look for an intersection of the two 3D rays produced.</p>\n\n<p>Projection can take different forms. Orthogonal or perspective. I'm guessing that you are assuming orthogonal projection?</p>\n\n<p>In your case assuming you had the original matrix you would have 4 rays in 3D space. You would then be able to constrain the problem by your 3d rectangle dimensions and attempt to solve. </p>\n\n<p>The solution will not be unique as a rotation around either axis that is parallel to the 2d projection plane will be ambiguous in direction. In other words if the 2d image is perpendicular to the z axis then rotating the 3d rectangle clockwise or anti clockwise around the x axis would produce the same image. Likewise for the y axis.</p>\n\n<p>In the case where the rectangle plane is parallel to the z axis you have even more solutions.</p>\n\n<p>As you don't have the original projection matrix further ambiguity is introduced by an arbitary scaling factor that exists in any projection. You cannot distinguish between a scaling in the projection and a translation in 3d in the direction of the z axis. This is not a problem if you are only interested in the relative positions of the 4 points in 3d space when related to each other and not to the plane of the 2d projection.</p>\n\n<p>In a perspective projection things get harder...</p>\n" }, { "answer_id": 77188, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>If you know the shape is a rectangle in a plane, you can greatly further constrain the problem. You certainly cannot figure out \"which\" plane, so you can choose that it is lying on the plane where z=0 and one of the corners is at x=y=0, and the edges are parallel to the x/y axis.</p>\n\n<p>The points in 3d are therefore {0,0,0},{w,0,0},{w,h,0},and {0,h,0}. I'm pretty certain the absolute size will not be found, so only the ratio w/h is releavant, so this is one unknown.</p>\n\n<p>Relative to this plane the camera must be at some point cx,cy,cz in space, must be pointing in a direction nx,ny,nz (a vector of length one so one of these is redundant), and have a focal_length/image_width factor of w. These numbers turn into a 3x3 projection matrix.</p>\n\n<p>That gives a total of 7 unknowns: w/h, cx, cy, cz, nx, ny, and w.</p>\n\n<p>You have a total of 8 knowns: the 4 x+y pairs.</p>\n\n<p>So this can be solved.</p>\n\n<p>Next step is to use Matlab or Mathmatica.</p>\n" }, { "answer_id": 78057, "author": "user14208", "author_id": 14208, "author_profile": "https://Stackoverflow.com/users/14208", "pm_score": 3, "selected": false, "text": "<p>For my OpenGL engine, the following snip will convert mouse/screen coordinates into 3D world coordinates. Read the commments for an actual description of what is going on.</p>\n<pre>\n/* FUNCTION: YCamera :: CalculateWorldCoordinates\n ARGUMENTS: x mouse x coordinate\n y mouse y coordinate\n vec where to store coordinates\n RETURN: n/a\n DESCRIPTION: Convert mouse coordinates into world coordinates\n*/\n</pre>\n<pre><code>void YCamera :: CalculateWorldCoordinates(float x, float y, YVector3 *vec)\n{\n // START\n GLint viewport[4];\n GLdouble mvmatrix[16], projmatrix[16];\n \n GLint real_y;\n GLdouble mx, my, mz;\n\n glGetIntegerv(GL_VIEWPORT, viewport);\n glGetDoublev(GL_MODELVIEW_MATRIX, mvmatrix);\n glGetDoublev(GL_PROJECTION_MATRIX, projmatrix);\n\n real_y = viewport[3] - (GLint) y - 1; // viewport[3] is height of window in pixels\n gluUnProject((GLdouble) x, (GLdouble) real_y, 1.0, mvmatrix, projmatrix, viewport, &amp;mx, &amp;my, &amp;mz);\n\n /* 'mouse' is the point where mouse projection reaches FAR_PLANE.\n World coordinates is intersection of line(camera-&gt;mouse) with plane(z=0) (see LaMothe 306)\n \n Equation of line in 3D:\n (x-x0)/a = (y-y0)/b = (z-z0)/c \n\n Intersection of line with plane:\n z = 0\n x-x0 = a(z-z0)/c &lt;=&gt; x = x0+a(0-z0)/c &lt;=&gt; x = x0 -a*z0/c\n y = y0 - b*z0/c\n \n */\n double lx = fPosition.x - mx;\n double ly = fPosition.y - my;\n double lz = fPosition.z - mz;\n double sum = lx*lx + ly*ly + lz*lz;\n double normal = sqrt(sum);\n double z0_c = fPosition.z / (lz/normal);\n \n vec-&gt;x = (float) (fPosition.x - (lx/normal)*z0_c);\n vec-&gt;y = (float) (fPosition.y - (ly/normal)*z0_c);\n vec-&gt;z = 0.0f;\n}\n</code></pre>\n" }, { "answer_id": 93779, "author": "Nils Pipenbrinck", "author_id": 15955, "author_profile": "https://Stackoverflow.com/users/15955", "pm_score": 2, "selected": false, "text": "<p>To follow up on Rons approach: You can find your z-values if you know how you've rotated your rectangle.</p>\n\n<p>The trick is to find the projective matrix that did the projection. Fortunately this is possible and even cheap to do. The relevant math can be found in the paper \"Projective Mappings for Image Warping\" by Paul Heckbert. </p>\n\n<p><a href=\"http://pages.cs.wisc.edu/~dyer/cs766/readings/heckbert-proj.pdf\" rel=\"nofollow noreferrer\">http://pages.cs.wisc.edu/~dyer/cs766/readings/heckbert-proj.pdf</a></p>\n\n<p>This way you can recover the homogenous part of each vertex back that was lost during projection. </p>\n\n<p>Now you're still left with four lines instead of points (as Ron explained). Since you know the size of your original rectangle however nothing is lost. You can now plug the data from Ron's method and from the 2D approach into a linear equation solver and solve for z. You get the exact z-values of each vertex that way. </p>\n\n<p>Note: This just works because: </p>\n\n<ol>\n<li>The original shape was a rectangle</li>\n<li>You know the exact size of the rectangle in 3D space.</li>\n</ol>\n\n<p>It's a special case really.</p>\n\n<p>Hope it helps,\n Nils</p>\n" }, { "answer_id": 3554754, "author": "Julien-L", "author_id": 143504, "author_profile": "https://Stackoverflow.com/users/143504", "pm_score": 3, "selected": false, "text": "<p><em>D. DeMenthon</em> devised an algorithm to compute the <em>pose</em> of an object (its position and orientation in space) from feature points in a 2D image when knowing the model of the object -- <strong>this is your exact problem</strong>:</p>\n\n<blockquote>\n <p>We describe a method for finding the pose of an object from a single image. We assume that we can detect and match in the image four or more noncoplanar feature points of the object, and that we know their relative geometry on the object.</p>\n</blockquote>\n\n<p>The algorithm is known as <strong>Posit</strong> and is described in it classical article \"Model-Based Object Pose in 25 Lines of Code\" (available on <a href=\"http://www.cfar.umd.edu/~daniel/Site_2/Research.html\" rel=\"noreferrer\">its website</a>, section 4).</p>\n\n<p>Direct link to the article: <a href=\"http://www.cfar.umd.edu/~daniel/daniel_papersfordownload/Pose25Lines.pdf\" rel=\"noreferrer\">http://www.cfar.umd.edu/~daniel/daniel_papersfordownload/Pose25Lines.pdf</a>\nOpenCV implementation: <a href=\"http://opencv.willowgarage.com/wiki/Posit\" rel=\"noreferrer\">http://opencv.willowgarage.com/wiki/Posit</a></p>\n\n<p>The idea is to repeatedly approximating the perspective projection by a <em>scaled orthographic projection</em> until converging to an accurate pose.</p>\n" }, { "answer_id": 13937210, "author": "dim_tz", "author_id": 1435500, "author_profile": "https://Stackoverflow.com/users/1435500", "pm_score": 3, "selected": false, "text": "<p>This is the Classic problem for marker based Augmented Reality.</p>\n\n<p>You have a square marker (2D Barcode), and you want to find its Pose (translation &amp; rotation in relation to the camera), after finding the four edges of the marker.\n<a href=\"http://www.brightsideofnews.com/Data/2009_10_26/Zombies-nVidia-Tegra-Augmented-Reality/Zombies_AR_Marker_675.jpg\" rel=\"noreferrer\">Overview-Picture</a></p>\n\n<p>I'm not aware of the latest contributions to the field, but at least up to a point (2009) RPP was supposed to outperform POSIT that is mentioned above (and is indeed a classic approach for this)\nPlease see the links, they also provide source.</p>\n\n<ul>\n<li><p><a href=\"http://www.emt.tugraz.at/~vmg/schweighofer\" rel=\"noreferrer\">http://www.emt.tugraz.at/~vmg/schweighofer</a></p></li>\n<li><p><a href=\"http://www.emt.tugraz.at/publications/EMT_TR/TR-EMT-2005-01.pdf\" rel=\"noreferrer\">http://www.emt.tugraz.at/publications/EMT_TR/TR-EMT-2005-01.pdf</a></p></li>\n<li><p><a href=\"http://www.emt.tugraz.at/system/files/rpp_MATLAB_ref_implementation.tar.gz\" rel=\"noreferrer\">http://www.emt.tugraz.at/system/files/rpp_MATLAB_ref_implementation.tar.gz</a></p></li>\n</ul>\n\n<p>(PS - I know it's a bit old topic, but anyway, the post might be helpful to somebody)</p>\n" }, { "answer_id": 33976739, "author": "Vegard", "author_id": 1697183, "author_profile": "https://Stackoverflow.com/users/1697183", "pm_score": 7, "selected": false, "text": "<p>Alright, I came here looking for an answer and didn't find something simple and straightforward, so I went ahead and did the dumb but effective (and relatively simple) thing: Monte Carlo optimisation.</p>\n\n<p>Very simply put, the algorithm is as follows: Randomly perturb your projection matrix until it projects your known 3D coordinates to your known 2D coordinates.</p>\n\n<p>Here is a still photo from Thomas the Tank Engine:</p>\n\n<p><a href=\"https://i.stack.imgur.com/YUhsm.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/YUhsm.png\" alt=\"Thomas the Tank Engine\"></a></p>\n\n<p>Let's say we use GIMP to find the 2D coordinates of what we think is a square on the ground plane (whether or not it is really a square depends on your judgment of the depth):</p>\n\n<p><a href=\"https://i.stack.imgur.com/u8nKF.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/u8nKF.png\" alt=\"With an outline of the square\"></a></p>\n\n<p>I get four points in the 2D image: <code>(318, 247)</code>, <code>(326, 312)</code>, <code>(418, 241)</code>, and <code>(452, 303)</code>.</p>\n\n<p>By convention, we say that these points should correspond to the 3D points: <code>(0, 0, 0)</code>, <code>(0, 0, 1)</code>, <code>(1, 0, 0)</code>, and <code>(1, 0, 1)</code>. In other words, a unit square in the y=0 plane.</p>\n\n<p>Projecting each of these 3D coordinates into 2D is done by multiplying the 4D vector <code>[x, y, z, 1]</code> with a 4x4 projection matrix, then dividing the x and y components by z to actually get the perspective correction. This is more or less what <a href=\"https://www.opengl.org/sdk/docs/man2/xhtml/gluProject.xml\" rel=\"noreferrer\">gluProject()</a> does, except <code>gluProject()</code> also takes the current viewport into account and takes a separate modelview matrix into account (we can just assume the modelview matrix is the identity matrix). It is very handy to look at the <code>gluProject()</code> documentation because I actually want a solution that works for OpenGL, but beware that the documentation is missing the division by z in the formula.</p>\n\n<p>Remember, the algorithm is to start with some projection matrix and randomly perturb it until it gives the projection that we want. So what we're going to do is project each of the four 3D points and see how close we get to the 2D points we wanted. If our random perturbations cause the projected 2D points to get closer to the ones we marked above, then we keep that matrix as an improvement over our initial (or previous) guess.</p>\n\n<p>Let's define our points:</p>\n\n<pre><code># Known 2D coordinates of our rectangle\ni0 = Point2(318, 247)\ni1 = Point2(326, 312)\ni2 = Point2(418, 241)\ni3 = Point2(452, 303)\n\n# 3D coordinates corresponding to i0, i1, i2, i3\nr0 = Point3(0, 0, 0)\nr1 = Point3(0, 0, 1)\nr2 = Point3(1, 0, 0)\nr3 = Point3(1, 0, 1)\n</code></pre>\n\n<p>We need to start with some matrix, identity matrix seems a natural choice:</p>\n\n<pre><code>mat = [\n [1, 0, 0, 0],\n [0, 1, 0, 0],\n [0, 0, 1, 0],\n [0, 0, 0, 1],\n]\n</code></pre>\n\n<p>We need to actually implement the projection (which is basically a matrix multiplication):</p>\n\n<pre><code>def project(p, mat):\n x = mat[0][0] * p.x + mat[0][1] * p.y + mat[0][2] * p.z + mat[0][3] * 1\n y = mat[1][0] * p.x + mat[1][1] * p.y + mat[1][2] * p.z + mat[1][3] * 1\n w = mat[3][0] * p.x + mat[3][1] * p.y + mat[3][2] * p.z + mat[3][3] * 1\n return Point(720 * (x / w + 1) / 2., 576 - 576 * (y / w + 1) / 2.)\n</code></pre>\n\n<p>This is basically what <code>gluProject()</code> does, 720 and 576 are the width and height of the image, respectively (i.e. the viewport), and we subtract from 576 to count for the fact that we counted y coordinates from the top while OpenGL typically counts them from the bottom. You'll notice we're not calculating z, that's because we don't really need it here (though it could be handy to ensure it falls within the range that OpenGL uses for the depth buffer).</p>\n\n<p>Now we need a function for evaluating how close we are to the correct solution. The value returned by this function is what we will use to check whether one matrix is better than another. I chose to go by sum of squared distances, i.e.:</p>\n\n<pre><code># The squared distance between two points a and b\ndef norm2(a, b):\n dx = b.x - a.x\n dy = b.y - a.y\n return dx * dx + dy * dy\n\ndef evaluate(mat): \n c0 = project(r0, mat)\n c1 = project(r1, mat)\n c2 = project(r2, mat)\n c3 = project(r3, mat)\n return norm2(i0, c0) + norm2(i1, c1) + norm2(i2, c2) + norm2(i3, c3)\n</code></pre>\n\n<p>To perturb the matrix, we simply pick an element to perturb by a random amount within some range:</p>\n\n<pre><code>def perturb(amount):\n from copy import deepcopy\n from random import randrange, uniform\n mat2 = deepcopy(mat)\n mat2[randrange(4)][randrange(4)] += uniform(-amount, amount)\n</code></pre>\n\n<p>(It's worth noting that our <code>project()</code> function doesn't actually use <code>mat[2]</code> at all, since we don't compute z, and since all our y coordinates are 0 the <code>mat[*][1]</code> values are irrelevant as well. We could use this fact and never try to perturb those values, which would give a small speedup, but that is left as an exercise...)</p>\n\n<p>For convenience, let's add a function that does the bulk of the approximation by calling <code>perturb()</code> over and over again on what is the best matrix we've found so far:</p>\n\n<pre><code>def approximate(mat, amount, n=100000):\n est = evaluate(mat)\n\n for i in xrange(n):\n mat2 = perturb(mat, amount)\n est2 = evaluate(mat2)\n if est2 &lt; est:\n mat = mat2\n est = est2\n\n return mat, est\n</code></pre>\n\n<p>Now all that's left to do is to run it...:</p>\n\n<pre><code>for i in xrange(100):\n mat = approximate(mat, 1)\n mat = approximate(mat, .1)\n</code></pre>\n\n<p>I find this already gives a pretty accurate answer. After running for a while, the matrix I found was:</p>\n\n<pre><code>[\n [1.0836000765696232, 0, 0.16272110011060575, -0.44811064935115597],\n [0.09339193527789781, 1, -0.7990570384334473, 0.539087345090207 ],\n [0, 0, 1, 0 ],\n [0.06700844759602216, 0, -0.8333379578853196, 3.875290562060915 ],\n]\n</code></pre>\n\n<p>with an error of around <code>2.6e-5</code>. (Notice how the elements we said were not used in the computation have not actually been changed from our initial matrix; that's because changing these entries would not change the result of the evaluation and so the change would never get carried along.)</p>\n\n<p>We can pass the matrix into OpenGL using <code>glLoadMatrix()</code> (but remember to transpose it first, and remember to load your modelview matrix with the identity matrix):</p>\n\n<pre><code>def transpose(m):\n return [\n [m[0][0], m[1][0], m[2][0], m[3][0]],\n [m[0][1], m[1][1], m[2][1], m[3][1]],\n [m[0][2], m[1][2], m[2][2], m[3][2]],\n [m[0][3], m[1][3], m[2][3], m[3][3]],\n ]\n\nglLoadMatrixf(transpose(mat))\n</code></pre>\n\n<p>Now we can for example translate along the z axis to get different positions along the tracks:</p>\n\n<pre><code>glTranslate(0, 0, frame)\nframe = frame + 1\n\nglBegin(GL_QUADS)\nglVertex3f(0, 0, 0)\nglVertex3f(0, 0, 1)\nglVertex3f(1, 0, 1)\nglVertex3f(1, 0, 0)\nglEnd()\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/dfeEx.gif\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/dfeEx.gif\" alt=\"With 3D translation\"></a></p>\n\n<p>For sure this is not very elegant from a mathematical point of view; you don't get a closed form equation that you can just plug your numbers into and get a direct (and accurate) answer. HOWEVER, it does allow you to add additional constraints without having to worry about complicating your equations; for example if we wanted to incorporate height as well, we could use that corner of the house and say (in our evaluation function) that the distance from the ground to the roof should be so-and-so, and run the algorithm again. So yes, it's a brute force of sorts, but works, and works well.</p>\n\n<p><a href=\"https://i.stack.imgur.com/smdR8.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/smdR8.png\" alt=\"Choo choo!\"></a></p>\n" }, { "answer_id": 39877333, "author": "BBSysDyn", "author_id": 423805, "author_profile": "https://Stackoverflow.com/users/423805", "pm_score": 2, "selected": false, "text": "<p>Thanks to @Vegard for an excellent answer. I cleaned up the code a little bit:</p>\n\n<pre><code>import pandas as pd\nimport numpy as np\n\nclass Point2:\n def __init__(self,x,y):\n self.x = x\n self.y = y\n\nclass Point3:\n def __init__(self,x,y,z):\n self.x = x\n self.y = y\n self.z = z\n\n# Known 2D coordinates of our rectangle\ni0 = Point2(318, 247)\ni1 = Point2(326, 312)\ni2 = Point2(418, 241)\ni3 = Point2(452, 303)\n\n# 3D coordinates corresponding to i0, i1, i2, i3\nr0 = Point3(0, 0, 0)\nr1 = Point3(0, 0, 1)\nr2 = Point3(1, 0, 0)\nr3 = Point3(1, 0, 1)\n\nmat = [\n [1, 0, 0, 0],\n [0, 1, 0, 0],\n [0, 0, 1, 0],\n [0, 0, 0, 1],\n]\n\ndef project(p, mat):\n #print mat\n x = mat[0][0] * p.x + mat[0][1] * p.y + mat[0][2] * p.z + mat[0][3] * 1\n y = mat[1][0] * p.x + mat[1][1] * p.y + mat[1][2] * p.z + mat[1][3] * 1\n w = mat[3][0] * p.x + mat[3][1] * p.y + mat[3][2] * p.z + mat[3][3] * 1\n return Point2(720 * (x / w + 1) / 2., 576 - 576 * (y / w + 1) / 2.)\n\n# The squared distance between two points a and b\ndef norm2(a, b):\n dx = b.x - a.x\n dy = b.y - a.y\n return dx * dx + dy * dy\n\ndef evaluate(mat): \n c0 = project(r0, mat)\n c1 = project(r1, mat)\n c2 = project(r2, mat)\n c3 = project(r3, mat)\n return norm2(i0, c0) + norm2(i1, c1) + norm2(i2, c2) + norm2(i3, c3) \n\ndef perturb(mat, amount):\n from copy import deepcopy\n from random import randrange, uniform\n mat2 = deepcopy(mat)\n mat2[randrange(4)][randrange(4)] += uniform(-amount, amount)\n return mat2\n\ndef approximate(mat, amount, n=1000):\n est = evaluate(mat)\n for i in xrange(n):\n mat2 = perturb(mat, amount)\n est2 = evaluate(mat2)\n if est2 &lt; est:\n mat = mat2\n est = est2\n\n return mat, est\n\nfor i in xrange(1000):\n mat,est = approximate(mat, 1)\n print mat\n print est\n</code></pre>\n\n<p>The approximate call with .1 did not work for me, so I took it out. I ran it for a while too, and last I checked it was at </p>\n\n<pre><code>[[0.7576315397559887, 0, 0.11439449272592839, -0.314856490473439], \n[0.06440497208710227, 1, -0.5607502645413118, 0.38338196981556827], \n[0, 0, 1, 0], \n[0.05421620936883742, 0, -0.5673977598434641, 2.693116299312736]]\n</code></pre>\n\n<p>with an error around 0.02. </p>\n" }, { "answer_id": 43801764, "author": "Inflight", "author_id": 2388690, "author_profile": "https://Stackoverflow.com/users/2388690", "pm_score": 0, "selected": false, "text": "<p>Yes, Monte Carlo works, but I found better solution for this issue. This code works perfectly (and uses OpenCV):</p>\n\n<pre><code>Cv2.CalibrateCamera(new List&lt;List&lt;Point3f&gt;&gt;() { points3d }, new List&lt;List&lt;Point2f&gt;&gt;() { points2d }, new Size(height, width), cameraMatrix, distCoefs, out rvecs, out tvecs, CalibrationFlags.ZeroTangentDist | CalibrationFlags.FixK1 | CalibrationFlags.FixK2 | CalibrationFlags.FixK3);\n</code></pre>\n\n<p>This function takes known 3d and 2d points, size of screen and returns rotation (rvecs[0]), translation (tvecs[0]) and matrix of intrinsics values of camera. It's everything you need.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/76134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8409/" ]
I have 4 2D points in screen-space, and I need to reverse-project them back into 3D space. I know that each of the 4 points is a corner of a 3D-rotated rigid rectangle, and I know the size of the rectangle. How can I get 3D coordinates from this? I am not using any particular API, and I do not have an existing projection matrix. I'm just looking for basic math to do this. Of course there isn't enough data to convert a single 2D point to 3D with no other reference, but I imagine that if you have 4 points, you know that they're all at right-angles to each other on the same plane, and you know the distance between them, you should be able to figure it out from there. Unfortunately I can't quite work out how though. This might fall under the umbrella of photogrammetry, but google searches for that haven't led me to any helpful information.
Alright, I came here looking for an answer and didn't find something simple and straightforward, so I went ahead and did the dumb but effective (and relatively simple) thing: Monte Carlo optimisation. Very simply put, the algorithm is as follows: Randomly perturb your projection matrix until it projects your known 3D coordinates to your known 2D coordinates. Here is a still photo from Thomas the Tank Engine: [![Thomas the Tank Engine](https://i.stack.imgur.com/YUhsm.png)](https://i.stack.imgur.com/YUhsm.png) Let's say we use GIMP to find the 2D coordinates of what we think is a square on the ground plane (whether or not it is really a square depends on your judgment of the depth): [![With an outline of the square](https://i.stack.imgur.com/u8nKF.png)](https://i.stack.imgur.com/u8nKF.png) I get four points in the 2D image: `(318, 247)`, `(326, 312)`, `(418, 241)`, and `(452, 303)`. By convention, we say that these points should correspond to the 3D points: `(0, 0, 0)`, `(0, 0, 1)`, `(1, 0, 0)`, and `(1, 0, 1)`. In other words, a unit square in the y=0 plane. Projecting each of these 3D coordinates into 2D is done by multiplying the 4D vector `[x, y, z, 1]` with a 4x4 projection matrix, then dividing the x and y components by z to actually get the perspective correction. This is more or less what [gluProject()](https://www.opengl.org/sdk/docs/man2/xhtml/gluProject.xml) does, except `gluProject()` also takes the current viewport into account and takes a separate modelview matrix into account (we can just assume the modelview matrix is the identity matrix). It is very handy to look at the `gluProject()` documentation because I actually want a solution that works for OpenGL, but beware that the documentation is missing the division by z in the formula. Remember, the algorithm is to start with some projection matrix and randomly perturb it until it gives the projection that we want. So what we're going to do is project each of the four 3D points and see how close we get to the 2D points we wanted. If our random perturbations cause the projected 2D points to get closer to the ones we marked above, then we keep that matrix as an improvement over our initial (or previous) guess. Let's define our points: ``` # Known 2D coordinates of our rectangle i0 = Point2(318, 247) i1 = Point2(326, 312) i2 = Point2(418, 241) i3 = Point2(452, 303) # 3D coordinates corresponding to i0, i1, i2, i3 r0 = Point3(0, 0, 0) r1 = Point3(0, 0, 1) r2 = Point3(1, 0, 0) r3 = Point3(1, 0, 1) ``` We need to start with some matrix, identity matrix seems a natural choice: ``` mat = [ [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1], ] ``` We need to actually implement the projection (which is basically a matrix multiplication): ``` def project(p, mat): x = mat[0][0] * p.x + mat[0][1] * p.y + mat[0][2] * p.z + mat[0][3] * 1 y = mat[1][0] * p.x + mat[1][1] * p.y + mat[1][2] * p.z + mat[1][3] * 1 w = mat[3][0] * p.x + mat[3][1] * p.y + mat[3][2] * p.z + mat[3][3] * 1 return Point(720 * (x / w + 1) / 2., 576 - 576 * (y / w + 1) / 2.) ``` This is basically what `gluProject()` does, 720 and 576 are the width and height of the image, respectively (i.e. the viewport), and we subtract from 576 to count for the fact that we counted y coordinates from the top while OpenGL typically counts them from the bottom. You'll notice we're not calculating z, that's because we don't really need it here (though it could be handy to ensure it falls within the range that OpenGL uses for the depth buffer). Now we need a function for evaluating how close we are to the correct solution. The value returned by this function is what we will use to check whether one matrix is better than another. I chose to go by sum of squared distances, i.e.: ``` # The squared distance between two points a and b def norm2(a, b): dx = b.x - a.x dy = b.y - a.y return dx * dx + dy * dy def evaluate(mat): c0 = project(r0, mat) c1 = project(r1, mat) c2 = project(r2, mat) c3 = project(r3, mat) return norm2(i0, c0) + norm2(i1, c1) + norm2(i2, c2) + norm2(i3, c3) ``` To perturb the matrix, we simply pick an element to perturb by a random amount within some range: ``` def perturb(amount): from copy import deepcopy from random import randrange, uniform mat2 = deepcopy(mat) mat2[randrange(4)][randrange(4)] += uniform(-amount, amount) ``` (It's worth noting that our `project()` function doesn't actually use `mat[2]` at all, since we don't compute z, and since all our y coordinates are 0 the `mat[*][1]` values are irrelevant as well. We could use this fact and never try to perturb those values, which would give a small speedup, but that is left as an exercise...) For convenience, let's add a function that does the bulk of the approximation by calling `perturb()` over and over again on what is the best matrix we've found so far: ``` def approximate(mat, amount, n=100000): est = evaluate(mat) for i in xrange(n): mat2 = perturb(mat, amount) est2 = evaluate(mat2) if est2 < est: mat = mat2 est = est2 return mat, est ``` Now all that's left to do is to run it...: ``` for i in xrange(100): mat = approximate(mat, 1) mat = approximate(mat, .1) ``` I find this already gives a pretty accurate answer. After running for a while, the matrix I found was: ``` [ [1.0836000765696232, 0, 0.16272110011060575, -0.44811064935115597], [0.09339193527789781, 1, -0.7990570384334473, 0.539087345090207 ], [0, 0, 1, 0 ], [0.06700844759602216, 0, -0.8333379578853196, 3.875290562060915 ], ] ``` with an error of around `2.6e-5`. (Notice how the elements we said were not used in the computation have not actually been changed from our initial matrix; that's because changing these entries would not change the result of the evaluation and so the change would never get carried along.) We can pass the matrix into OpenGL using `glLoadMatrix()` (but remember to transpose it first, and remember to load your modelview matrix with the identity matrix): ``` def transpose(m): return [ [m[0][0], m[1][0], m[2][0], m[3][0]], [m[0][1], m[1][1], m[2][1], m[3][1]], [m[0][2], m[1][2], m[2][2], m[3][2]], [m[0][3], m[1][3], m[2][3], m[3][3]], ] glLoadMatrixf(transpose(mat)) ``` Now we can for example translate along the z axis to get different positions along the tracks: ``` glTranslate(0, 0, frame) frame = frame + 1 glBegin(GL_QUADS) glVertex3f(0, 0, 0) glVertex3f(0, 0, 1) glVertex3f(1, 0, 1) glVertex3f(1, 0, 0) glEnd() ``` [![With 3D translation](https://i.stack.imgur.com/dfeEx.gif)](https://i.stack.imgur.com/dfeEx.gif) For sure this is not very elegant from a mathematical point of view; you don't get a closed form equation that you can just plug your numbers into and get a direct (and accurate) answer. HOWEVER, it does allow you to add additional constraints without having to worry about complicating your equations; for example if we wanted to incorporate height as well, we could use that corner of the house and say (in our evaluation function) that the distance from the ground to the roof should be so-and-so, and run the algorithm again. So yes, it's a brute force of sorts, but works, and works well. [![Choo choo!](https://i.stack.imgur.com/smdR8.png)](https://i.stack.imgur.com/smdR8.png)
76,204
<p>I am receiving a 3rd party feed of which I cannot be certain of the namespace so I am currently having to use the local-name() function in my XSLT to get the element values. However I need to get an attribute from one such element and I don't know how to do this when the namespaces are unknown (hence need for local-name() function).</p> <p>N.B. I am using .net 2.0 to process the XSLT</p> <p>Here is a sample of the XML:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;feed xmlns="http://www.w3.org/2005/Atom"&gt; &lt;id&gt;some id&lt;/id&gt; &lt;title&gt;some title&lt;/title&gt; &lt;updated&gt;2008-09-11T15:53:31+01:00&lt;/updated&gt; &lt;link rel="self" href="http://www.somefeedurl.co.uk" /&gt; &lt;author&gt; &lt;name&gt;some author&lt;/name&gt; &lt;uri&gt;http://someuri.co.uk&lt;/uri&gt; &lt;/author&gt; &lt;generator uri="http://aardvarkmedia.co.uk/"&gt;AardvarkMedia script&lt;/generator&gt; &lt;entry&gt; &lt;id&gt;http://soemaddress.co.uk/branded3/80406&lt;/id&gt; &lt;title type="html"&gt;My Ttile&lt;/title&gt; &lt;link rel="alternate" href="http://www.someurl.co.uk" /&gt; &lt;updated&gt;2008-02-13T00:00:00+01:00&lt;/updated&gt; &lt;published&gt;2002-09-11T14:16:20+01:00&lt;/published&gt; &lt;category term="mycategorytext" label="restaurant"&gt;Test&lt;/category&gt; &lt;content type="xhtml"&gt; &lt;div xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;div class="vcard"&gt; &lt;p class="fn org"&gt;some title&lt;/p&gt; &lt;p class="adr"&gt; &lt;abbr class="type" title="POSTAL" /&gt; &lt;span class="street-address"&gt;54 Some Street&lt;/span&gt; , &lt;span class="locality" /&gt; , &lt;span class="country-name"&gt;UK&lt;/span&gt; &lt;/p&gt; &lt;p class="tel"&gt; &lt;span class="value"&gt;0123456789&lt;/span&gt; &lt;/p&gt; &lt;div class="geo"&gt; &lt;span class="latitude"&gt;51.99999&lt;/span&gt; , &lt;span class="longitude"&gt;-0.123456&lt;/span&gt; &lt;/div&gt; &lt;p class="note"&gt; &lt;span class="type"&gt;Review&lt;/span&gt; &lt;span class="value"&gt;Some content&lt;/span&gt; &lt;/p&gt; &lt;p class="note"&gt; &lt;span class="type"&gt;Overall rating&lt;/span&gt; &lt;span class="value"&gt;8&lt;/span&gt; &lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/content&gt; &lt;category term="cuisine-54" label="Spanish" /&gt; &lt;Point xmlns="http://www.w3.org/2003/01/geo/wgs84_pos#"&gt; &lt;lat&gt;51.123456789&lt;/lat&gt; &lt;long&gt;-0.11111111&lt;/long&gt; &lt;/Point&gt; &lt;/entry&gt; &lt;/feed&gt; </code></pre> <p>This is XSLT</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8" ?&gt; &lt;xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:wgs="http://www.w3.org/2003/01/geo/wgs84_pos#" exclude-result-prefixes="atom wgs"&gt; &lt;xsl:output method="xml" indent="yes"/&gt; &lt;xsl:key name="uniqueVenuesKey" match="entry" use="id"/&gt; &lt;xsl:key name="uniqueCategoriesKey" match="entry" use="category/@term"/&gt; &lt;xsl:template match="/"&gt; &lt;locations&gt; &lt;!-- Get all unique venues --&gt; &lt;xsl:for-each select="/*[local-name()='feed']/*[local-name()='entry']"&gt; &lt;xsl:variable name="CurrentVenueKey" select="*[local-name()='id']" &gt;&lt;/xsl:variable&gt; &lt;xsl:variable name="CurrentVenueName" select="*[local-name()='title']" &gt;&lt;/xsl:variable&gt; &lt;xsl:variable name="CurrentVenueAddress1" select="*[local-name()='content']/*[local-name()='div']/*[local-name()='div']/*[local-name()='p'][@class='adr']/*[local-name()='span'][@class='street-address']" &gt;&lt;/xsl:variable&gt; &lt;xsl:variable name="CurrentVenueCity" select="*[local-name()='content']/*[local-name()='div']/*[local-name()='div']/*[local-name()='p'][@class='adr']/*[local-name()='span'][@class='locality']" &gt;&lt;/xsl:variable&gt; &lt;xsl:variable name="CurrentVenuePostcode" select="*[local-name()='postcode']" &gt;&lt;/xsl:variable&gt; &lt;xsl:variable name="CurrentVenueTelephone" select="*[local-name()='telephone']" &gt;&lt;/xsl:variable&gt; &lt;xsl:variable name="CurrentVenueLat" select="*[local-name()='Point']/*[local-name()='lat']" &gt;&lt;/xsl:variable&gt; &lt;xsl:variable name="CurrentVenueLong" select="*[local-name()='Point']/*[local-name()='long']" &gt;&lt;/xsl:variable&gt; &lt;xsl:variable name="CurrentCategory" select="WHATDOIPUTHERE"&gt;&lt;/xsl:variable&gt; &lt;location&gt; &lt;locationName&gt; &lt;xsl:value-of select = "$CurrentVenueName" /&gt; &lt;/locationName&gt; &lt;category&gt; &lt;xsl:value-of select = "$CurrentCategory" /&gt; &lt;/category&gt; &lt;description&gt; &lt;xsl:value-of select = "$CurrentVenueName" /&gt; &lt;/description&gt; &lt;venueAddress&gt; &lt;streetName&gt; &lt;xsl:value-of select = "$CurrentVenueAddress1" /&gt; &lt;/streetName&gt; &lt;town&gt; &lt;xsl:value-of select = "$CurrentVenueCity" /&gt; &lt;/town&gt; &lt;postcode&gt; &lt;xsl:value-of select = "$CurrentVenuePostcode" /&gt; &lt;/postcode&gt; &lt;wgs84_latitude&gt; &lt;xsl:value-of select = "$CurrentVenueLat" /&gt; &lt;/wgs84_latitude&gt; &lt;wgs84_longitude&gt; &lt;xsl:value-of select = "$CurrentVenueLong" /&gt; &lt;/wgs84_longitude&gt; &lt;/venueAddress&gt; &lt;venuePhone&gt; &lt;phonenumber&gt; &lt;xsl:value-of select = "$CurrentVenueTelephone" /&gt; &lt;/phonenumber&gt; &lt;/venuePhone&gt; &lt;/location&gt; &lt;/xsl:for-each&gt; &lt;/locations&gt; &lt;/xsl:template&gt; &lt;/xsl:stylesheet&gt; </code></pre> <p>I'm trying to replace the $CurrentCategory variable the appropriate code to display <em>mycategorytext</em></p>
[ { "answer_id": 76497, "author": "Santiago Palladino", "author_id": 12791, "author_profile": "https://Stackoverflow.com/users/12791", "pm_score": 5, "selected": true, "text": "<p>I don't have an XSLT editor here, but have you tried using</p>\n\n<pre><code>*[local-name()='category']/@*[local-name()='term']\n</code></pre>\n" }, { "answer_id": 76627, "author": "elarson", "author_id": 5434, "author_profile": "https://Stackoverflow.com/users/5434", "pm_score": 0, "selected": false, "text": "<p>I'm not really sure why you have to use local-name(), but if you share a little more info as to what xslt processor you are using along with the language, I'll be that can be figured out. I say this b/c you should be able to do something like:</p>\n\n<pre><code>&lt;xsl:stylesheet xmlns=\"http://www.w3.org/2005/Atom\" ..&gt;\n\n&lt;xsl:template match=\"feed\"&gt;\n &lt;xsl:apply-templates /&gt;\n&lt;/xsl:template&gt;\n\n&lt;xsl:template match=\"entry\"&gt;\n ... \n &lt;xsl:variable name=\"current-category\" select=\"category/@term\" /&gt;\n ...\n&lt;/xsl:template&gt;\n</code></pre>\n\n<p>The two things I'm hoping help you out are the xmlns declaration at the top without a prefix. That sets the default namespace so you don't have to use the namespace prefixes. Likewise, you could call do 'xmlns:a=\"http://www.w3.org/2005/Atom\"' and then do 'select=\"a:feed\"'. The other thing to notice is using the '@term' which selects attributes. If you wanted to match on any attribute '@*' works just like it would for elements. </p>\n\n<p>Again, depending on the processor, there might be other helpful tools at your disposal so if you can provide a little more information it might help. Also, the <a href=\"http://www.mulberrytech.com/xsl/xsl-list/\" rel=\"nofollow noreferrer\">XSL mailing list</a> might another helpful resource.</p>\n" }, { "answer_id": 76658, "author": "Dominic Cronin", "author_id": 9967, "author_profile": "https://Stackoverflow.com/users/9967", "pm_score": 2, "selected": false, "text": "<p>According to <a href=\"http://www.w3.org/TR/2006/REC-xml-names-20060816/#scoping-defaulting\" rel=\"nofollow noreferrer\">http://www.w3.org/TR/2006/REC-xml-names-20060816/#scoping-defaulting</a></p>\n\n<p>\"Default namespace declarations do not apply directly to attribute names; the interpretation of unprefixed attributes is determined by the element on which they appear.\"</p>\n\n<p>This means that your attributes aren't in a namespace. Just use \"@term\". </p>\n\n<p>Just to be a bit clearer, there is no need for using local-name() to solve this problem. \nThe conventional way to deal with it would be to declare a prefix for the atom namespace in your XSLT, and then use that in your xpath queries. </p>\n\n<p>You have already got this declaration on your stylesheet element (xmlns:atom=\"http://www.w3.org/2005/Atom\"), so all that remains is to use it. </p>\n\n<p>As I have already explained, the attribute is not affected by the default namespace, so your code would look like this (assuming that you were to add \"xmlns:xhtml='<a href=\"http://www.w3.org/1999/xhtml\" rel=\"nofollow noreferrer\">http://www.w3.org/1999/xhtml</a>'\"): </p>\n\n<pre><code> &lt;xsl:for-each select=\"/atom:feed/atom:entry\"&gt;\n &lt;xsl:variable name=\"CurrentVenueKey\" select=\"atom:id\" /&gt;\n &lt;xsl:variable name=\"CurrentVenueName\" select=\"atom:title\" /&gt;\n &lt;xsl:variable name=\"CurrentVenueAddress1\" \n select=\"atom:content/xhtml:div/xhtml:div/xhtml:p[@class='adr']/xhtml:span[@class='street-address']\" /&gt;\n &lt;xsl:variable name=\"CurrentVenueCity\" \n select=\"atom:content/xhtml:div/xhtml:div'/xhtml:p[@class='adr']/xhtml:span[@class='locality'] /&gt;\n...\n &lt;xsl:variable name=\"CurrentCategory\" select=\"atom:category/@term\" /&gt;\n\n..... \n</code></pre>\n\n<p>local-name() can be very useful if you really don't know the structure of the XML you are transforming, but in this case, if you receive anything other than what you're expecting, it will break in any case. </p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/76204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/258/" ]
I am receiving a 3rd party feed of which I cannot be certain of the namespace so I am currently having to use the local-name() function in my XSLT to get the element values. However I need to get an attribute from one such element and I don't know how to do this when the namespaces are unknown (hence need for local-name() function). N.B. I am using .net 2.0 to process the XSLT Here is a sample of the XML: ``` <?xml version="1.0" encoding="UTF-8"?> <feed xmlns="http://www.w3.org/2005/Atom"> <id>some id</id> <title>some title</title> <updated>2008-09-11T15:53:31+01:00</updated> <link rel="self" href="http://www.somefeedurl.co.uk" /> <author> <name>some author</name> <uri>http://someuri.co.uk</uri> </author> <generator uri="http://aardvarkmedia.co.uk/">AardvarkMedia script</generator> <entry> <id>http://soemaddress.co.uk/branded3/80406</id> <title type="html">My Ttile</title> <link rel="alternate" href="http://www.someurl.co.uk" /> <updated>2008-02-13T00:00:00+01:00</updated> <published>2002-09-11T14:16:20+01:00</published> <category term="mycategorytext" label="restaurant">Test</category> <content type="xhtml"> <div xmlns="http://www.w3.org/1999/xhtml"> <div class="vcard"> <p class="fn org">some title</p> <p class="adr"> <abbr class="type" title="POSTAL" /> <span class="street-address">54 Some Street</span> , <span class="locality" /> , <span class="country-name">UK</span> </p> <p class="tel"> <span class="value">0123456789</span> </p> <div class="geo"> <span class="latitude">51.99999</span> , <span class="longitude">-0.123456</span> </div> <p class="note"> <span class="type">Review</span> <span class="value">Some content</span> </p> <p class="note"> <span class="type">Overall rating</span> <span class="value">8</span> </p> </div> </div> </content> <category term="cuisine-54" label="Spanish" /> <Point xmlns="http://www.w3.org/2003/01/geo/wgs84_pos#"> <lat>51.123456789</lat> <long>-0.11111111</long> </Point> </entry> </feed> ``` This is XSLT ``` <?xml version="1.0" encoding="UTF-8" ?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:wgs="http://www.w3.org/2003/01/geo/wgs84_pos#" exclude-result-prefixes="atom wgs"> <xsl:output method="xml" indent="yes"/> <xsl:key name="uniqueVenuesKey" match="entry" use="id"/> <xsl:key name="uniqueCategoriesKey" match="entry" use="category/@term"/> <xsl:template match="/"> <locations> <!-- Get all unique venues --> <xsl:for-each select="/*[local-name()='feed']/*[local-name()='entry']"> <xsl:variable name="CurrentVenueKey" select="*[local-name()='id']" ></xsl:variable> <xsl:variable name="CurrentVenueName" select="*[local-name()='title']" ></xsl:variable> <xsl:variable name="CurrentVenueAddress1" select="*[local-name()='content']/*[local-name()='div']/*[local-name()='div']/*[local-name()='p'][@class='adr']/*[local-name()='span'][@class='street-address']" ></xsl:variable> <xsl:variable name="CurrentVenueCity" select="*[local-name()='content']/*[local-name()='div']/*[local-name()='div']/*[local-name()='p'][@class='adr']/*[local-name()='span'][@class='locality']" ></xsl:variable> <xsl:variable name="CurrentVenuePostcode" select="*[local-name()='postcode']" ></xsl:variable> <xsl:variable name="CurrentVenueTelephone" select="*[local-name()='telephone']" ></xsl:variable> <xsl:variable name="CurrentVenueLat" select="*[local-name()='Point']/*[local-name()='lat']" ></xsl:variable> <xsl:variable name="CurrentVenueLong" select="*[local-name()='Point']/*[local-name()='long']" ></xsl:variable> <xsl:variable name="CurrentCategory" select="WHATDOIPUTHERE"></xsl:variable> <location> <locationName> <xsl:value-of select = "$CurrentVenueName" /> </locationName> <category> <xsl:value-of select = "$CurrentCategory" /> </category> <description> <xsl:value-of select = "$CurrentVenueName" /> </description> <venueAddress> <streetName> <xsl:value-of select = "$CurrentVenueAddress1" /> </streetName> <town> <xsl:value-of select = "$CurrentVenueCity" /> </town> <postcode> <xsl:value-of select = "$CurrentVenuePostcode" /> </postcode> <wgs84_latitude> <xsl:value-of select = "$CurrentVenueLat" /> </wgs84_latitude> <wgs84_longitude> <xsl:value-of select = "$CurrentVenueLong" /> </wgs84_longitude> </venueAddress> <venuePhone> <phonenumber> <xsl:value-of select = "$CurrentVenueTelephone" /> </phonenumber> </venuePhone> </location> </xsl:for-each> </locations> </xsl:template> </xsl:stylesheet> ``` I'm trying to replace the $CurrentCategory variable the appropriate code to display *mycategorytext*
I don't have an XSLT editor here, but have you tried using ``` *[local-name()='category']/@*[local-name()='term'] ```
76,223
<p>I am working on a project where the requirement is to have a date calculated as being the last Friday of a given month. I think I have a solution that only uses standard Java, but I was wondering if anyone knew of anything more concise or efficient. Below is what I tested with for this year:</p> <pre><code> for (int month = 0; month &lt; 13; month++) { GregorianCalendar d = new GregorianCalendar(); d.set(d.MONTH, month); System.out.println("Last Week of Month in " + d.getDisplayName(d.MONTH, Calendar.LONG, Locale.ENGLISH) + ": " + d.getLeastMaximum(d.WEEK_OF_MONTH)); d.set(d.DAY_OF_WEEK, d.FRIDAY); d.set(d.WEEK_OF_MONTH, d.getActualMaximum(d.WEEK_OF_MONTH)); while (d.get(d.MONTH) &gt; month || d.get(d.MONTH) &lt; month) { d.add(d.WEEK_OF_MONTH, -1); } Date dt = d.getTime(); System.out.println("Last Friday of Last Week in " + d.getDisplayName(d.MONTH, Calendar.LONG, Locale.ENGLISH) + ": " + dt.toString()); } </code></pre>
[ { "answer_id": 76265, "author": "scubabbl", "author_id": 9450, "author_profile": "https://Stackoverflow.com/users/9450", "pm_score": 0, "selected": false, "text": "<p>That looks like a perfectly acceptable solution. If that works, use it. That is minimal code and there's no reason to optimize it unless you have to. </p>\n" }, { "answer_id": 76389, "author": "Binil Thomas", "author_id": 3973, "author_profile": "https://Stackoverflow.com/users/3973", "pm_score": 1, "selected": false, "text": "<p>Slightly easier to read, brute-force approach:</p>\n\n<pre><code>public int getLastFriday(int month, int year) {\n Calendar cal = Calendar.getInstance();\n cal.set(year, month, 1, 0, 0, 0); // set to first day of the month\n cal.set(Calendar.MILLISECOND, 0);\n\n int friday = -1;\n while (cal.get(Calendar.MONTH) == month) { \n if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY) { // is it a friday?\n friday = cal.get(Calendar.DAY_OF_MONTH);\n cal.add(Calendar.DAY_OF_MONTH, 7); // skip 7 days\n } else {\n cal.add(Calendar.DAY_OF_MONTH, 1); // skip 1 day\n }\n }\n return friday;\n}\n</code></pre>\n" }, { "answer_id": 76430, "author": "Hans Doggen", "author_id": 9504, "author_profile": "https://Stackoverflow.com/users/9504", "pm_score": 3, "selected": false, "text": "<p>I would use a library like <a href=\"http://joda-time.sourceforge.net\" rel=\"noreferrer\">Jodatime</a>. It has a very useful API and it uses normal month numbers. And best of all, it is thread safe.</p>\n\n<p>I think that you can have a solution with (but possibly not the shortest, but certainly more readable):</p>\n\n<pre><code>DateTime now = new DateTime(); \nDateTime dt = now.dayOfMonth().withMaximumValue().withDayOfWeek(DateTimeConstants.FRIDAY);\nif (dt.getMonthOfYear() != now.getMonthOfYear()) {\n dt = dt.minusDays(7);\n} \nSystem.out.println(dt);\n</code></pre>\n" }, { "answer_id": 76437, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>You never need to loop to find this out. For determining the \"last Friday\" date for this month, start with the first day of next month. Subtract the appropriate number of days depending on what (numerical) day of the week the first day of the month falls on. There's your \"last Friday.\" I'm pretty sure it can be boiled down to a longish one-liner, but I'm not a java dev. So I'll leave that to someone else. </p>\n" }, { "answer_id": 76447, "author": "Benno Richters", "author_id": 3565, "author_profile": "https://Stackoverflow.com/users/3565", "pm_score": 1, "selected": false, "text": "<p>Though I agree with scubabbl, here is a version without an inner while.</p>\n\n<pre><code>int year = 2008;\nfor (int m = Calendar.JANUARY; m &lt;= Calendar.DECEMBER; m++) {\n Calendar cal = new GregorianCalendar(year, m, 1);\n cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));\n int diff = Calendar.FRIDAY - cal.get(Calendar.DAY_OF_WEEK);\n if (diff &gt; 0) {\n diff -= 7;\n }\n cal.add(Calendar.DAY_OF_MONTH, diff);\n System.out.println(cal.getTime());\n}\n</code></pre>\n" }, { "answer_id": 76744, "author": "Adam Davis", "author_id": 2915, "author_profile": "https://Stackoverflow.com/users/2915", "pm_score": 2, "selected": false, "text": "<p>You need to know two things - the number of days in the month, and the weekday the first of the month falls on.</p>\n\n<p>If the first day of the month is a</p>\n\n<ul>\n<li>Sunday, then the last Friday is <em>always</em> the 27th.</li>\n<li>Monday, then the last Friday is <em>always</em> the 26th.</li>\n<li>Tuesday, then the last Friday is <em>always</em> the 25th.</li>\n<li>Wednesday, then the last Friday is the 24th, unless there are 31 days in the month, then it's the 31st</li>\n<li>Thursday, then the last Friday is the 23rd, unless there are 30 days or more in the month, then it's the 30th.</li>\n<li>Friday, then the last Friday is the 22nd, unless there are 29 days or more in the month, then it's the 29th.</li>\n<li>Saturday, then the last Friday is <em>always</em> the 28th.</li>\n</ul>\n\n<p>There are only three special cases. A single switch statement and three if statements (or ternary operators if you like every case to have a single line...)</p>\n\n<p>Work it out on paper. Don't need any special libraries, functions, julian conversions, etc (well, except to get the weekday the 1st falls on, and maybe the number of days that month... )</p>\n\n<p><a href=\"https://stackoverflow.com/questions/76223/get-last-friday-of-month-in-java#77315\">Aaron implemented it in Java.</a></p>\n\n<p>-Adam</p>\n" }, { "answer_id": 77077, "author": "ColinD", "author_id": 13792, "author_profile": "https://Stackoverflow.com/users/13792", "pm_score": 6, "selected": true, "text": "<p>Based on <a href=\"https://stackoverflow.com/questions/76223/get-last-friday-of-month-in-java#76437\">marked23's</a> suggestion:</p>\n\n<pre><code>public Date getLastFriday( int month, int year ) {\n Calendar cal = Calendar.getInstance();\n cal.set( year, month + 1, 1 );\n cal.add( Calendar.DAY_OF_MONTH, -( cal.get( Calendar.DAY_OF_WEEK ) % 7 + 1 ) );\n return cal.getTime();\n}\n</code></pre>\n" }, { "answer_id": 77315, "author": "Aaron", "author_id": 7659, "author_profile": "https://Stackoverflow.com/users/7659", "pm_score": 2, "selected": false, "text": "<p>code for <a href=\"https://stackoverflow.com/questions/76223/get-last-friday-of-month-in-java#76744\">Adam Davis's algorithm</a></p>\n\n<pre><code>public static int getLastFriday(int month, int year)\n{\nCalendar cal = Calendar.getInstance();\ncal.set(year, month, 1, 0, 0, 0); // set to first day of the month\ncal.set(Calendar.MILLISECOND, 0);\n\nint firstDay = cal.get(Calendar.DAY_OF_WEEK);\nint daysOfMonth = cal.getMaximum(Calendar.DAY_OF_MONTH);\n\nswitch (firstDay)\n{\n case Calendar.SUNDAY :\n return 27;\n case Calendar.MONDAY :\n return 26;\n case Calendar.TUESDAY :\n return 25;\n case Calendar.WEDNESDAY :\n if (daysOfMonth == 31) return 31;\n return 24;\n case Calendar.THURSDAY :\n if (daysOfMonth &gt;= 30) return 30;\n return 23;\n case Calendar.FRIDAY :\n if (daysOfMonth &gt;= 29) return 29;\n return 22;\n case Calendar.SATURDAY :\n return 28;\n}\nthrow new RuntimeException(\"what day of the month?\");\n}}\n</code></pre>\n" }, { "answer_id": 1067710, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Hope this helps..</p>\n\n<pre><code>public static void getSundaysInThisMonth(int monthNumber, int yearNumber){\n //int year =2009;\n //int dayOfWeek = Calendar.SUNDAY;\n // instantiate Calender and set to first Sunday of 2009\n Calendar cal = new GregorianCalendar();\n cal.set(Calendar.MONTH, monthNumber-1);\n cal.set(Calendar.YEAR, yearNumber);\n cal.set(Calendar.DATE, 1);\n int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);\n int dateOfWeek = cal.get(Calendar.DATE);\n while (dayOfWeek != Calendar.SUNDAY) {\n cal.set(Calendar.DATE, ++dateOfWeek);\n dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);\n }\n cal.set(Calendar.DATE, dateOfWeek);\n\n int i = 1;\n while (cal.get(Calendar.YEAR) == yearNumber &amp;&amp; cal.get(Calendar.MONTH)==monthNumber-1)\n {\n System.out.println(\"Sunday \" + \" \" + i + \": \" + cal.get(Calendar.DAY_OF_MONTH));\n cal.add(Calendar.DAY_OF_MONTH, 7);\n i++;\n }\n\n }\n public static void main(String args[]){\n getSundaysInThisMonth(1,2009);\n }\n</code></pre>\n" }, { "answer_id": 2545695, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "<p>Let Calendar.class do its magic for you ;)</p>\n\n<pre><code>pCal.set(GregorianCalendar.DAY_OF_WEEK,Calendar.FRIDAY);\npCal.set(GregorianCalendar.DAY_OF_WEEK_IN_MONTH, -1);\n</code></pre>\n" }, { "answer_id": 7806120, "author": "josephus", "author_id": 611228, "author_profile": "https://Stackoverflow.com/users/611228", "pm_score": 2, "selected": false, "text": "<p>here's how to get the last friday, or whatever week day, of the month:</p>\n\n<pre><code>Calendar thisMonth = Calendar.getInstance();\ndayOfWeek = Calendar.FRIDAY; // or whatever\nthisMonth.set(Calendar.WEEK_OF_MONTH, thisMonth.getActualMaximum(Calendar.WEEK_OF_MONTH);;\nthisMonth.set(Calendar.DAY_OF_WEEK, dayOfWeek);\nint lastDay = thisMonth.get(Calendar.DAY_OF_MONTH); // this should be it.\n</code></pre>\n" }, { "answer_id": 9469295, "author": "Alexeyy Alexeyy", "author_id": 1192726, "author_profile": "https://Stackoverflow.com/users/1192726", "pm_score": -1, "selected": false, "text": "<pre><code>public static Calendar getNthDow(int month, int year, int dayOfWeek, int n) {\n Calendar cal = Calendar.getInstance();\n cal.set(year, month, 1);\n cal.set(Calendar.DAY_OF_WEEK, dayOfWeek);\n cal.set(Calendar.DAY_OF_WEEK_IN_MONTH, n);\n return (cal.get(Calendar.MONTH) == month) &amp;&amp; (cal.get(Calendar.YEAR) == year) ? cal : null;\n}\n</code></pre>\n" }, { "answer_id": 10922864, "author": "akshay jangid", "author_id": 1440879, "author_profile": "https://Stackoverflow.com/users/1440879", "pm_score": 1, "selected": false, "text": "<p>Below program is for the last Friday of each month. it can be used to get the last of any day of the week in any month. The variable <code>offset=0</code> means current month(system date), offset=1 means next month, so on. The <code>getLastFridayofMonth(int offset)</code> method will return the last Friday.</p>\n\n<pre><code>import java.text.SimpleDateFormat;\nimport java.util.Calendar;\n\npublic class LastFriday {\n\n public static Calendar getLastFriday(Calendar cal,int offset){\n int dayofweek;//1-Sunday,2-Monday so on....\n cal.set(Calendar.MONTH,cal.get(Calendar.MONTH)+offset);\n cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH)); //set calendar to last day of month\n dayofweek=cal.get(Calendar.DAY_OF_WEEK); //get the day of the week for last day of month set above,1-sunday,2-monday etc\n if(dayofweek&lt;Calendar.FRIDAY) //Calendar.FRIDAY will return integer value =5 \n cal.set(Calendar.DAY_OF_MONTH, cal.get(Calendar.DAY_OF_MONTH)-7+Calendar.FRIDAY-dayofweek);\n else\n cal.set(Calendar.DAY_OF_MONTH, cal.get(Calendar.DAY_OF_MONTH)+Calendar.FRIDAY-dayofweek); \n\n return cal;\n }\n\n public static String getLastFridayofMonth(int offset) { //offset=0 mean current month\n final String DATE_FORMAT_NOW = \"dd-MMM-yyyy\";\n Calendar cal = Calendar.getInstance();\n SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);\n cal=getLastFriday(cal,offset);\n return sdf.format(cal.getTime()); \n\n }\n\n public static void main(String[] args) {\n System.out.println(getLastFridayofMonth(0)); //0 = current month\n System.out.println(getLastFridayofMonth(1));//1=next month\n System.out.println(getLastFridayofMonth(2));//2=month after next month\n }\n\n}\n</code></pre>\n" }, { "answer_id": 22397346, "author": "Dhananjay Chauhan", "author_id": 3418626, "author_profile": "https://Stackoverflow.com/users/3418626", "pm_score": 0, "selected": false, "text": "<pre><code>public static int lastSundayDate()\n{\n Calendar cal = getCalendarInstance();\n cal.setTime(new Date(getUTCTimeMillis()));\n cal.set( Calendar.DAY_OF_MONTH , 25 );\n return (25 + 8 - (cal.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY ? cal.get(Calendar.DAY_OF_WEEK) : 8));\n}\n</code></pre>\n" }, { "answer_id": 33867973, "author": "Przemek", "author_id": 1981559, "author_profile": "https://Stackoverflow.com/users/1981559", "pm_score": 4, "selected": false, "text": "<h1>java.time</h1>\n\n<p>Using <a href=\"http://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html\" rel=\"noreferrer\">java.time</a> library built into Java 8 and later, you may use <a href=\"https://docs.oracle.com/javase/8/docs/api/java/time/temporal/TemporalAdjusters.html#lastInMonth-java.time.DayOfWeek-\" rel=\"noreferrer\"><code>TemporalAdjusters.lastInMonth</code></a>:</p>\n\n<pre><code>val now = LocalDate.now() \nval lastInMonth = now.with(TemporalAdjusters.lastInMonth(DayOfWeek.FRIDAY))\n</code></pre>\n\n<p>You may choose any day from the <a href=\"http://docs.oracle.com/javase/8/docs/api/java/time/DayOfWeek.html\" rel=\"noreferrer\"><code>DayOfWeek</code></a> enum.</p>\n\n<p>If you need to add time information, you may use any available <a href=\"http://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html\" rel=\"noreferrer\"><code>LocalDate</code></a> to <a href=\"http://docs.oracle.com/javase/8/docs/api/java/time/LocalDateTime.html\" rel=\"noreferrer\"><code>LocalDateTime</code></a> conversion like</p>\n\n<pre><code>lastFriday.atStartOfDay() // e.g. 2015-11-27T00:00\n</code></pre>\n" }, { "answer_id": 40993952, "author": "KayV", "author_id": 3956731, "author_profile": "https://Stackoverflow.com/users/3956731", "pm_score": 1, "selected": false, "text": "<p>In Java 8, we can do it simply as:</p>\n\n<pre><code>LocalDate lastFridayOfMonth = LocalDate\n .now()\n .with(lastDayOfMonth())\n .with(previous(DayOfWeek.FRIDAY));\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/76223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7008/" ]
I am working on a project where the requirement is to have a date calculated as being the last Friday of a given month. I think I have a solution that only uses standard Java, but I was wondering if anyone knew of anything more concise or efficient. Below is what I tested with for this year: ``` for (int month = 0; month < 13; month++) { GregorianCalendar d = new GregorianCalendar(); d.set(d.MONTH, month); System.out.println("Last Week of Month in " + d.getDisplayName(d.MONTH, Calendar.LONG, Locale.ENGLISH) + ": " + d.getLeastMaximum(d.WEEK_OF_MONTH)); d.set(d.DAY_OF_WEEK, d.FRIDAY); d.set(d.WEEK_OF_MONTH, d.getActualMaximum(d.WEEK_OF_MONTH)); while (d.get(d.MONTH) > month || d.get(d.MONTH) < month) { d.add(d.WEEK_OF_MONTH, -1); } Date dt = d.getTime(); System.out.println("Last Friday of Last Week in " + d.getDisplayName(d.MONTH, Calendar.LONG, Locale.ENGLISH) + ": " + dt.toString()); } ```
Based on [marked23's](https://stackoverflow.com/questions/76223/get-last-friday-of-month-in-java#76437) suggestion: ``` public Date getLastFriday( int month, int year ) { Calendar cal = Calendar.getInstance(); cal.set( year, month + 1, 1 ); cal.add( Calendar.DAY_OF_MONTH, -( cal.get( Calendar.DAY_OF_WEEK ) % 7 + 1 ) ); return cal.getTime(); } ```