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
248,603
<p>Anyone have a good resource or provide a sample of a natural order sort in C# for an <code>FileInfo</code> array? I am implementing the <code>IComparer</code> interface in my sorts.</p>
[ { "answer_id": 248613, "author": "Greg Beech", "author_id": 13552, "author_profile": "https://Stackoverflow.com/users/13552", "pm_score": 8, "selected": true, "text": "<p>The easiest thing to do is just P/Invoke the built-in function in Windows, and use it as the comparison function in your <code>IComparer</code>:</p>\n\n<pre><code>[DllImport(\"shlwapi.dll\", CharSet = CharSet.Unicode)]\nprivate static extern int StrCmpLogicalW(string psz1, string psz2);\n</code></pre>\n\n<p>Michael Kaplan has some <a href=\"http://www.siao2.com/2006/10/01/778990.aspx\" rel=\"noreferrer\">examples of how this function works here</a>, and the changes that were made for Vista to make it work more intuitively. The plus side of this function is that it will have the same behaviour as the version of Windows it runs on, however this does mean that it differs between versions of Windows so you need to consider whether this is a problem for you.</p>\n\n<p>So a complete implementation would be something like:</p>\n\n<pre><code>[SuppressUnmanagedCodeSecurity]\ninternal static class SafeNativeMethods\n{\n [DllImport(\"shlwapi.dll\", CharSet = CharSet.Unicode)]\n public static extern int StrCmpLogicalW(string psz1, string psz2);\n}\n\npublic sealed class NaturalStringComparer : IComparer&lt;string&gt;\n{\n public int Compare(string a, string b)\n {\n return SafeNativeMethods.StrCmpLogicalW(a, b);\n }\n}\n\npublic sealed class NaturalFileInfoNameComparer : IComparer&lt;FileInfo&gt;\n{\n public int Compare(FileInfo a, FileInfo b)\n {\n return SafeNativeMethods.StrCmpLogicalW(a.Name, b.Name);\n }\n}\n</code></pre>\n" }, { "answer_id": 1364210, "author": "Jonathan Gilbert", "author_id": 166815, "author_profile": "https://Stackoverflow.com/users/166815", "pm_score": 4, "selected": false, "text": "<p>You do need to be careful -- I vaguely recall reading that StrCmpLogicalW, or something like it, was not strictly transitive, and I have observed .NET's sort methods to sometimes get stuck in infinite loops if the comparison function breaks that rule.</p>\n\n<p>A transitive comparison will always report that a &lt; c if a &lt; b and b &lt; c. There exists a function that does a natural sort order comparison that does not always meet that criterion, but I can't recall whether it is StrCmpLogicalW or something else.</p>\n" }, { "answer_id": 1466808, "author": "Wilka", "author_id": 1367, "author_profile": "https://Stackoverflow.com/users/1367", "pm_score": 3, "selected": false, "text": "<p>Adding to <a href=\"https://stackoverflow.com/questions/248603/natural-sort-order-in-c/248613#248613\">Greg Beech's answer</a> (because I've just been searching for that), if you want to use this from Linq you can use the <code>OrderBy</code> that takes an <code>IComparer</code>. E.g.:</p>\n\n<pre><code>var items = new List&lt;MyItem&gt;();\n\n// fill items\n\nvar sorted = items.OrderBy(item =&gt; item.Name, new NaturalStringComparer());\n</code></pre>\n" }, { "answer_id": 2433501, "author": "James McCormack", "author_id": 71906, "author_profile": "https://Stackoverflow.com/users/71906", "pm_score": 5, "selected": false, "text": "<p>Pure C# solution for linq orderby:</p>\n\n<p><a href=\"http://zootfroot.blogspot.com/2009/09/natural-sort-compare-with-linq-orderby.html\" rel=\"noreferrer\">http://zootfroot.blogspot.com/2009/09/natural-sort-compare-with-linq-orderby.html</a></p>\n\n<pre><code>public class NaturalSortComparer&lt;T&gt; : IComparer&lt;string&gt;, IDisposable\n{\n private bool isAscending;\n\n public NaturalSortComparer(bool inAscendingOrder = true)\n {\n this.isAscending = inAscendingOrder;\n }\n\n #region IComparer&lt;string&gt; Members\n\n public int Compare(string x, string y)\n {\n throw new NotImplementedException();\n }\n\n #endregion\n\n #region IComparer&lt;string&gt; Members\n\n int IComparer&lt;string&gt;.Compare(string x, string y)\n {\n if (x == y)\n return 0;\n\n string[] x1, y1;\n\n if (!table.TryGetValue(x, out x1))\n {\n x1 = Regex.Split(x.Replace(\" \", \"\"), \"([0-9]+)\");\n table.Add(x, x1);\n }\n\n if (!table.TryGetValue(y, out y1))\n {\n y1 = Regex.Split(y.Replace(\" \", \"\"), \"([0-9]+)\");\n table.Add(y, y1);\n }\n\n int returnVal;\n\n for (int i = 0; i &lt; x1.Length &amp;&amp; i &lt; y1.Length; i++)\n {\n if (x1[i] != y1[i])\n {\n returnVal = PartCompare(x1[i], y1[i]);\n return isAscending ? returnVal : -returnVal;\n }\n }\n\n if (y1.Length &gt; x1.Length)\n {\n returnVal = 1;\n }\n else if (x1.Length &gt; y1.Length)\n { \n returnVal = -1; \n }\n else\n {\n returnVal = 0;\n }\n\n return isAscending ? returnVal : -returnVal;\n }\n\n private static int PartCompare(string left, string right)\n {\n int x, y;\n if (!int.TryParse(left, out x))\n return left.CompareTo(right);\n\n if (!int.TryParse(right, out y))\n return left.CompareTo(right);\n\n return x.CompareTo(y);\n }\n\n #endregion\n\n private Dictionary&lt;string, string[]&gt; table = new Dictionary&lt;string, string[]&gt;();\n\n public void Dispose()\n {\n table.Clear();\n table = null;\n }\n}\n</code></pre>\n" }, { "answer_id": 7048016, "author": "J.D.", "author_id": 542821, "author_profile": "https://Stackoverflow.com/users/542821", "pm_score": 5, "selected": false, "text": "<p>None of the existing implementations looked great so I wrote my own. The results are almost identical to the sorting used by modern versions of Windows Explorer (Windows 7/8). The only differences I've seen are 1) although Windows used to (e.g. XP) handle numbers of any length, it's now limited to 19 digits - mine is unlimited, 2) Windows gives inconsistent results with certain sets of Unicode digits - mine works fine (although it doesn't numerically compare digits from surrogate pairs; nor does Windows), and 3) mine can't distinguish different types of non-primary sort weights if they occur in different sections (e.g. \"e-1é\" vs \"é1e-\" - the sections before and after the number have diacritic and punctuation weight differences).</p>\n\n<pre><code>public static int CompareNatural(string strA, string strB) {\n return CompareNatural(strA, strB, CultureInfo.CurrentCulture, CompareOptions.IgnoreCase);\n}\n\npublic static int CompareNatural(string strA, string strB, CultureInfo culture, CompareOptions options) {\n CompareInfo cmp = culture.CompareInfo;\n int iA = 0;\n int iB = 0;\n int softResult = 0;\n int softResultWeight = 0;\n while (iA &lt; strA.Length &amp;&amp; iB &lt; strB.Length) {\n bool isDigitA = Char.IsDigit(strA[iA]);\n bool isDigitB = Char.IsDigit(strB[iB]);\n if (isDigitA != isDigitB) {\n return cmp.Compare(strA, iA, strB, iB, options);\n }\n else if (!isDigitA &amp;&amp; !isDigitB) {\n int jA = iA + 1;\n int jB = iB + 1;\n while (jA &lt; strA.Length &amp;&amp; !Char.IsDigit(strA[jA])) jA++;\n while (jB &lt; strB.Length &amp;&amp; !Char.IsDigit(strB[jB])) jB++;\n int cmpResult = cmp.Compare(strA, iA, jA - iA, strB, iB, jB - iB, options);\n if (cmpResult != 0) {\n // Certain strings may be considered different due to \"soft\" differences that are\n // ignored if more significant differences follow, e.g. a hyphen only affects the\n // comparison if no other differences follow\n string sectionA = strA.Substring(iA, jA - iA);\n string sectionB = strB.Substring(iB, jB - iB);\n if (cmp.Compare(sectionA + \"1\", sectionB + \"2\", options) ==\n cmp.Compare(sectionA + \"2\", sectionB + \"1\", options))\n {\n return cmp.Compare(strA, iA, strB, iB, options);\n }\n else if (softResultWeight &lt; 1) {\n softResult = cmpResult;\n softResultWeight = 1;\n }\n }\n iA = jA;\n iB = jB;\n }\n else {\n char zeroA = (char)(strA[iA] - (int)Char.GetNumericValue(strA[iA]));\n char zeroB = (char)(strB[iB] - (int)Char.GetNumericValue(strB[iB]));\n int jA = iA;\n int jB = iB;\n while (jA &lt; strA.Length &amp;&amp; strA[jA] == zeroA) jA++;\n while (jB &lt; strB.Length &amp;&amp; strB[jB] == zeroB) jB++;\n int resultIfSameLength = 0;\n do {\n isDigitA = jA &lt; strA.Length &amp;&amp; Char.IsDigit(strA[jA]);\n isDigitB = jB &lt; strB.Length &amp;&amp; Char.IsDigit(strB[jB]);\n int numA = isDigitA ? (int)Char.GetNumericValue(strA[jA]) : 0;\n int numB = isDigitB ? (int)Char.GetNumericValue(strB[jB]) : 0;\n if (isDigitA &amp;&amp; (char)(strA[jA] - numA) != zeroA) isDigitA = false;\n if (isDigitB &amp;&amp; (char)(strB[jB] - numB) != zeroB) isDigitB = false;\n if (isDigitA &amp;&amp; isDigitB) {\n if (numA != numB &amp;&amp; resultIfSameLength == 0) {\n resultIfSameLength = numA &lt; numB ? -1 : 1;\n }\n jA++;\n jB++;\n }\n }\n while (isDigitA &amp;&amp; isDigitB);\n if (isDigitA != isDigitB) {\n // One number has more digits than the other (ignoring leading zeros) - the longer\n // number must be larger\n return isDigitA ? 1 : -1;\n }\n else if (resultIfSameLength != 0) {\n // Both numbers are the same length (ignoring leading zeros) and at least one of\n // the digits differed - the first difference determines the result\n return resultIfSameLength;\n }\n int lA = jA - iA;\n int lB = jB - iB;\n if (lA != lB) {\n // Both numbers are equivalent but one has more leading zeros\n return lA &gt; lB ? -1 : 1;\n }\n else if (zeroA != zeroB &amp;&amp; softResultWeight &lt; 2) {\n softResult = cmp.Compare(strA, iA, 1, strB, iB, 1, options);\n softResultWeight = 2;\n }\n iA = jA;\n iB = jB;\n }\n }\n if (iA &lt; strA.Length || iB &lt; strB.Length) {\n return iA &lt; strA.Length ? 1 : -1;\n }\n else if (softResult != 0) {\n return softResult;\n }\n return 0;\n}\n</code></pre>\n\n<p>The signature matches the <code>Comparison&lt;string&gt;</code> delegate:</p>\n\n<pre><code>string[] files = Directory.GetFiles(@\"C:\\\");\nArray.Sort(files, CompareNatural);\n</code></pre>\n\n<p>Here's a wrapper class for use as <code>IComparer&lt;string&gt;</code>:</p>\n\n<pre><code>public class CustomComparer&lt;T&gt; : IComparer&lt;T&gt; {\n private Comparison&lt;T&gt; _comparison;\n\n public CustomComparer(Comparison&lt;T&gt; comparison) {\n _comparison = comparison;\n }\n\n public int Compare(T x, T y) {\n return _comparison(x, y);\n }\n}\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>string[] files = Directory.EnumerateFiles(@\"C:\\\")\n .OrderBy(f =&gt; f, new CustomComparer&lt;string&gt;(CompareNatural))\n .ToArray();\n</code></pre>\n\n<p>Here's a good set of filenames I use for testing:</p>\n\n<pre><code>Func&lt;string, string&gt; expand = (s) =&gt; { int o; while ((o = s.IndexOf('\\\\')) != -1) { int p = o + 1;\n int z = 1; while (s[p] == '0') { z++; p++; } int c = Int32.Parse(s.Substring(p, z));\n s = s.Substring(0, o) + new string(s[o - 1], c) + s.Substring(p + z); } return s; };\nstring encodedFileNames =\n \"KDEqLW4xMiotbjEzKjAwMDFcMDY2KjAwMlwwMTcqMDA5XDAxNyowMlwwMTcqMDlcMDE3KjEhKjEtISox\" +\n \"LWEqMS4yNT8xLjI1KjEuNT8xLjUqMSoxXDAxNyoxXDAxOCoxXDAxOSoxXDA2NioxXDA2NyoxYSoyXDAx\" +\n \"NyoyXDAxOCo5XDAxNyo5XDAxOCo5XDA2Nio9MSphMDAxdGVzdDAxKmEwMDF0ZXN0aW5nYTBcMzEqYTAw\" +\n \"Mj9hMDAyIGE/YTAwMiBhKmEwMDIqYTAwMmE/YTAwMmEqYTAxdGVzdGluZ2EwMDEqYTAxdnNmcyphMSph\" +\n \"MWEqYTF6KmEyKmIwMDAzcTYqYjAwM3E0KmIwM3E1KmMtZSpjZCpjZipmIDEqZipnP2cgMT9oLW4qaG8t\" +\n \"bipJKmljZS1jcmVhbT9pY2VjcmVhbT9pY2VjcmVhbS0/ajBcNDE/ajAwMWE/ajAxP2shKmsnKmstKmsx\" +\n \"KmthKmxpc3QqbTAwMDNhMDA1YSptMDAzYTAwMDVhKm0wMDNhMDA1Km0wMDNhMDA1YSpuMTIqbjEzKm8t\" +\n \"bjAxMypvLW4xMipvLW40P28tbjQhP28tbjR6P28tbjlhLWI1Km8tbjlhYjUqb24wMTMqb24xMipvbjQ/\" +\n \"b240IT9vbjR6P29uOWEtYjUqb245YWI1Km/CrW4wMTMqb8KtbjEyKnAwMCpwMDEqcDAxwr0hKnAwMcK9\" +\n \"KnAwMcK9YSpwMDHCvcK+KnAwMipwMMK9KnEtbjAxMypxLW4xMipxbjAxMypxbjEyKnItMDAhKnItMDAh\" +\n \"NSpyLTAwIe+8lSpyLTAwYSpyLe+8kFwxIS01KnIt77yQXDEhLe+8lSpyLe+8kFwxISpyLe+8kFwxITUq\" +\n \"ci3vvJBcMSHvvJUqci3vvJBcMWEqci3vvJBcMyE1KnIwMCEqcjAwLTUqcjAwLjUqcjAwNSpyMDBhKnIw\" +\n \"NSpyMDYqcjQqcjUqctmg2aYqctmkKnLZpSpy27Dbtipy27Qqctu1KnLfgN+GKnLfhCpy34UqcuClpuCl\" +\n \"rCpy4KWqKnLgpasqcuCnpuCnrCpy4KeqKnLgp6sqcuCppuCprCpy4KmqKnLgqasqcuCrpuCrrCpy4Kuq\" +\n \"KnLgq6sqcuCtpuCtrCpy4K2qKnLgrasqcuCvpuCvrCpy4K+qKnLgr6sqcuCxpuCxrCpy4LGqKnLgsasq\" +\n \"cuCzpuCzrCpy4LOqKnLgs6sqcuC1puC1rCpy4LWqKnLgtasqcuC5kOC5lipy4LmUKnLguZUqcuC7kOC7\" +\n \"lipy4LuUKnLgu5UqcuC8oOC8pipy4LykKnLgvKUqcuGBgOGBhipy4YGEKnLhgYUqcuGCkOGClipy4YKU\" +\n \"KnLhgpUqcuGfoOGfpipy4Z+kKnLhn6UqcuGgkOGglipy4aCUKnLhoJUqcuGlhuGljCpy4aWKKnLhpYsq\" +\n \"cuGnkOGnlipy4aeUKnLhp5UqcuGtkOGtlipy4a2UKnLhrZUqcuGusOGutipy4a60KnLhrrUqcuGxgOGx\" +\n \"hipy4bGEKnLhsYUqcuGxkOGxlipy4bGUKnLhsZUqcuqYoFwx6pilKnLqmKDqmKUqcuqYoOqYpipy6pik\" +\n \"KnLqmKUqcuqjkOqjlipy6qOUKnLqo5UqcuqkgOqkhipy6qSEKnLqpIUqcuqpkOqplipy6qmUKnLqqZUq\" +\n \"cvCQkqAqcvCQkqUqcvCdn5gqcvCdn50qcu+8kFwxISpy77yQXDEt77yVKnLvvJBcMS7vvJUqcu+8kFwx\" +\n \"YSpy77yQXDHqmKUqcu+8kFwx77yO77yVKnLvvJBcMe+8lSpy77yQ77yVKnLvvJDvvJYqcu+8lCpy77yV\" +\n \"KnNpKnPEsSp0ZXN02aIqdGVzdNmi2aAqdGVzdNmjKnVBZS0qdWFlKnViZS0qdUJlKnVjZS0xw6kqdWNl\" +\n \"McOpLSp1Y2Uxw6kqdWPDqS0xZSp1Y8OpMWUtKnVjw6kxZSp3ZWlhMSp3ZWlhMip3ZWlzczEqd2Vpc3My\" +\n \"KndlaXoxKndlaXoyKndlacOfMSp3ZWnDnzIqeSBhMyp5IGE0KnknYTMqeSdhNCp5K2EzKnkrYTQqeS1h\" +\n \"Myp5LWE0KnlhMyp5YTQqej96IDA1MD96IDIxP3ohMjE/ejIwP3oyMj96YTIxP3rCqTIxP1sxKl8xKsKt\" +\n \"bjEyKsKtbjEzKsSwKg==\";\nstring[] fileNames = Encoding.UTF8.GetString(Convert.FromBase64String(encodedFileNames))\n .Replace(\"*\", \".txt?\").Split(new[] { \"?\" }, StringSplitOptions.RemoveEmptyEntries)\n .Select(n =&gt; expand(n)).ToArray();\n</code></pre>\n" }, { "answer_id": 11624488, "author": "mpen", "author_id": 65387, "author_profile": "https://Stackoverflow.com/users/65387", "pm_score": 4, "selected": false, "text": "<p>My solution:</p>\n\n<pre><code>void Main()\n{\n new[] {\"a4\",\"a3\",\"a2\",\"a10\",\"b5\",\"b4\",\"b400\",\"1\",\"C1d\",\"c1d2\"}.OrderBy(x =&gt; x, new NaturalStringComparer()).Dump();\n}\n\npublic class NaturalStringComparer : IComparer&lt;string&gt;\n{\n private static readonly Regex _re = new Regex(@\"(?&lt;=\\D)(?=\\d)|(?&lt;=\\d)(?=\\D)\", RegexOptions.Compiled);\n\n public int Compare(string x, string y)\n {\n x = x.ToLower();\n y = y.ToLower();\n if(string.Compare(x, 0, y, 0, Math.Min(x.Length, y.Length)) == 0)\n {\n if(x.Length == y.Length) return 0;\n return x.Length &lt; y.Length ? -1 : 1;\n }\n var a = _re.Split(x);\n var b = _re.Split(y);\n int i = 0;\n while(true)\n {\n int r = PartCompare(a[i], b[i]);\n if(r != 0) return r;\n ++i;\n }\n }\n\n private static int PartCompare(string x, string y)\n {\n int a, b;\n if(int.TryParse(x, out a) &amp;&amp; int.TryParse(y, out b))\n return a.CompareTo(b);\n return x.CompareTo(y);\n }\n}\n</code></pre>\n\n<p>Results:</p>\n\n<pre><code>1\na2\na3\na4\na10\nb4\nb5\nb400\nC1d\nc1d2\n</code></pre>\n" }, { "answer_id": 11720793, "author": "Matthew Horsley", "author_id": 1562837, "author_profile": "https://Stackoverflow.com/users/1562837", "pm_score": 6, "selected": false, "text": "<p>Just thought I'd add to this (with the most concise solution I could find):</p>\n\n<pre><code>public static IOrderedEnumerable&lt;T&gt; OrderByAlphaNumeric&lt;T&gt;(this IEnumerable&lt;T&gt; source, Func&lt;T, string&gt; selector)\n{\n int max = source\n .SelectMany(i =&gt; Regex.Matches(selector(i), @\"\\d+\").Cast&lt;Match&gt;().Select(m =&gt; (int?)m.Value.Length))\n .Max() ?? 0;\n\n return source.OrderBy(i =&gt; Regex.Replace(selector(i), @\"\\d+\", m =&gt; m.Value.PadLeft(max, '0')));\n}\n</code></pre>\n\n<p>The above pads any numbers in the string to the max length of all numbers in all strings and uses the resulting string to sort. </p>\n\n<p>The cast to (<code>int?</code>) is to allow for collections of strings without any numbers (<code>.Max()</code> on an empty enumerable throws an <code>InvalidOperationException</code>).</p>\n" }, { "answer_id": 15560295, "author": "Eric Liprandi", "author_id": 80280, "author_profile": "https://Stackoverflow.com/users/80280", "pm_score": 0, "selected": false, "text": "<p>We had a need for a natural sort to deal with text with the following pattern:</p>\n\n<pre><code>\"Test 1-1-1 something\"\n\"Test 1-2-3 something\"\n...\n</code></pre>\n\n<p>For some reason when I first looked on SO, I didn't find this post and implemented our own. Compared to some of the solutions presented here, while similar in concept, it could have the benefit of maybe being simpler and easier to understand. However, while I did try to look at performance bottlenecks, It is still a much slower implementation than the default <code>OrderBy()</code>.</p>\n\n<p>Here is the extension method I implement:</p>\n\n<pre><code>public static class EnumerableExtensions\n{\n // set up the regex parser once and for all\n private static readonly Regex Regex = new Regex(@\"\\d+|\\D+\", RegexOptions.Compiled | RegexOptions.Singleline);\n\n // stateless comparer can be built once\n private static readonly AggregateComparer Comparer = new AggregateComparer();\n\n public static IEnumerable&lt;T&gt; OrderByNatural&lt;T&gt;(this IEnumerable&lt;T&gt; source, Func&lt;T, string&gt; selector)\n {\n // first extract string from object using selector\n // then extract digit and non-digit groups\n Func&lt;T, IEnumerable&lt;IComparable&gt;&gt; splitter =\n s =&gt; Regex.Matches(selector(s))\n .Cast&lt;Match&gt;()\n .Select(m =&gt; Char.IsDigit(m.Value[0]) ? (IComparable) int.Parse(m.Value) : m.Value);\n return source.OrderBy(splitter, Comparer);\n }\n\n /// &lt;summary&gt;\n /// This comparer will compare two lists of objects against each other\n /// &lt;/summary&gt;\n /// &lt;remarks&gt;Objects in each list are compare to their corresponding elements in the other\n /// list until a difference is found.&lt;/remarks&gt;\n private class AggregateComparer : IComparer&lt;IEnumerable&lt;IComparable&gt;&gt;\n {\n public int Compare(IEnumerable&lt;IComparable&gt; x, IEnumerable&lt;IComparable&gt; y)\n {\n return\n x.Zip(y, (a, b) =&gt; new {a, b}) // walk both lists\n .Select(pair =&gt; pair.a.CompareTo(pair.b)) // compare each object\n .FirstOrDefault(result =&gt; result != 0); // until a difference is found\n }\n }\n}\n</code></pre>\n\n<p>The idea is to split the original strings into blocks of digits and non-digits (<code>\"\\d+|\\D+\"</code>). Since this is a potentially expensive task, it is done only once per entry. We then use a comparer of comparable objects (sorry, I can't find a more proper way to say it). It compares each block to its corresponding block in the other string.</p>\n\n<p>I would like feedback on how this could be improved and what the major flaws are. Note that maintainability is important to us at this point and we are not currently using this in extremely large data sets.</p>\n" }, { "answer_id": 22323356, "author": "Michael Parker", "author_id": 1554346, "author_profile": "https://Stackoverflow.com/users/1554346", "pm_score": 5, "selected": false, "text": "<p>Matthews Horsleys answer is the fastest method which doesn't change behaviour depending on which version of windows your program is running on. However, it can be even faster by creating the regex once, and using RegexOptions.Compiled. I also added the option of inserting a string comparer so you can ignore case if needed, and improved readability a bit.</p>\n\n<pre><code> public static IEnumerable&lt;T&gt; OrderByNatural&lt;T&gt;(this IEnumerable&lt;T&gt; items, Func&lt;T, string&gt; selector, StringComparer stringComparer = null)\n {\n var regex = new Regex(@\"\\d+\", RegexOptions.Compiled);\n\n int maxDigits = items\n .SelectMany(i =&gt; regex.Matches(selector(i)).Cast&lt;Match&gt;().Select(digitChunk =&gt; (int?)digitChunk.Value.Length))\n .Max() ?? 0;\n\n return items.OrderBy(i =&gt; regex.Replace(selector(i), match =&gt; match.Value.PadLeft(maxDigits, '0')), stringComparer ?? StringComparer.CurrentCulture);\n }\n</code></pre>\n\n<p>Use by</p>\n\n<pre><code>var sortedEmployees = employees.OrderByNatural(emp =&gt; emp.Name);\n</code></pre>\n\n<p>This takes 450ms to sort 100,000 strings compared to 300ms for the default .net string comparison - pretty fast!</p>\n" }, { "answer_id": 26004132, "author": "Voxpire", "author_id": 2203880, "author_profile": "https://Stackoverflow.com/users/2203880", "pm_score": 1, "selected": false, "text": "<p>Expanding on a couple of the previous answers and making use of extension methods, I came up with the following that doesn't have the caveats of potential multiple enumerable enumeration, or performance issues concerned with using multiple regex objects, or calling regex needlessly, that being said, it does use ToList(), which can negate the benefits in larger collections.</p>\n\n<p>The selector supports generic typing to allow any delegate to be assigned, the elements in the source collection are mutated by the selector, then converted to strings with ToString().</p>\n\n<pre><code> private static readonly Regex _NaturalOrderExpr = new Regex(@\"\\d+\", RegexOptions.Compiled);\n\n public static IEnumerable&lt;TSource&gt; OrderByNatural&lt;TSource, TKey&gt;(\n this IEnumerable&lt;TSource&gt; source, Func&lt;TSource, TKey&gt; selector)\n {\n int max = 0;\n\n var selection = source.Select(\n o =&gt;\n {\n var v = selector(o);\n var s = v != null ? v.ToString() : String.Empty;\n\n if (!String.IsNullOrWhiteSpace(s))\n {\n var mc = _NaturalOrderExpr.Matches(s);\n\n if (mc.Count &gt; 0)\n {\n max = Math.Max(max, mc.Cast&lt;Match&gt;().Max(m =&gt; m.Value.Length));\n }\n }\n\n return new\n {\n Key = o,\n Value = s\n };\n }).ToList();\n\n return\n selection.OrderBy(\n o =&gt;\n String.IsNullOrWhiteSpace(o.Value) ? o.Value : _NaturalOrderExpr.Replace(o.Value, m =&gt; m.Value.PadLeft(max, '0')))\n .Select(o =&gt; o.Key);\n }\n\n public static IEnumerable&lt;TSource&gt; OrderByDescendingNatural&lt;TSource, TKey&gt;(\n this IEnumerable&lt;TSource&gt; source, Func&lt;TSource, TKey&gt; selector)\n {\n int max = 0;\n\n var selection = source.Select(\n o =&gt;\n {\n var v = selector(o);\n var s = v != null ? v.ToString() : String.Empty;\n\n if (!String.IsNullOrWhiteSpace(s))\n {\n var mc = _NaturalOrderExpr.Matches(s);\n\n if (mc.Count &gt; 0)\n {\n max = Math.Max(max, mc.Cast&lt;Match&gt;().Max(m =&gt; m.Value.Length));\n }\n }\n\n return new\n {\n Key = o,\n Value = s\n };\n }).ToList();\n\n return\n selection.OrderByDescending(\n o =&gt;\n String.IsNullOrWhiteSpace(o.Value) ? o.Value : _NaturalOrderExpr.Replace(o.Value, m =&gt; m.Value.PadLeft(max, '0')))\n .Select(o =&gt; o.Key);\n }\n</code></pre>\n" }, { "answer_id": 40290779, "author": "Picsonald", "author_id": 6014732, "author_profile": "https://Stackoverflow.com/users/6014732", "pm_score": 4, "selected": false, "text": "<p>This is my code to sort a string having both alpha and numeric characters.</p>\n<p>First, this extension method:</p>\n<pre><code>public static IEnumerable&lt;string&gt; AlphanumericSort(this IEnumerable&lt;string&gt; me)\n{\n return me.OrderBy(x =&gt; Regex.Replace(x, @&quot;\\d+&quot;, m =&gt; m.Value.PadLeft(50, '0')));\n}\n</code></pre>\n<p>Then, simply use it anywhere in your code like this:</p>\n<pre><code>List&lt;string&gt; test = new List&lt;string&gt;() { &quot;The 1st&quot;, &quot;The 12th&quot;, &quot;The 2nd&quot; };\ntest = test.AlphanumericSort();\n</code></pre>\n<p>How does it works ? By replaceing with zeros:</p>\n<pre><code> Original | Regex Replace | The | Returned\n List | Apply PadLeft | Sorting | List\n | | |\n &quot;The 1st&quot; | &quot;The 001st&quot; | &quot;The 001st&quot; | &quot;The 1st&quot;\n &quot;The 12th&quot; | &quot;The 012th&quot; | &quot;The 002nd&quot; | &quot;The 2nd&quot;\n &quot;The 2nd&quot; | &quot;The 002nd&quot; | &quot;The 012th&quot; | &quot;The 12th&quot;\n</code></pre>\n<p>Works with multiples numbers:</p>\n<pre><code> Alphabetical Sorting | Alphanumeric Sorting\n |\n &quot;Page 21, Line 42&quot; | &quot;Page 3, Line 7&quot;\n &quot;Page 21, Line 5&quot; | &quot;Page 3, Line 32&quot;\n &quot;Page 3, Line 32&quot; | &quot;Page 21, Line 5&quot;\n &quot;Page 3, Line 7&quot; | &quot;Page 21, Line 42&quot;\n</code></pre>\n<p>Hope that's will help.</p>\n" }, { "answer_id": 41168219, "author": "Drew Noakes", "author_id": 24874, "author_profile": "https://Stackoverflow.com/users/24874", "pm_score": 3, "selected": false, "text": "<p>Here's a relatively simple example that doesn't use P/Invoke and avoids any allocation during execution.</p>\n<p>Feel free to use the code from here, or if it's easier there's a NuGet package:</p>\n<p><a href=\"https://www.nuget.org/packages/NaturalSort\" rel=\"nofollow noreferrer\">https://www.nuget.org/packages/NaturalSort</a></p>\n<p><a href=\"https://github.com/drewnoakes/natural-sort\" rel=\"nofollow noreferrer\">https://github.com/drewnoakes/natural-sort</a></p>\n<pre class=\"lang-cs prettyprint-override\"><code>internal sealed class NaturalStringComparer : IComparer&lt;string&gt;\n{\n public static NaturalStringComparer Instance { get; } = new NaturalStringComparer();\n\n public int Compare(string x, string y)\n {\n // sort nulls to the start\n if (x == null)\n return y == null ? 0 : -1;\n if (y == null)\n return 1;\n\n var ix = 0;\n var iy = 0;\n\n while (true)\n {\n // sort shorter strings to the start\n if (ix &gt;= x.Length)\n return iy &gt;= y.Length ? 0 : -1;\n if (iy &gt;= y.Length)\n return 1;\n\n var cx = x[ix];\n var cy = y[iy];\n\n int result;\n if (char.IsDigit(cx) &amp;&amp; char.IsDigit(cy))\n result = CompareInteger(x, y, ref ix, ref iy);\n else\n result = cx.CompareTo(y[iy]);\n\n if (result != 0)\n return result;\n\n ix++;\n iy++;\n }\n }\n\n private static int CompareInteger(string x, string y, ref int ix, ref int iy)\n {\n var lx = GetNumLength(x, ix);\n var ly = GetNumLength(y, iy);\n\n // shorter number first (note, doesn't handle leading zeroes)\n if (lx != ly)\n return lx.CompareTo(ly);\n\n for (var i = 0; i &lt; lx; i++)\n {\n var result = x[ix++].CompareTo(y[iy++]);\n if (result != 0)\n return result;\n }\n\n return 0;\n }\n\n private static int GetNumLength(string s, int i)\n {\n var length = 0;\n while (i &lt; s.Length &amp;&amp; char.IsDigit(s[i++]))\n length++;\n return length;\n }\n}\n</code></pre>\n<p>It doesn't ignore leading zeroes, so <code>01</code> comes after <code>2</code>.</p>\n<p>Corresponding unit test:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public class NumericStringComparerTests\n{\n [Fact]\n public void OrdersCorrectly()\n {\n AssertEqual(&quot;&quot;, &quot;&quot;);\n AssertEqual(null, null);\n AssertEqual(&quot;Hello&quot;, &quot;Hello&quot;);\n AssertEqual(&quot;Hello123&quot;, &quot;Hello123&quot;);\n AssertEqual(&quot;123&quot;, &quot;123&quot;);\n AssertEqual(&quot;123Hello&quot;, &quot;123Hello&quot;);\n\n AssertOrdered(&quot;&quot;, &quot;Hello&quot;);\n AssertOrdered(null, &quot;Hello&quot;);\n AssertOrdered(&quot;Hello&quot;, &quot;Hello1&quot;);\n AssertOrdered(&quot;Hello123&quot;, &quot;Hello124&quot;);\n AssertOrdered(&quot;Hello123&quot;, &quot;Hello133&quot;);\n AssertOrdered(&quot;Hello123&quot;, &quot;Hello223&quot;);\n AssertOrdered(&quot;123&quot;, &quot;124&quot;);\n AssertOrdered(&quot;123&quot;, &quot;133&quot;);\n AssertOrdered(&quot;123&quot;, &quot;223&quot;);\n AssertOrdered(&quot;123&quot;, &quot;1234&quot;);\n AssertOrdered(&quot;123&quot;, &quot;2345&quot;);\n AssertOrdered(&quot;0&quot;, &quot;1&quot;);\n AssertOrdered(&quot;123Hello&quot;, &quot;124Hello&quot;);\n AssertOrdered(&quot;123Hello&quot;, &quot;133Hello&quot;);\n AssertOrdered(&quot;123Hello&quot;, &quot;223Hello&quot;);\n AssertOrdered(&quot;123Hello&quot;, &quot;1234Hello&quot;);\n }\n\n private static void AssertEqual(string x, string y)\n {\n Assert.Equal(0, NaturalStringComparer.Instance.Compare(x, y));\n Assert.Equal(0, NaturalStringComparer.Instance.Compare(y, x));\n }\n\n private static void AssertOrdered(string x, string y)\n {\n Assert.Equal(-1, NaturalStringComparer.Instance.Compare(x, y));\n Assert.Equal( 1, NaturalStringComparer.Instance.Compare(y, x));\n }\n}\n</code></pre>\n" }, { "answer_id": 47400729, "author": "Tom Pažourek", "author_id": 108374, "author_profile": "https://Stackoverflow.com/users/108374", "pm_score": 2, "selected": false, "text": "<p>I've actually implemented it as an extension method on the <code>StringComparer</code> so that you could do for example:</p>\n<ul>\n<li><code>StringComparer.CurrentCulture.WithNaturalSort()</code> or</li>\n<li><code>StringComparer.OrdinalIgnoreCase.WithNaturalSort()</code>.</li>\n</ul>\n<p>The resulting <code>IComparer&lt;string&gt;</code> can be used in all places like <code>OrderBy</code>, <code>OrderByDescending</code>, <code>ThenBy</code>, <code>ThenByDescending</code>, <code>SortedSet&lt;string&gt;</code>, etc. And you can still easily tweak case sensitivity, culture, etc.</p>\n<p>The implementation is fairly trivial and it should perform quite well even on large sequences.</p>\n<hr />\n<p>I've also published it as a tiny <strong><a href=\"https://www.nuget.org/packages/NaturalSort.Extension/\" rel=\"nofollow noreferrer\">NuGet package</a></strong>, so you can just do:</p>\n<pre><code>Install-Package NaturalSort.Extension\n</code></pre>\n<p>The code including XML documentation comments and <a href=\"https://github.com/tompazourek/NaturalSort.Extension/blob/master/tests/NaturalSort.Extension.Tests/NaturalSortComparerTests.cs\" rel=\"nofollow noreferrer\">suite of tests</a> is available in <a href=\"https://github.com/tompazourek/NaturalSort.Extension\" rel=\"nofollow noreferrer\">the NaturalSort.Extension <strong>GitHub repository</strong></a>.</p>\n<hr />\n<p>The entire code is this (if you cannot use C# 7 yet, just install the NuGet package):</p>\n<pre><code>public static class StringComparerNaturalSortExtension\n{\n public static IComparer&lt;string&gt; WithNaturalSort(this StringComparer stringComparer) =&gt; new NaturalSortComparer(stringComparer);\n\n private class NaturalSortComparer : IComparer&lt;string&gt;\n {\n public NaturalSortComparer(StringComparer stringComparer)\n {\n _stringComparer = stringComparer;\n }\n\n private readonly StringComparer _stringComparer;\n private static readonly Regex NumberSequenceRegex = new Regex(@&quot;(\\d+)&quot;, RegexOptions.Compiled | RegexOptions.CultureInvariant);\n private static string[] Tokenize(string s) =&gt; s == null ? new string[] { } : NumberSequenceRegex.Split(s);\n private static ulong ParseNumberOrZero(string s) =&gt; ulong.TryParse(s, NumberStyles.None, CultureInfo.InvariantCulture, out var result) ? result : 0;\n\n public int Compare(string s1, string s2)\n {\n var tokens1 = Tokenize(s1);\n var tokens2 = Tokenize(s2);\n\n var zipCompare = tokens1.Zip(tokens2, TokenCompare).FirstOrDefault(x =&gt; x != 0);\n if (zipCompare != 0)\n return zipCompare;\n\n var lengthCompare = tokens1.Length.CompareTo(tokens2.Length);\n return lengthCompare;\n }\n \n private int TokenCompare(string token1, string token2)\n {\n var number1 = ParseNumberOrZero(token1);\n var number2 = ParseNumberOrZero(token2);\n\n var numberCompare = number1.CompareTo(number2);\n if (numberCompare != 0)\n return numberCompare;\n\n var stringCompare = _stringComparer.Compare(token1, token2);\n return stringCompare;\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 49982177, "author": "mshsayem", "author_id": 152349, "author_profile": "https://Stackoverflow.com/users/152349", "pm_score": 2, "selected": false, "text": "<p>Here is a naive one-line regex-less LINQ way (borrowed from python):</p>\n\n<pre><code>var alphaStrings = new List&lt;string&gt;() { \"10\",\"2\",\"3\",\"4\",\"50\",\"11\",\"100\",\"a12\",\"b12\" };\nvar orderedString = alphaStrings.OrderBy(g =&gt; new Tuple&lt;int, string&gt;(g.ToCharArray().All(char.IsDigit)? int.Parse(g) : int.MaxValue, g));\n// Order Now: [\"2\",\"3\",\"4\",\"10\",\"11\",\"50\",\"100\",\"a12\",\"b12\"]\n</code></pre>\n" }, { "answer_id": 52318194, "author": "Oliver", "author_id": 284741, "author_profile": "https://Stackoverflow.com/users/284741", "pm_score": 2, "selected": false, "text": "<p>Inspired by Michael Parker's solution, here is an <code>IComparer</code> implementation that you can drop in to any of the linq ordering methods:</p>\n\n<pre><code>private class NaturalStringComparer : IComparer&lt;string&gt;\n{\n public int Compare(string left, string right)\n {\n int max = new[] { left, right }\n .SelectMany(x =&gt; Regex.Matches(x, @\"\\d+\").Cast&lt;Match&gt;().Select(y =&gt; (int?)y.Value.Length))\n .Max() ?? 0;\n\n var leftPadded = Regex.Replace(left, @\"\\d+\", m =&gt; m.Value.PadLeft(max, '0'));\n var rightPadded = Regex.Replace(right, @\"\\d+\", m =&gt; m.Value.PadLeft(max, '0'));\n\n return string.Compare(leftPadded, rightPadded);\n }\n}\n</code></pre>\n" }, { "answer_id": 53323586, "author": "girishkatta9", "author_id": 2501245, "author_profile": "https://Stackoverflow.com/users/2501245", "pm_score": -1, "selected": false, "text": "<p>Let me explain my problem and how i was able to solve it. </p>\n\n<p>Problem:- Sort files based on FileName from FileInfo objects which are retrieved from a Directory.</p>\n\n<p>Solution:- I selected the file names from FileInfo and trimed the \".png\" part of the file name. Now, just do List.Sort(), which sorts the filenames in Natural sorting order. Based on my testing i found that having .png messes up sorting order. Have a look at the below code </p>\n\n<pre><code>var imageNameList = new DirectoryInfo(@\"C:\\Temp\\Images\").GetFiles(\"*.png\").Select(x =&gt;x.Name.Substring(0, x.Name.Length - 4)).ToList();\nimageNameList.Sort();\n</code></pre>\n" }, { "answer_id": 58328837, "author": "Kelly Elton", "author_id": 222054, "author_profile": "https://Stackoverflow.com/users/222054", "pm_score": 1, "selected": false, "text": "<p>A version that's easier to read/maintain.</p>\n\n<pre><code>public class NaturalStringComparer : IComparer&lt;string&gt;\n{\n public static NaturalStringComparer Instance { get; } = new NaturalStringComparer();\n\n public int Compare(string x, string y) {\n const int LeftIsSmaller = -1;\n const int RightIsSmaller = 1;\n const int Equal = 0;\n\n var leftString = x;\n var rightString = y;\n\n var stringComparer = CultureInfo.CurrentCulture.CompareInfo;\n\n int rightIndex;\n int leftIndex;\n\n for (leftIndex = 0, rightIndex = 0;\n leftIndex &lt; leftString.Length &amp;&amp; rightIndex &lt; rightString.Length;\n leftIndex++, rightIndex++) {\n var leftChar = leftString[leftIndex];\n var rightChar = rightString[leftIndex];\n\n var leftIsNumber = char.IsNumber(leftChar);\n var rightIsNumber = char.IsNumber(rightChar);\n\n if (!leftIsNumber &amp;&amp; !rightIsNumber) {\n var result = stringComparer.Compare(leftString, leftIndex, 1, rightString, leftIndex, 1);\n if (result != 0) return result;\n } else if (leftIsNumber &amp;&amp; !rightIsNumber) {\n return LeftIsSmaller;\n } else if (!leftIsNumber &amp;&amp; rightIsNumber) {\n return RightIsSmaller;\n } else {\n var leftNumberLength = NumberLength(leftString, leftIndex, out var leftNumber);\n var rightNumberLength = NumberLength(rightString, rightIndex, out var rightNumber);\n\n if (leftNumberLength &lt; rightNumberLength) {\n return LeftIsSmaller;\n } else if (leftNumberLength &gt; rightNumberLength) {\n return RightIsSmaller;\n } else {\n if(leftNumber &lt; rightNumber) {\n return LeftIsSmaller;\n } else if(leftNumber &gt; rightNumber) {\n return RightIsSmaller;\n }\n }\n }\n }\n\n if (leftString.Length &lt; rightString.Length) {\n return LeftIsSmaller;\n } else if(leftString.Length &gt; rightString.Length) {\n return RightIsSmaller;\n }\n\n return Equal;\n }\n\n public int NumberLength(string str, int offset, out int number) {\n if (string.IsNullOrWhiteSpace(str)) throw new ArgumentNullException(nameof(str));\n if (offset &gt;= str.Length) throw new ArgumentOutOfRangeException(nameof(offset), offset, \"Offset must be less than the length of the string.\");\n\n var currentOffset = offset;\n\n var curChar = str[currentOffset];\n\n if (!char.IsNumber(curChar))\n throw new ArgumentException($\"'{curChar}' is not a number.\", nameof(offset));\n\n int length = 1;\n\n var numberString = string.Empty;\n\n for (currentOffset = offset + 1;\n currentOffset &lt; str.Length;\n currentOffset++, length++) {\n\n curChar = str[currentOffset];\n numberString += curChar;\n\n if (!char.IsNumber(curChar)) {\n number = int.Parse(numberString);\n\n return length;\n }\n }\n\n number = int.Parse(numberString);\n\n return length;\n }\n}\n</code></pre>\n" }, { "answer_id": 66354540, "author": "Thomas Levesque", "author_id": 98713, "author_profile": "https://Stackoverflow.com/users/98713", "pm_score": 3, "selected": false, "text": "<p>Here's a version for .NET Core 2.1+ / .NET 5.0+, using spans to avoid allocations</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public class NaturalSortStringComparer : IComparer&lt;string&gt;\n{\n public static NaturalSortStringComparer Ordinal { get; } = new NaturalSortStringComparer(StringComparison.Ordinal);\n public static NaturalSortStringComparer OrdinalIgnoreCase { get; } = new NaturalSortStringComparer(StringComparison.OrdinalIgnoreCase);\n public static NaturalSortStringComparer CurrentCulture { get; } = new NaturalSortStringComparer(StringComparison.CurrentCulture);\n public static NaturalSortStringComparer CurrentCultureIgnoreCase { get; } = new NaturalSortStringComparer(StringComparison.CurrentCultureIgnoreCase);\n public static NaturalSortStringComparer InvariantCulture { get; } = new NaturalSortStringComparer(StringComparison.InvariantCulture);\n public static NaturalSortStringComparer InvariantCultureIgnoreCase { get; } = new NaturalSortStringComparer(StringComparison.InvariantCultureIgnoreCase);\n\n private readonly StringComparison _comparison;\n\n public NaturalSortStringComparer(StringComparison comparison)\n {\n _comparison = comparison;\n }\n\n public int Compare(string x, string y)\n {\n // Let string.Compare handle the case where x or y is null\n if (x is null || y is null)\n return string.Compare(x, y, _comparison);\n\n var xSegments = GetSegments(x);\n var ySegments = GetSegments(y);\n\n while (xSegments.MoveNext() &amp;&amp; ySegments.MoveNext())\n {\n int cmp;\n\n // If they're both numbers, compare the value\n if (xSegments.CurrentIsNumber &amp;&amp; ySegments.CurrentIsNumber)\n {\n var xValue = long.Parse(xSegments.Current);\n var yValue = long.Parse(ySegments.Current);\n cmp = xValue.CompareTo(yValue);\n if (cmp != 0)\n return cmp;\n }\n // If x is a number and y is not, x is &quot;lesser than&quot; y\n else if (xSegments.CurrentIsNumber)\n {\n return -1;\n }\n // If y is a number and x is not, x is &quot;greater than&quot; y\n else if (ySegments.CurrentIsNumber)\n {\n return 1;\n }\n\n // OK, neither are number, compare the segments as text\n cmp = xSegments.Current.CompareTo(ySegments.Current, _comparison);\n if (cmp != 0)\n return cmp;\n }\n\n // At this point, either all segments are equal, or one string is shorter than the other\n\n // If x is shorter, it's &quot;lesser than&quot; y\n if (x.Length &lt; y.Length)\n return -1;\n // If x is longer, it's &quot;greater than&quot; y\n if (x.Length &gt; y.Length)\n return 1;\n\n // If they have the same length, they're equal\n return 0;\n }\n\n private static StringSegmentEnumerator GetSegments(string s) =&gt; new StringSegmentEnumerator(s);\n\n private struct StringSegmentEnumerator\n {\n private readonly string _s;\n private int _start;\n private int _length;\n\n public StringSegmentEnumerator(string s)\n {\n _s = s;\n _start = -1;\n _length = 0;\n CurrentIsNumber = false;\n }\n\n public ReadOnlySpan&lt;char&gt; Current =&gt; _s.AsSpan(_start, _length);\n \n public bool CurrentIsNumber { get; private set; }\n\n public bool MoveNext()\n {\n var currentPosition = _start &gt;= 0\n ? _start + _length\n : 0;\n\n if (currentPosition &gt;= _s.Length)\n return false;\n\n int start = currentPosition;\n bool isFirstCharDigit = Char.IsDigit(_s[currentPosition]);\n\n while (++currentPosition &lt; _s.Length &amp;&amp; Char.IsDigit(_s[currentPosition]) == isFirstCharDigit)\n {\n }\n\n _start = start;\n _length = currentPosition - start;\n CurrentIsNumber = isFirstCharDigit;\n\n return true;\n }\n }\n}\n</code></pre>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/248603", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26327/" ]
Anyone have a good resource or provide a sample of a natural order sort in C# for an `FileInfo` array? I am implementing the `IComparer` interface in my sorts.
The easiest thing to do is just P/Invoke the built-in function in Windows, and use it as the comparison function in your `IComparer`: ``` [DllImport("shlwapi.dll", CharSet = CharSet.Unicode)] private static extern int StrCmpLogicalW(string psz1, string psz2); ``` Michael Kaplan has some [examples of how this function works here](http://www.siao2.com/2006/10/01/778990.aspx), and the changes that were made for Vista to make it work more intuitively. The plus side of this function is that it will have the same behaviour as the version of Windows it runs on, however this does mean that it differs between versions of Windows so you need to consider whether this is a problem for you. So a complete implementation would be something like: ``` [SuppressUnmanagedCodeSecurity] internal static class SafeNativeMethods { [DllImport("shlwapi.dll", CharSet = CharSet.Unicode)] public static extern int StrCmpLogicalW(string psz1, string psz2); } public sealed class NaturalStringComparer : IComparer<string> { public int Compare(string a, string b) { return SafeNativeMethods.StrCmpLogicalW(a, b); } } public sealed class NaturalFileInfoNameComparer : IComparer<FileInfo> { public int Compare(FileInfo a, FileInfo b) { return SafeNativeMethods.StrCmpLogicalW(a.Name, b.Name); } } ```
248,615
<p>I have a private const int defined in a C# class. I want compilation to fail with an error if the value of this int mod 3 != 0. How can I accomplish this?</p>
[ { "answer_id": 248636, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 2, "selected": false, "text": "<p>Although there is an <a href=\"http://msdn.microsoft.com/en-us/library/x5hedts0.aspx\" rel=\"nofollow noreferrer\"><em>#error</em></a> pre-processor directive for generating compile-time errors, there is no way for it to be based on the existence of a const value. It only works with compiler symbols, like \"DEBUG\", for which a value can't be assigned. </p>\n" }, { "answer_id": 248637, "author": "Timothy Khouri", "author_id": 11917, "author_profile": "https://Stackoverflow.com/users/11917", "pm_score": -1, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>if (MY_CONST % 3 != 0) { int compilerError = 1 / 0; }\n</code></pre>\n" }, { "answer_id": 248645, "author": "Timothy Khouri", "author_id": 11917, "author_profile": "https://Stackoverflow.com/users/11917", "pm_score": 1, "selected": false, "text": "<p>Sorry, that code I said below won't work, but this will :)</p>\n\n<pre><code>int pointless = 1 / (MY_CONST % 3);\n</code></pre>\n\n<p>The reason why this will work is because you'll get a compile time, \"can't devide by zero\" error. Your \"MY_CONST\" field will have to be anything that (once modded by 3) will not be equal to zero.</p>\n" }, { "answer_id": 248657, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 3, "selected": true, "text": "<p>Timothy Khouri almost got it. It should be this:</p>\n\n<pre><code>int compilerError = 1 / (MY_CONST % 3 == 0 ? 1 : 0);\n</code></pre>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/248615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a private const int defined in a C# class. I want compilation to fail with an error if the value of this int mod 3 != 0. How can I accomplish this?
Timothy Khouri almost got it. It should be this: ``` int compilerError = 1 / (MY_CONST % 3 == 0 ? 1 : 0); ```
248,617
<p>I'm wondering if it is possible to add methods in main program to an existing class defined in header file. For example: There is <code>class CFun</code> defined in file <code>CFun.hpp</code>, but in our <code>party.cpp</code> we want to add a method <code>void hello() {cout &lt;&lt; "hello" &lt;&lt; endl;};</code>without editing <code>CFun.hpp</code></p> <p>Obviously (unfortunately) construction:</p> <pre><code>#include "CFun.hpp" class CFun { public: void hello() {cout &lt;&lt; "hello" &lt;&lt; endl;}; }; </code></pre> <p>doesn't work returning an error <code>Multiple declaration for 'CFun'</code></p> <p>Is it possible to make it work without class inheritance?</p>
[ { "answer_id": 248622, "author": "Paul Nathan", "author_id": 26227, "author_profile": "https://Stackoverflow.com/users/26227", "pm_score": 0, "selected": false, "text": "<p>Not to my knowledge. Although, you could do some kind of jury-rigging and make a namespace-y solution.</p>\n" }, { "answer_id": 248643, "author": "Eclipse", "author_id": 8701, "author_profile": "https://Stackoverflow.com/users/8701", "pm_score": 4, "selected": true, "text": "<p>No, but you could add a method that takes a reference/pointer to a CFun class - you just won't have access to private data:</p>\n\n<pre><code>void Hello(CFun &amp;fun)\n{\n cout &lt;&lt; \"hello\" &lt;&lt; endl;\n}\n</code></pre>\n\n<p>This is probably the best you'll be able to do. As pointed out by litb - this function has to be in the same namespace as CFun. Fortunately, namespaces, unlike classes, can be added to in multiple places.</p>\n" }, { "answer_id": 248644, "author": "Dima", "author_id": 13313, "author_profile": "https://Stackoverflow.com/users/13313", "pm_score": 2, "selected": false, "text": "<p>No, that is not possible. There can only be one definition of any particular class, and it has to be a complete definition, meaning that you cannot have partial definitions in different places, adding members to the class.</p>\n\n<p>If you need to add a member function to a class, then either you have to change the class definition (edit CFun.hpp), or derive a new class from <code>CFun</code> and put <code>hello()</code> there.</p>\n" }, { "answer_id": 248671, "author": "Eclipse", "author_id": 8701, "author_profile": "https://Stackoverflow.com/users/8701", "pm_score": 1, "selected": false, "text": "<p>After thinking about it, you could do something terrible: Find some function in CFun that has a return type that you want, and is only mention once in the entire header. Let's say <code>void GoodBye()</code>.</p>\n\n<p>Now create a file CFunWrapper.hpp with this content:</p>\n\n<pre><code>#define GoodBye() Hello() { cout &lt;&lt; \"hello\" &lt;&lt; endl; } void GoodBye()\n#include \"CFun.hpp\"\n#undef GoodBye\n</code></pre>\n\n<p>Then only ever include CFunWrapper.hpp instead of CFun.hpp.</p>\n\n<p>But don't do this, unless there's some really good reason to do so. It's extremely prone to breaking, and may not even be possible, depending on the contents of CFun.hpp.</p>\n" }, { "answer_id": 248676, "author": "Harper Shelby", "author_id": 21196, "author_profile": "https://Stackoverflow.com/users/21196", "pm_score": 2, "selected": false, "text": "<p>The closest analog to that sort of construct (adding functionality to predefined classes) in C++ is the Decorator pattern. It's not exactly what you're after, but it may allow you to do what you need.</p>\n" }, { "answer_id": 324915, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<pre><code>class Party : class CFun\n</code></pre>\n\n<p>(your party.cpp)</p>\n\n<p>inherits CFun stuff, including hello() function.</p>\n\n<p>So...</p>\n\n<pre><code>Party p;\np.hello();\n</code></pre>\n\n<p>No?</p>\n" }, { "answer_id": 7432448, "author": "Tamzin Blake", "author_id": 650551, "author_profile": "https://Stackoverflow.com/users/650551", "pm_score": 2, "selected": false, "text": "<p>This seems like an obvious use-case for inheritance. Define a new class:</p>\n\n<pre><code>#include \"CFun.hpp\"\n\nclass CFun2 : public CFun\n{\n public:\n void hello() {cout &lt;&lt; \"hello\" &lt;&lt; endl;};\n};\n</code></pre>\n\n<p>Then use <code>CFun2</code> instead of <code>CFun</code> in your source code.</p>\n" }, { "answer_id": 14435792, "author": "Timo", "author_id": 1996572, "author_profile": "https://Stackoverflow.com/users/1996572", "pm_score": 3, "selected": false, "text": "<p>You can redefine the class like this:</p>\n\n<pre><code>#define CFun CLessFun\n#include \"CFun.hpp\"\n#undef CFun\n\nclass CFun : CLessFun\n{\n public:\n void hello() {cout &lt;&lt; \"hello\" &lt;&lt; endl;};\n};\n</code></pre>\n\n<p>Put this in a new header file <code>CMoreFun.hpp</code> and include that instead of <code>CFun.hpp</code></p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/248617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32312/" ]
I'm wondering if it is possible to add methods in main program to an existing class defined in header file. For example: There is `class CFun` defined in file `CFun.hpp`, but in our `party.cpp` we want to add a method `void hello() {cout << "hello" << endl;};`without editing `CFun.hpp` Obviously (unfortunately) construction: ``` #include "CFun.hpp" class CFun { public: void hello() {cout << "hello" << endl;}; }; ``` doesn't work returning an error `Multiple declaration for 'CFun'` Is it possible to make it work without class inheritance?
No, but you could add a method that takes a reference/pointer to a CFun class - you just won't have access to private data: ``` void Hello(CFun &fun) { cout << "hello" << endl; } ``` This is probably the best you'll be able to do. As pointed out by litb - this function has to be in the same namespace as CFun. Fortunately, namespaces, unlike classes, can be added to in multiple places.
248,642
<p>I have a GridView control that I am dynamically creating at runtime. I am creating all the columns like this.</p> <pre><code>foreach (GridColumnConfig column in columns) { BoundField boundField = new BoundField(); boundField.HeaderText = column.Title; boundField.DataField = column.FieldName; boundField.SortExpression = column.FieldName; boundField.ItemStyle.Wrap = false; boundField.ItemStyle.Width = new Unit(column.Width, UnitType.Pixel); boundField.ItemStyle.HorizontalAlign = TextToAlign(column.Align); m_GenericListView.Grid.Columns.Add(boundField); } </code></pre> <p>However even though I have specified the item not to wrap text it still does so in IE6. In FireFox it just creates a very wide column which is probably not what either, even though the width has been specified. </p> <p>Is there any way to really control these widths and wrapping columns in a GridView ?</p>
[ { "answer_id": 248656, "author": "Paul Prewett", "author_id": 15751, "author_profile": "https://Stackoverflow.com/users/15751", "pm_score": 1, "selected": false, "text": "<p>The word-wrap CSS style works for me when I want to control wrapping. Here's a discussion that pretty well covers it.</p>\n\n<p><a href=\"http://bytes.com/forum/thread627827.html\" rel=\"nofollow noreferrer\">http://bytes.com/forum/thread627827.html</a></p>\n" }, { "answer_id": 8760816, "author": "Alex Z", "author_id": 1030029, "author_profile": "https://Stackoverflow.com/users/1030029", "pm_score": 0, "selected": false, "text": "<p>you can add this to the gridview - \n Style=\"white-space: nowrap\" </p>\n\n<p>Gridview doesnt have a property called style, but you can add it and it will work.</p>\n\n<p>Or you can declare a CSS class and assign it to the gridview</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/248642", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27294/" ]
I have a GridView control that I am dynamically creating at runtime. I am creating all the columns like this. ``` foreach (GridColumnConfig column in columns) { BoundField boundField = new BoundField(); boundField.HeaderText = column.Title; boundField.DataField = column.FieldName; boundField.SortExpression = column.FieldName; boundField.ItemStyle.Wrap = false; boundField.ItemStyle.Width = new Unit(column.Width, UnitType.Pixel); boundField.ItemStyle.HorizontalAlign = TextToAlign(column.Align); m_GenericListView.Grid.Columns.Add(boundField); } ``` However even though I have specified the item not to wrap text it still does so in IE6. In FireFox it just creates a very wide column which is probably not what either, even though the width has been specified. Is there any way to really control these widths and wrapping columns in a GridView ?
The word-wrap CSS style works for me when I want to control wrapping. Here's a discussion that pretty well covers it. <http://bytes.com/forum/thread627827.html>
248,667
<p>Objective: take a UIImage, crop out a square in the middle, change size of square to 320x320 pixels, slice up the image into 16 80x80 images, save the 16 images in an array.</p> <p>Here's my code:</p> <pre><code>CGImageRef originalImage, resizedImage, finalImage, tmp; float imgWidth, imgHeight, diff; UIImage *squareImage, *playImage; NSMutableArray *tileImgArray; int r, c; originalImage = [image CGImage]; imgWidth = image.size.width; imgHeight = image.size.height; diff = fabs(imgWidth - imgHeight); if(imgWidth &gt; imgHeight){ resizedImage = CGImageCreateWithImageInRect(originalImage, CGRectMake(floor(diff/2), 0, imgHeight, imgHeight)); }else{ resizedImage = CGImageCreateWithImageInRect(originalImage, CGRectMake(0, floor(diff/2), imgWidth, imgWidth)); } CGImageRelease(originalImage); squareImage = [UIImage imageWithCGImage:resizedImage]; if(squareImage.size.width != squareImage.size.height){ NSLog(@"image cutout error!"); //*code to return to main menu of app, irrelevant here }else{ float newDim = squareImage.size.width; if(newDim != 320.0){ CGSize finalSize = CGSizeMake(320.0, 320.0); UIGraphicsBeginImageContext(finalSize); [squareImage drawInRect:CGRectMake(0, 0, finalSize.width, finalSize.height)]; playImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); }else{ playImage = squareImage; } } finalImage = [playImage CGImage]; tileImgArray = [NSMutableArray arrayWithCapacity:0]; for(int i = 0; i &lt; 16; i++){ r = i/4; c = i%4; //* tmp = CGImageCreateWithImageInRect(finalImage, CGRectMake(c*tileSize, r*tileSize, tileSize, tileSize)); [tileImgArray addObject:[UIImage imageWithCGImage:tmp]]; } </code></pre> <p>The code works correctly when the original (the variable image) has its smaller dimension either bigger or smaller than 320 pixels. When it's exactly 320, the resulting 80x80 images are almost entirely black, some with a few pixels at the edges that may (I can't really tell) be from the original image.</p> <p>I tested by displaying the full image both directly:</p> <pre><code>[UIImage imageWithCGImage:finalImage]; </code></pre> <p>And indirectly:</p> <pre><code>[UIImage imageWithCGImage:CGImageCreateWithImageInRect(finalImage, CGRectMake(0, 0, 320, 320))]; </code></pre> <p>In both cases, the display worked. The problems only arise when I attempt to slice out some part of the image.</p>
[ { "answer_id": 249174, "author": "executor21", "author_id": 30952, "author_profile": "https://Stackoverflow.com/users/30952", "pm_score": 4, "selected": true, "text": "<p>After some more experimentation, I found the following solution (I still don't know why it didn't work as originally written, though.) But anyway, the slicing works after the resize code is put in place even when resizing is unnecessary:</p>\n\n<pre><code>if(newDim != 320.0){\n CGSize finalSize = CGSizeMake(320.0, 320.0);\n UIGraphicsBeginImageContext(finalSize);\n [squareImage drawInRect:CGRectMake(0, 0, finalSize.width, finalSize.height)];\n playImage = UIGraphicsGetImageFromCurrentImageContext();\n UIGraphicsEndImageContext();\n}else{\n CGSize finalSize = CGSizeMake(320.0, 320.0);\n UIGraphicsBeginImageContext(finalSize);\n [squareImage drawInRect:CGRectMake(0, 0, finalSize.width, finalSize.height)];\n playImage = UIGraphicsGetImageFromCurrentImageContext();\n UIGraphicsEndImageContext();\n}\n</code></pre>\n\n<p>Anyone has any clue WHY this is going on?</p>\n\n<p>P.S. Yes, if/else is no longer required here. Removing it <b>before</b> I knew it was going to work would be stupid, though.</p>\n" }, { "answer_id": 962447, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Just out of curiosity, why did you make your mutable array with bound of 0 when you know you're going to put 16 things in it?</p>\n\n<p>Well, aside from that, I've tried the basic techniques you used for resizing and slicing (I did not need to crop, because I'm working with images that are already square) and I'm unable to reproduce your problem in the simulator. You might want to try breaking your code into three separate functions (crop to square, resize, and slice into pieces) and then test the three separately so you can figure out which of the three steps is causing the problems (ie. input images that you've manipulated in a normal graphics program instead of using objective c and then inspect what you get back out!). </p>\n\n<p>I'll attach my versions of the resize and slice functions below, which will hopefully be helpful. It was nice to have your versions to look at, since I didn't have to find all the methods by myself for once. :)</p>\n\n<p>Just as a note, the two dimensional array mentioned is my own class built out of NSMutableArrays, but you could easily implement your own version or use a flat NSMutableArray instead. ;)</p>\n\n<pre><code>// cut the given image into a grid of equally sized smaller images\n// this assumes that the image can be equally divided in the requested increments\n// the images will be stored in the return array in [row][column] order\n+ (TwoDimensionalArray *) chopImageIntoGrid : (UIImage *) originalImage : (int) numberOfRows : (int) numberOfColumns\n{ \n// figure out the size of our tiles\nint tileWidth = originalImage.size.width / numberOfColumns;\nint tileHeight = originalImage.size.height / numberOfRows;\n\n// create our return array\nTwoDimensionalArray * toReturn = [[TwoDimensionalArray alloc] initWithBounds : numberOfRows \n : numberOfColumns];\n\n// get a CGI image version of our image\nCGImageRef cgVersionOfOriginal = [originalImage CGImage];\n\n// loop to chop up each row\nfor(int row = 0; row &lt; numberOfRows ; row++){\n // loop to chop up each individual piece by column\n for (int column = 0; column &lt; numberOfColumns; column++)\n {\n CGImageRef tempImage = \n CGImageCreateWithImageInRect(cgVersionOfOriginal, \n CGRectMake(column * tileWidth, \n row * tileHeight, \n tileWidth, \n tileHeight));\n [toReturn setObjectAt : row : column : [UIImage imageWithCGImage:tempImage]];\n }\n}\n\n// now return the set of images we created\nreturn [toReturn autorelease];\n}\n\n// this method resizes an image to the requested dimentions\n// be a bit careful when using this method, since the resize will not respect\n// the proportions of the image\n+ (UIImage *) resize : (UIImage *) originalImage : (int) newWidth : (int) newHeight\n{ \n// translate the image to the new size\nCGSize newSize = CGSizeMake(newWidth, newHeight); // the new size we want the image to be\nUIGraphicsBeginImageContext(newSize); // downside: this can't go on a background thread, I'm told\n[originalImage drawInRect : CGRectMake(0, 0, newSize.width, newSize.height)];\nUIImage* newImage = UIGraphicsGetImageFromCurrentImageContext(); // get our new image\nUIGraphicsEndImageContext();\n\n// return our brand new image\nreturn newImage;\n}\n</code></pre>\n\n<p>Eva Schiffer</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/248667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30952/" ]
Objective: take a UIImage, crop out a square in the middle, change size of square to 320x320 pixels, slice up the image into 16 80x80 images, save the 16 images in an array. Here's my code: ``` CGImageRef originalImage, resizedImage, finalImage, tmp; float imgWidth, imgHeight, diff; UIImage *squareImage, *playImage; NSMutableArray *tileImgArray; int r, c; originalImage = [image CGImage]; imgWidth = image.size.width; imgHeight = image.size.height; diff = fabs(imgWidth - imgHeight); if(imgWidth > imgHeight){ resizedImage = CGImageCreateWithImageInRect(originalImage, CGRectMake(floor(diff/2), 0, imgHeight, imgHeight)); }else{ resizedImage = CGImageCreateWithImageInRect(originalImage, CGRectMake(0, floor(diff/2), imgWidth, imgWidth)); } CGImageRelease(originalImage); squareImage = [UIImage imageWithCGImage:resizedImage]; if(squareImage.size.width != squareImage.size.height){ NSLog(@"image cutout error!"); //*code to return to main menu of app, irrelevant here }else{ float newDim = squareImage.size.width; if(newDim != 320.0){ CGSize finalSize = CGSizeMake(320.0, 320.0); UIGraphicsBeginImageContext(finalSize); [squareImage drawInRect:CGRectMake(0, 0, finalSize.width, finalSize.height)]; playImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); }else{ playImage = squareImage; } } finalImage = [playImage CGImage]; tileImgArray = [NSMutableArray arrayWithCapacity:0]; for(int i = 0; i < 16; i++){ r = i/4; c = i%4; //* tmp = CGImageCreateWithImageInRect(finalImage, CGRectMake(c*tileSize, r*tileSize, tileSize, tileSize)); [tileImgArray addObject:[UIImage imageWithCGImage:tmp]]; } ``` The code works correctly when the original (the variable image) has its smaller dimension either bigger or smaller than 320 pixels. When it's exactly 320, the resulting 80x80 images are almost entirely black, some with a few pixels at the edges that may (I can't really tell) be from the original image. I tested by displaying the full image both directly: ``` [UIImage imageWithCGImage:finalImage]; ``` And indirectly: ``` [UIImage imageWithCGImage:CGImageCreateWithImageInRect(finalImage, CGRectMake(0, 0, 320, 320))]; ``` In both cases, the display worked. The problems only arise when I attempt to slice out some part of the image.
After some more experimentation, I found the following solution (I still don't know why it didn't work as originally written, though.) But anyway, the slicing works after the resize code is put in place even when resizing is unnecessary: ``` if(newDim != 320.0){ CGSize finalSize = CGSizeMake(320.0, 320.0); UIGraphicsBeginImageContext(finalSize); [squareImage drawInRect:CGRectMake(0, 0, finalSize.width, finalSize.height)]; playImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); }else{ CGSize finalSize = CGSizeMake(320.0, 320.0); UIGraphicsBeginImageContext(finalSize); [squareImage drawInRect:CGRectMake(0, 0, finalSize.width, finalSize.height)]; playImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); } ``` Anyone has any clue WHY this is going on? P.S. Yes, if/else is no longer required here. Removing it **before** I knew it was going to work would be stupid, though.
248,668
<p>I've been trying to code a Perl script to substitute some text on all source files of my project. I'm in need of something like:</p> <pre><code>perl -p -i.bak -e "s/thisgoesout/thisgoesin/gi" *.{cs,aspx,ascx} </code></pre> <p>But that parses <strong>all</strong> the files of a directory <strong>recursively</strong>.</p> <p>I just started a script:</p> <pre><code>use File::Find::Rule; use strict; my @files = (File::Find::Rule-&gt;file()-&gt;name('*.cs','*.aspx','*.ascx')-&gt;in('.')); foreach my $f (@files){ if ($f =~ s/thisgoesout/thisgoesin/gi) { # In-place file editing, or something like that } } </code></pre> <p>But now I'm stuck. Is there a simple way to edit all files in place using Perl?</p> <p>Please note that I don't need to keep a copy of every modified file; I'm have 'em all subversioned =)</p> <p><strong>Update</strong>: I tried this on <a href="http://en.wikipedia.org/wiki/Cygwin" rel="nofollow noreferrer">Cygwin</a>,</p> <pre><code>perl -p -i.bak -e "s/thisgoesout/thisgoesin/gi" {*,*/*,*/*/*}.{cs,aspx,ascx </code></pre> <p>But it looks like my arguments list exploded to the maximum size allowed. In fact, I'm getting very strange errors on Cygwin...</p>
[ { "answer_id": 248680, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 2, "selected": false, "text": "<p>You could use <code>find</code>:</p>\n\n<pre><code>find . -name '*.{cs,aspx,ascx}' | xargs perl -p -i.bak -e \"s/thisgoesout/thisgoesin/gi\"\n</code></pre>\n\n<p>This will list all the filenames recursively, then <code>xargs</code> will read its stdin and run the remainder of the command line with the filenames appended on the end. One nice thing about <code>xargs</code> is it will run the command line more than once if the command line it builds gets too long to run in one go.</p>\n\n<p>Note that I'm not sure whether <code>find</code> completely understands all the shell methods of selecting files, so if the above doesn't work then perhaps try:</p>\n\n<pre><code>find . | grep -E '(cs|aspx|ascx)$' | xargs ...\n</code></pre>\n\n<p>When using pipelines like this, I like to build up the command line and run each part individually before proceeding, to make sure each program is getting the input it wants. So you could run the part without <code>xargs</code> first to check it.</p>\n\n<p>It just occurred to me that although you didn't say so, you're probably on Windows due to the file suffixes you're looking for. In that case, the above pipeline could be run using Cygwin. It's possible to write a Perl script to do the same thing, as you started to do, but you'll have to do the in-place editing yourself because you can't take advantage of the <code>-i</code> switch in that situation.</p>\n" }, { "answer_id": 248779, "author": "Max Lybbert", "author_id": 10593, "author_profile": "https://Stackoverflow.com/users/10593", "pm_score": 2, "selected": false, "text": "<p>Change</p>\n\n<pre><code>foreach my $f (@files){\n if ($f =~ s/thisgoesout/thisgoesin/gi) {\n #inplace file editing, or something like that\n }\n}\n</code></pre>\n\n<p>To</p>\n\n<pre><code>foreach my $f (@files){\n open my $in, '&lt;', $f;\n open my $out, '&gt;', \"$f.out\";\n while (my $line = &lt;$in&gt;){\n chomp $line;\n $line =~ s/thisgoesout/thisgoesin/gi\n print $out \"$line\\n\";\n }\n}\n</code></pre>\n\n<p>This assumes that the pattern doesn't span multiple lines. If the pattern might span lines, you'll need to slurp in the file contents. (\"slurp\" is a pretty common Perl term).</p>\n\n<p>The chomp isn't actually necessary, I've just been bitten by lines that weren't <code>chomp</code>ed one too many times (if you drop the <code>chomp</code>, change <code>print $out \"$line\\n\";</code> to <code>print $out $line;</code>).</p>\n\n<p>Likewise, you can change <code>open my $out, '&gt;', \"$f.out\";</code> to <code>open my $out, '&gt;', undef;</code> to open a temporary file and then copy that file back over the original when the substitution's done. In fact, and especially if you slurp in the whole file, you can simply make the substitution in memory and then write over the original file. But I've made enough mistakes doing that that I always write to a new file, and verify the contents.</p>\n\n<hr>\n\n<p><strong>Note</strong>, I originally had an if statement in that code. That was most likely wrong. That would have only copied over lines that matched the regular expression \"thisgoesout\" (replacing it with \"thisgoesin\" of course) while silently gobbling up the rest.</p>\n" }, { "answer_id": 248781, "author": "Robert Krimen", "author_id": 25171, "author_profile": "https://Stackoverflow.com/users/25171", "pm_score": 3, "selected": false, "text": "<p>You may be interested in <a href=\"http://search.cpan.org/perldoc?File::Transaction::Atomic\" rel=\"nofollow noreferrer\">File::Transaction::Atomic</a> or <a href=\"http://search.cpan.org/perldoc?File::Transaction\" rel=\"nofollow noreferrer\">File::Transaction</a></p>\n\n<p>The SYNOPSIS for F::T::A looks very similar with what you're trying to do:</p>\n\n<pre><code> # In this example, we wish to replace \n # the word 'foo' with the word 'bar' in several files, \n # with no risk of ending up with the replacement done \n # in some files but not in others.\n\n use File::Transaction::Atomic;\n\n my $ft = File::Transaction::Atomic-&gt;new;\n\n eval {\n foreach my $file (@list_of_file_names) {\n $ft-&gt;linewise_rewrite($file, sub {\n s#\\bfoo\\b#bar#g;\n });\n }\n };\n\n if ($@) {\n $ft-&gt;revert;\n die \"update aborted: $@\";\n }\n else {\n $ft-&gt;commit;\n }\n</code></pre>\n\n<p>Couple that with the File::Find you've already written, and you should be good to go.</p>\n" }, { "answer_id": 248795, "author": "Svante", "author_id": 31615, "author_profile": "https://Stackoverflow.com/users/31615", "pm_score": 3, "selected": false, "text": "<p>You can use Tie::File to scalably access large files and change them in place. See the manpage (man 3perl Tie::File).</p>\n" }, { "answer_id": 248832, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 5, "selected": true, "text": "<p>If you assign <code>@ARGV</code> before using <code>*ARGV</code> (aka the diamond <code>&lt;&gt;</code>), <code>$^I</code>/<code>-i</code> will work on those files instead of what was specified on the command line.</p>\n\n<pre><code>use File::Find::Rule;\nuse strict;\n\n@ARGV = (File::Find::Rule-&gt;file()-&gt;name('*.cs', '*.aspx', '*.ascx')-&gt;in('.'));\n$^I = '.bak'; # or set `-i` in the #! line or on the command-line\n\nwhile (&lt;&gt;) {\n s/thisgoesout/thisgoesin/gi;\n print;\n}\n</code></pre>\n\n<p>This should do exactly what you want.</p>\n\n<p>If your pattern can span multiple lines, add in a <code>undef $/;</code> before the <code>&lt;&gt;</code> so that Perl operates on a whole file at a time instead of line-by-line.</p>\n" }, { "answer_id": 252140, "author": "Seiti", "author_id": 27959, "author_profile": "https://Stackoverflow.com/users/27959", "pm_score": 1, "selected": false, "text": "<p>Thanks to ephemient on this question and on <a href=\"https://stackoverflow.com/questions/125171/passing-a-regex-substitution-as-a-variable-in-perl#125329\">this answer</a>, I got this:</p>\n\n<pre><code>use File::Find::Rule;\nuse strict;\n\nsub ReplaceText {\n my $regex = shift;\n my $replace = shift;\n\n @ARGV = (File::Find::Rule-&gt;file()-&gt;name('*.cs','*.aspx','*.ascx')-&gt;in('.'));\n $^I = '.bak';\n while (&lt;&gt;) {\n s/$regex/$replace-&gt;()/gie;\n print;\n }\n}\n\nReplaceText qr/some(crazy)regexp/, sub { \"some $1 text\" };\n</code></pre>\n\n<p>Now I can even loop through a hash containing regexp=>subs entries!</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/248668", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27959/" ]
I've been trying to code a Perl script to substitute some text on all source files of my project. I'm in need of something like: ``` perl -p -i.bak -e "s/thisgoesout/thisgoesin/gi" *.{cs,aspx,ascx} ``` But that parses **all** the files of a directory **recursively**. I just started a script: ``` use File::Find::Rule; use strict; my @files = (File::Find::Rule->file()->name('*.cs','*.aspx','*.ascx')->in('.')); foreach my $f (@files){ if ($f =~ s/thisgoesout/thisgoesin/gi) { # In-place file editing, or something like that } } ``` But now I'm stuck. Is there a simple way to edit all files in place using Perl? Please note that I don't need to keep a copy of every modified file; I'm have 'em all subversioned =) **Update**: I tried this on [Cygwin](http://en.wikipedia.org/wiki/Cygwin), ``` perl -p -i.bak -e "s/thisgoesout/thisgoesin/gi" {*,*/*,*/*/*}.{cs,aspx,ascx ``` But it looks like my arguments list exploded to the maximum size allowed. In fact, I'm getting very strange errors on Cygwin...
If you assign `@ARGV` before using `*ARGV` (aka the diamond `<>`), `$^I`/`-i` will work on those files instead of what was specified on the command line. ``` use File::Find::Rule; use strict; @ARGV = (File::Find::Rule->file()->name('*.cs', '*.aspx', '*.ascx')->in('.')); $^I = '.bak'; # or set `-i` in the #! line or on the command-line while (<>) { s/thisgoesout/thisgoesin/gi; print; } ``` This should do exactly what you want. If your pattern can span multiple lines, add in a `undef $/;` before the `<>` so that Perl operates on a whole file at a time instead of line-by-line.
248,683
<p>I want to do a select in MySql that combines several columns... something like this pseudocode:</p> <pre><code>SELECT payment1_paid AND payment2_paid AS paid_in_full FROM denormalized_payments WHERE payment1_type = 'check'; </code></pre> <p><strong>Edit</strong>: payment1_paid and payment2_paid are booleans.</p> <p>I can't use any other language for this particular problem than MySql.</p> <p>Thanks for any help!</p> <p><strong>Edit</strong>: Sorry to everybody who gave me suggestions for summing and concatenating, but I've voted those early answers up because they're useful anyway. And <strong>thanks</strong> to everybody for your incredibly quick answers!</p>
[ { "answer_id": 248685, "author": "Eric Hogue", "author_id": 4137, "author_profile": "https://Stackoverflow.com/users/4137", "pm_score": 2, "selected": false, "text": "<p>Just do </p>\n\n<pre><code>Select CONCAT(payment1_paid, payment2_paid) as paid_in_full \nfrom denormalized_payments \nwhere payment1_type = 'check';\n</code></pre>\n\n<p>You can concat any number of field you want. </p>\n" }, { "answer_id": 248689, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 2, "selected": false, "text": "<p>If by combine you mean concatenate then this will work:</p>\n\n<pre><code>select concat(payment1_paid, payment2_paid) as paid_in_full\nfrom denormalized_payments where payment1_type = 'check';\n</code></pre>\n\n<p>If by combine you mean add, then this should work:</p>\n\n<pre><code>select payment1_paid + payment2_paid as paid_in_full\nfrom denormalized_payments where payment1_type = 'check';\n</code></pre>\n\n<p>[EDIT]</p>\n\n<p>For boolean AND:</p>\n\n<pre><code>select payment1_paid &amp;&amp; payment2_paid as paid_in_full\nfrom denormalized_payments where payment1_type = 'check';\n</code></pre>\n" }, { "answer_id": 248691, "author": "mohammedn", "author_id": 29268, "author_profile": "https://Stackoverflow.com/users/29268", "pm_score": 1, "selected": false, "text": "<p>I am not sure but do you mean to concatenate?</p>\n\n<pre><code>SELECT CONCAT(ColumnA, ColumnB) AS ColumnZ\nFROM Table\n</code></pre>\n" }, { "answer_id": 248697, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 1, "selected": false, "text": "<p><code>SELECT IF(payment1_paid = 1 AND payment2_paid = 1, 1, 0) AS paid_in_fill</code></p>\n" }, { "answer_id": 248702, "author": "David Santamaria", "author_id": 24097, "author_profile": "https://Stackoverflow.com/users/24097", "pm_score": 0, "selected": false, "text": "<p>If are Strings (or you want to treat like Strings the columns that you want to combine) you can use <a href=\"http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_concat\" rel=\"nofollow noreferrer\">CONCAT</a> and <a href=\"http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_concat-ws\" rel=\"nofollow noreferrer\">CONCAT_WS</a>. Good luck!</p>\n" }, { "answer_id": 248705, "author": "Eric Hogue", "author_id": 4137, "author_profile": "https://Stackoverflow.com/users/4137", "pm_score": 4, "selected": true, "text": "<p>Ok, for logical and you can do </p>\n\n<pre><code>Select (payment1_paid &amp;&amp; payment2_paid) as paid_in_full \nfrom denormalized_payments \nwhere payment1_type = 'check';\n</code></pre>\n\n<p>As seen <a href=\"http://dev.mysql.com/doc/refman/5.0/en/logical-operators.html#operator_and\" rel=\"noreferrer\">here</a>.</p>\n" }, { "answer_id": 248762, "author": "dshaw", "author_id": 32595, "author_profile": "https://Stackoverflow.com/users/32595", "pm_score": 0, "selected": false, "text": "<pre><code>select (payment1_paid &amp;&amp; payment2_paid) as paid_in_full\nfrom denormalized_payments where payment1_type = 'check';\n</code></pre>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/248683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8047/" ]
I want to do a select in MySql that combines several columns... something like this pseudocode: ``` SELECT payment1_paid AND payment2_paid AS paid_in_full FROM denormalized_payments WHERE payment1_type = 'check'; ``` **Edit**: payment1\_paid and payment2\_paid are booleans. I can't use any other language for this particular problem than MySql. Thanks for any help! **Edit**: Sorry to everybody who gave me suggestions for summing and concatenating, but I've voted those early answers up because they're useful anyway. And **thanks** to everybody for your incredibly quick answers!
Ok, for logical and you can do ``` Select (payment1_paid && payment2_paid) as paid_in_full from denormalized_payments where payment1_type = 'check'; ``` As seen [here](http://dev.mysql.com/doc/refman/5.0/en/logical-operators.html#operator_and).
248,693
<p>I just came onto a project with a pretty huge code base. </p> <p>I'm mostly dealing with C++ and a lot of the code they write uses double negation for their boolean logic. </p> <pre><code> if (!!variable &amp;&amp; (!!api.lookup("some-string"))) { do_some_stuff(); } </code></pre> <p>I know these guys are intelligent programmers, it's obvious they aren't doing this by accident. </p> <p>I'm no seasoned C++ expert, my only guess at why they are doing this is that they want to make absolutely positive that the value being evaluated is the actual boolean representation. So they negate it, then negate that again to get it back to its actual boolean value. </p> <p>Is this correct, or am I missing something?</p>
[ { "answer_id": 248698, "author": "Don Neufeld", "author_id": 13097, "author_profile": "https://Stackoverflow.com/users/13097", "pm_score": 8, "selected": true, "text": "<p>It's a trick to convert to bool.</p>\n" }, { "answer_id": 248701, "author": "Marcin", "author_id": 22724, "author_profile": "https://Stackoverflow.com/users/22724", "pm_score": 2, "selected": false, "text": "<p>Is operator! overloaded?<br>\nIf not, they're probably doing this to convert the variable to a bool without producing a warning. This is definitely not a standard way of doing things.</p>\n" }, { "answer_id": 248703, "author": "jwfearn", "author_id": 10559, "author_profile": "https://Stackoverflow.com/users/10559", "pm_score": 4, "selected": false, "text": "<p>Yes it is correct and no you are not missing something. <code>!!</code> is a conversion to bool. See <a href=\"https://stackoverflow.com/questions/206106/is-a-safe-way-to-convert-to-bool-in-c\">this question</a> for more discussion.</p>\n" }, { "answer_id": 248720, "author": "Richard Harrison", "author_id": 19624, "author_profile": "https://Stackoverflow.com/users/19624", "pm_score": 4, "selected": false, "text": "<p>It's a technique to avoid writing (variable != 0) - i.e. to convert from whatever type it is to a bool.</p>\n\n<p>IMO Code like this has no place in systems that need to be maintained - because it is not immediately readable code (hence the question in the first place). </p>\n\n<p>Code must be legible - otherwise you leave a time debt legacy for the future - as it takes time to understand something that is needlessly convoluted.</p>\n" }, { "answer_id": 248725, "author": "fizzer", "author_id": 18167, "author_profile": "https://Stackoverflow.com/users/18167", "pm_score": 6, "selected": false, "text": "<p>The coders think that it will convert the operand to bool, but because the operands of &amp;&amp; are already implicitly converted to bool, it's utterly redundant.</p>\n" }, { "answer_id": 248732, "author": "Darius Bacon", "author_id": 27024, "author_profile": "https://Stackoverflow.com/users/27024", "pm_score": 0, "selected": false, "text": "<p>It's correct but, in C, pointless here -- 'if' and '&amp;&amp;' would treat the expression the same way without the '!!'.</p>\n\n<p>The reason to do this in C++, I suppose, is that '&amp;&amp;' could be overloaded. But then, so could '!', so it doesn't <em>really</em> guarantee you get a bool, without looking at the code for the types of <code>variable</code> and <code>api.call</code>. Maybe someone with more C++ experience could explain; perhaps it's meant as a defense-in-depth sort of measure, not a guarantee.</p>\n" }, { "answer_id": 248747, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 1, "selected": false, "text": "<p>As <a href=\"https://stackoverflow.com/questions/248693/double-negation-in-c-code#248701\">Marcin</a> mentioned, it might well matter if operator overloading is in play. Otherwise, in C/C++ it doesn't matter except if you're doing one of the following things:</p>\n\n<ul>\n<li><p>direct comparison to <code>true</code> (or in C something like a <code>TRUE</code> macro), which is almost always a bad idea. For example:</p>\n\n<p><code>if (api.lookup(\"some-string\") == true) {...}</code></p></li>\n<li><p>you simply want something converted to a strict 0/1 value. In C++ an assignment to a <code>bool</code> will do this implicitly (for those things that are implicitly convertible to <code>bool</code>). In C or if you're dealing with a non-bool variable, this is an idiom that I've seen, but I prefer the <code>(some_variable != 0)</code> variety myself.</p></li>\n</ul>\n\n<p>I think in the context of a larger boolean expression it simply clutters things up.</p>\n" }, { "answer_id": 248798, "author": "dongilmore", "author_id": 31962, "author_profile": "https://Stackoverflow.com/users/31962", "pm_score": 0, "selected": false, "text": "<p>Maybe the programmers were thinking something like this...</p>\n\n<p>!!myAnswer is boolean. In context, it should become boolean, but I just love to bang bang things to make sure, because once upon a time there was a mysterious bug that bit me, and bang bang, I killed it.</p>\n" }, { "answer_id": 249305, "author": "Tom Barta", "author_id": 29839, "author_profile": "https://Stackoverflow.com/users/29839", "pm_score": 6, "selected": false, "text": "<p>It's actually a very useful idiom in some contexts. Take these macros (example from the Linux kernel). For GCC, they're implemented as follows:</p>\n\n<pre><code>#define likely(cond) (__builtin_expect(!!(cond), 1))\n#define unlikely(cond) (__builtin_expect(!!(cond), 0))\n</code></pre>\n\n<p>Why do they have to do this? GCC's <code>__builtin_expect</code> treats its parameters as <code>long</code> and not <code>bool</code>, so there needs to be some form of conversion. Since they don't know what <code>cond</code> is when they're writing those macros, it is most general to simply use the <code>!!</code> idiom.</p>\n\n<p>They could probably do the same thing by comparing against 0, but in my opinion, it's actually more straightforward to do the double-negation, since that's the closest to a cast-to-bool that C has.</p>\n\n<p>This code can be used in C++ as well... it's a lowest-common-denominator thing. If possible, do what works in both C and C++.</p>\n" }, { "answer_id": 253151, "author": "RobH", "author_id": 25488, "author_profile": "https://Stackoverflow.com/users/25488", "pm_score": 3, "selected": false, "text": "<p>It side-steps a compiler warning. Try this:</p>\n\n<pre><code>int _tmain(int argc, _TCHAR* argv[])\n{\n int foo = 5;\n bool bar = foo;\n bool baz = !!foo;\n return 0;\n}\n</code></pre>\n\n<p>The 'bar' line generates a \"forcing value to bool 'true' or 'false' (performance warning)\" on MSVC++, but the 'baz' line sneaks through fine.</p>\n" }, { "answer_id": 10557422, "author": "Joshua", "author_id": 14768, "author_profile": "https://Stackoverflow.com/users/14768", "pm_score": 1, "selected": false, "text": "<p>If <em>variable</em> is of object type, it might have a ! operator defined but no cast to bool (or worse an implicit cast to int with different semantics. Calling the ! operator twice results in a convert to bool that works even in strange cases.</p>\n" }, { "answer_id": 25495721, "author": "chux - Reinstate Monica", "author_id": 2410359, "author_profile": "https://Stackoverflow.com/users/2410359", "pm_score": 2, "selected": false, "text": "<p><code>!!</code> was used to cope with original C++ which did not have a boolean type (as neither did C). </p>\n\n<hr>\n\n<p>Example Problem:</p>\n\n<p>Inside <code>if(condition)</code>, the <code>condition</code> needs to evaluate to some type like <code>double, int, void*</code>, etc., but not <code>bool</code> as it does not exist yet.</p>\n\n<p>Say a class existed <code>int256</code> (a 256 bit integer) and all integer conversions/casts were overloaded.</p>\n\n<pre><code>int256 x = foo();\nif (x) ...\n</code></pre>\n\n<p>To test if <code>x</code> was \"true\" or non-zero, <code>if (x)</code> would convert <code>x</code> to some integer and <em>then</em> assess if that <code>int</code> was non-zero. A typical overload of <code>(int) x</code> would return only the LSbits of <code>x</code>. <code>if (x)</code> was then only testing the LSbits of <code>x</code>.</p>\n\n<p>But C++ has the <code>!</code> operator. An overloaded <code>!x</code> would typically evaluate all the bits of <code>x</code>. So to get back to the non-inverted logic <code>if (!!x)</code> is used.</p>\n\n<p>Ref <a href=\"https://stackoverflow.com/questions/16994263/did-older-versions-of-c-use-the-int-operator-of-a-class-when-evaluating-the\">Did older versions of C++ use the `int` operator of a class when evaluating the condition in an `if()` statement?</a></p>\n" }, { "answer_id": 27261422, "author": "KarlU", "author_id": 766527, "author_profile": "https://Stackoverflow.com/users/766527", "pm_score": 3, "selected": false, "text": "<p>Legacy C developers had no Boolean type, so they often <code>#define TRUE 1</code> and <code>#define FALSE 0</code> and then used arbitrary numeric data types for Boolean comparisons. Now that we have <code>bool</code>, many compilers will emit warnings when certain types of assignments and comparisons are made using a mixture of numeric types and Boolean types. These two usages will eventually collide when working with legacy code.</p>\n\n<p>To work around this problem, some developers use the following Boolean identity: <code>!num_value</code> returns <code>bool true</code> if <code>num_value == 0</code>; <code>false</code> otherwise. <code>!!num_value</code> returns <code>bool false</code> if <code>num_value == 0</code>; <code>true</code> otherwise. The single negation is sufficient to convert <code>num_value</code> to <code>bool</code>; however, the double negation is necessary to restore the original sense of the Boolean expression. </p>\n\n<p>This pattern is known as an <em>idiom</em>, i.e., something commonly used by people familiar with the language. Therefore, I don't see it as an anti-pattern, as much as I would <code>static_cast&lt;bool&gt;(num_value)</code>. The cast might very well give the correct results, but some compilers then emit a performance warning, so you still have to address that. </p>\n\n<p>The other way to address this is to say, <code>(num_value != FALSE)</code>. I'm okay with that too, but all in all, <code>!!num_value</code> is far less verbose, may be clearer, and is not confusing the second time you see it. </p>\n" }, { "answer_id": 40001799, "author": "kgf3JfUtW", "author_id": 3927314, "author_profile": "https://Stackoverflow.com/users/3927314", "pm_score": 1, "selected": false, "text": "<p>This may be an example of the <strong>double-bang trick</strong> (see <a href=\"http://www.artima.com/cppsource/safebool.html\" rel=\"nofollow noreferrer\">The Safe Bool Idiom</a> for more details). Here I summarize the first page of the article.</p>\n<p>In C++ there are a number of ways to provide Boolean tests for classes.</p>\n<blockquote>\n<p>An obvious way is the <code>operator bool</code> conversion operator.</p>\n</blockquote>\n<pre><code>// operator bool version\nclass Testable {\n bool ok_;\n public:\n explicit Testable(bool b = true) : ok_(b) {}\n\n operator bool() const { // use bool conversion operator\n return ok_;\n }\n};\n</code></pre>\n<p>We can test the class as thus:</p>\n<pre><code>Testable test;\nif (test) {\n std::cout &lt;&lt; &quot;Yes, test is working!\\n&quot;;\n}\nelse { \n std::cout &lt;&lt; &quot;No, test is not working!\\n&quot;;\n}\n</code></pre>\n<p>However, <code>operator bool</code> is considered unsafe because it allows nonsensical operations such as <code>test &lt;&lt; 1;</code> or <code>int i = test</code>.</p>\n<blockquote>\n<p>Using <code>operator!</code> is safer because we avoid implicit conversion or overloading issues.</p>\n</blockquote>\n<p>The implementation is trivial,</p>\n<pre><code>bool operator!() const { // use operator!\n return !ok_;\n}\n</code></pre>\n<p>The two idiomatic ways to test <code>Testable</code> object are</p>\n<pre><code>Testable test;\nif (!!test) {\n std::cout &lt;&lt; &quot;Yes, test is working!\\n&quot;;\n}\nif (!test) {\n std::cout &lt;&lt; &quot;No, test is not working!\\n&quot;;\n}\n</code></pre>\n<p>The first version <code>if (!!test)</code> is what some people call the <strong>double-bang trick</strong>.</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/248693", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3415/" ]
I just came onto a project with a pretty huge code base. I'm mostly dealing with C++ and a lot of the code they write uses double negation for their boolean logic. ``` if (!!variable && (!!api.lookup("some-string"))) { do_some_stuff(); } ``` I know these guys are intelligent programmers, it's obvious they aren't doing this by accident. I'm no seasoned C++ expert, my only guess at why they are doing this is that they want to make absolutely positive that the value being evaluated is the actual boolean representation. So they negate it, then negate that again to get it back to its actual boolean value. Is this correct, or am I missing something?
It's a trick to convert to bool.
248,719
<p>We are a group of students doing our Master degree in field of computer science.</p> <p>This semester we should do a Software engineering project according to the following bottom explanation.</p> <p>we should exactly act and report as a real Software engineering Team.</p> <p>I have been chosen as a project manager of this group, I am good in writing java codes but I don't have the experience of doing the project manager task, any way I have to do my best to do this project with my group members as good as possible.</p> <p>The problem is this that I need to deal with different levels of knowledge but all the members should participate in implementation part.</p> <p>I will be pleased if some one guide me how to do this project and how to manage this group, and where to start? how to encourage the members, and how to do my plans in practice?</p> <p>please have a look to the explanation and help me what technology do I need to chose for this project?</p> <h2>Project Explanation</h2> <p>projects should be implemented as so called web applications. Because of the MVC requirements this is more than a server-client architecture – we call this (at least) a three-tier architecture.</p> <p>The view should be created dynamic on clients' request. Therefor the content has to be computed by the server (server side). Inside of the view there should not exist any type of source code (like “scriplets”, Java Code, etc.) besides the markup language.</p> <p>This should ensure that the view can be created by web designers where the content is in the responsibility of programmers.</p> <p>Vice versa the source code should not contain any markup languages (like HTML).</p> <p>To store information (make persistent) the system should use a database. But there should not exist database specific queries inside of the source code – because then the sources are very dependent of the usage of exactly this database. System should work with an object relational mapper to map the stored information from database on special type of objects (beans).</p> <p>All configuration like database, entities, configuration, initialization should be realized using XML files (or similar ways like e.g, annotations), so that changes don't require recompilation of the system's sources.</p> <p>Technologies available (suggestions):</p> <pre><code> J2EE: JSP, Servlets, JSP EL, JSTL, JSF, Facelets, Custom JSF Components, Custom Facelets TagLibs, JUnit (unit testing) Persistence: Hibernate, JDO IDE: Eclipse, NetBeans Servlet Container: Apache Tomcat </code></pre>
[ { "answer_id": 248755, "author": "Carl", "author_id": 2136, "author_profile": "https://Stackoverflow.com/users/2136", "pm_score": 2, "selected": false, "text": "<p>Your description is somewhat different from your initial question so it's a little confusing. I'll try my best to answer and give you a few tips ...</p>\n\n<p>As a <strong>project manager or leader</strong>, you should be trying to <strong>get the best out of everyone</strong> in your team. Each one of them will be good at something so try to find out what that is, and put them to work at that.</p>\n\n<p>When you do assign work, you should also assign some <strong>freedom and accountability / responsibility</strong>. They're the expert in that area so let them deal with it as best as they know how. Offer support, encouragement and guidance wherever you can, but listen to what they have to say.</p>\n\n<p>If you have some team members that are less skilled but willing to learn (or contribute), pair them up with someone else. Have them <strong>work together</strong> on a component allowing the more experienced person to 'mentor' the less experienced one. If there's a way you can make this part of the 'success criteria' for your project, then that's even better as it gives them some incentive to work well together.</p>\n\n<p>Then there's all the <strong>technical project management tasks</strong>. These are things like specs, gannt charts, schedules, reviews, etc. These are important but in my opinion are less important than the people management aspects. Have your team provide you with the data for these documents. For example, ask the developer of component A how long it will take to develop and test rather than trying to figure it out yourself.</p>\n\n<p>Hope this is some help and gives you some food for thought. Sorry I can't help with the more technical/architectural aspects of your assignment.</p>\n" }, { "answer_id": 248809, "author": "Artelius", "author_id": 31945, "author_profile": "https://Stackoverflow.com/users/31945", "pm_score": 2, "selected": false, "text": "<p>Perhaps pair programming (two people sitting at the same terminal programming something together) would be helpful?</p>\n\n<p>A second person makes a great \"sanity check\" - bugs will be greatly reduced. The two programmers will complement each other, and if one is significantly less experienced than the other, he will learn quickly.</p>\n" }, { "answer_id": 249045, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 0, "selected": false, "text": "<p>\"I will be pleased if some one guide me how to do this project and how to manage this group, and where to start? how to encourage the members, and how to do my plans in practice?\"</p>\n\n<p>That's the core problem in all group endeavors. The question is so vague that there is no specific answer. Here's a list of books on <a href=\"http://books.google.com/books?q=IT+project+management&amp;source=bll&amp;sa=X&amp;oi=book_group&amp;resnum=11&amp;ct=title&amp;cad=bottom-3results\" rel=\"nofollow noreferrer\">IT Project Management</a>. Pick any one and read it.</p>\n" }, { "answer_id": 249068, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 0, "selected": false, "text": "<p>\"please have a look to the explanation and help me what technology do I need to chose for this project?\"</p>\n\n<p>Since there's no explanation of what the project will build, any technology list is fine. The are no \"requirements\", no \"concept\" no \"goal\" or \"purpose\". It's impossible to evaluate the technology without any purpose.</p>\n\n<p>Your \"project explanation\" isn't an explanation of your project. It's mostly a bunch of architectural principles. A project must be more than just a pile of technology. There has to be some goal or purpose.</p>\n\n<p>Your \"technologies available\" list has way too much stuff in it.</p>\n\n<p>Struts and Hibernate are about all you need. Other things (JSP, servlets, etc.) are part of Struts. I recommend iBatis instead of Hibernate.</p>\n\n<p>JUnit is required, and isn't really a choices. Think of JUnit as a mandatory part of Java.</p>\n\n<p>Pick either NetBeans or Eclipse -- don't waste time waffling back and forth, they're both free and approximately identical. Just pick one.</p>\n\n<p>The rest of the stuff on your list of technologies is just distraction. Unless, of course, your project has some functional requirements for which these technologies are a handy solution.</p>\n" }, { "answer_id": 251140, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Explanation of the Project: <strong>( Full explanation here )</strong></p>\n\n<hr>\n\n<p>General Description (customer):\n UcooP is meant as a system for exchange of knowledge and experiences in the context of\n universities. This contains multiple levels of exchange.</p>\n\n<pre><code> (A) Administrative Staff Exchange\n (B) Scientific Employee Exchange\n (C) Student Exchange\n (D) Public Exchange\n\n Universities can get registered to participate in that platform by sending a corresponding request\n to administration of that platform (e.g. MoHE). After an university has become member of that\n platform, students, employees and administration staff can register themselves as member of\n that university with the related role (student, employee or administrative staff).\n The content that is accessible for members than depends on their role. So, students can't access\n content that is tagged as employee content – and so on. Content that is tagged as public is accessible for members of all roles.\n Content inside of that platform can mean two different things.\n\n (A) Forum (Discussions on topics)\n (B) Wiki (Best practices)\n\n So besides the topic, Wiki pages and Forum topics have to be categorized to administration,\n employee, student or public content.\n</code></pre>\n\n<p>For motivating the universities to participate and to publish their experiences and knowledge –\nthe system should contain a ranking system. Universities can get certificates (e.g. Level One\nNode, Level Two Node, etc. the higher the better) depending on the number of topics, answers\nin discussion and/or published wiki pages – created by the university members.\nDefining the details of the system – means creating the concept and prototype of that system –\nis up to you.</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/248719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
We are a group of students doing our Master degree in field of computer science. This semester we should do a Software engineering project according to the following bottom explanation. we should exactly act and report as a real Software engineering Team. I have been chosen as a project manager of this group, I am good in writing java codes but I don't have the experience of doing the project manager task, any way I have to do my best to do this project with my group members as good as possible. The problem is this that I need to deal with different levels of knowledge but all the members should participate in implementation part. I will be pleased if some one guide me how to do this project and how to manage this group, and where to start? how to encourage the members, and how to do my plans in practice? please have a look to the explanation and help me what technology do I need to chose for this project? Project Explanation ------------------- projects should be implemented as so called web applications. Because of the MVC requirements this is more than a server-client architecture – we call this (at least) a three-tier architecture. The view should be created dynamic on clients' request. Therefor the content has to be computed by the server (server side). Inside of the view there should not exist any type of source code (like “scriplets”, Java Code, etc.) besides the markup language. This should ensure that the view can be created by web designers where the content is in the responsibility of programmers. Vice versa the source code should not contain any markup languages (like HTML). To store information (make persistent) the system should use a database. But there should not exist database specific queries inside of the source code – because then the sources are very dependent of the usage of exactly this database. System should work with an object relational mapper to map the stored information from database on special type of objects (beans). All configuration like database, entities, configuration, initialization should be realized using XML files (or similar ways like e.g, annotations), so that changes don't require recompilation of the system's sources. Technologies available (suggestions): ``` J2EE: JSP, Servlets, JSP EL, JSTL, JSF, Facelets, Custom JSF Components, Custom Facelets TagLibs, JUnit (unit testing) Persistence: Hibernate, JDO IDE: Eclipse, NetBeans Servlet Container: Apache Tomcat ```
Your description is somewhat different from your initial question so it's a little confusing. I'll try my best to answer and give you a few tips ... As a **project manager or leader**, you should be trying to **get the best out of everyone** in your team. Each one of them will be good at something so try to find out what that is, and put them to work at that. When you do assign work, you should also assign some **freedom and accountability / responsibility**. They're the expert in that area so let them deal with it as best as they know how. Offer support, encouragement and guidance wherever you can, but listen to what they have to say. If you have some team members that are less skilled but willing to learn (or contribute), pair them up with someone else. Have them **work together** on a component allowing the more experienced person to 'mentor' the less experienced one. If there's a way you can make this part of the 'success criteria' for your project, then that's even better as it gives them some incentive to work well together. Then there's all the **technical project management tasks**. These are things like specs, gannt charts, schedules, reviews, etc. These are important but in my opinion are less important than the people management aspects. Have your team provide you with the data for these documents. For example, ask the developer of component A how long it will take to develop and test rather than trying to figure it out yourself. Hope this is some help and gives you some food for thought. Sorry I can't help with the more technical/architectural aspects of your assignment.
248,721
<p>I need to have a single instance application (as per this <a href="https://stackoverflow.com/questions/19147/what-is-the-correct-way-to-create-a-single-instance-application#19326">answer</a>), but it needs to be deployed via click once.</p> <p>The problem is that I require that click once doesn't automatically detect an update an attempt to load a newer version while the application is running. If it is running, then I need the other instance to be made active. Usually, when selecting a Click Once link, the very first thing it does is attempt to find an update. I want to intercept this and check for an already running instance <strong>prior</strong> to launching the normal update process.</p> <p>Does anyone know how this is possible within a Click Once deployment scenario?</p>
[ { "answer_id": 248735, "author": "Richard Harrison", "author_id": 19624, "author_profile": "https://Stackoverflow.com/users/19624", "pm_score": 0, "selected": false, "text": "<p>I don't think you'll be able to do it quite like this as the check before run is outside of your code.</p>\n\n<p>However you can change the clickonce deployment options to check for updates during code execution.</p>\n\n<p>If you need more control then you can use the <a href=\"http://msdn.microsoft.com/en-us/library/system.deployment.application.applicationdeployment.update.aspx\" rel=\"nofollow noreferrer\">ApplicationDeployment Update</a> or <a href=\"http://msdn.microsoft.com/en-us/library/ms136935.aspx\" rel=\"nofollow noreferrer\">CheckForUpdate</a> methods to have absolute over the update process.</p>\n" }, { "answer_id": 248852, "author": "Andrew", "author_id": 5662, "author_profile": "https://Stackoverflow.com/users/5662", "pm_score": 3, "selected": false, "text": "<p><strong>Sure</strong> - you can disable the automatic the ClickOnce update checking (in the Publish -> Updates.. dialog), then use the objects and commands in the <a href=\"http://msdn.microsoft.com/en-us/library/system.deployment.application.aspx\" rel=\"nofollow noreferrer\">System.Deployment.Application</a> namespace to pragmatically check for updates.</p>\n\n<p>Check out:</p>\n\n<ul>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/system.deployment.application.applicationdeployment.checkforupdate.aspx\" rel=\"nofollow noreferrer\">System.Deployment.Application.ApplicationDeployment.CheckForUpdate()</a></li>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/system.deployment.application.applicationdeployment.checkforupdateasync.aspx\" rel=\"nofollow noreferrer\">System.Deployment.Application.ApplicationDeployment.CheckForUpdateAsync()</a></li>\n</ul>\n\n<p>If there is an update, you can do your single instance application checks before actually updating, by calling: </p>\n\n<ul>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/system.deployment.application.applicationdeployment.update.aspx\" rel=\"nofollow noreferrer\">System.Deployment.Application.ApplicationDeployment.Update()</a></li>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/system.deployment.application.applicationdeployment.updateasync.aspx\" rel=\"nofollow noreferrer\">System.Deployment.Application.ApplicationDeployment.UpdateAsync()</a></li>\n</ul>\n" }, { "answer_id": 322984, "author": "ping", "author_id": 41206, "author_profile": "https://Stackoverflow.com/users/41206", "pm_score": 6, "selected": true, "text": "<p>To tackle the problem, we built a prototype application which has the following two functionalities.</p>\n\n<ol>\n<li><p>Multiple instances on one pc are disabled. A single instance application is deployed via clickonce. When a user tries to start a second instance of the app, a message will pop up indicating that \"Another instance is already running\".</p></li>\n<li><p>Checks for an update asynchronously, and installs the update if one exists. A message: \"An update is available\" will pop up if there is an update available when a user runs a new instance. </p></li>\n</ol>\n\n<p>The process to build the demo application is as follows:</p>\n\n<h2><strong>Step 1: Detect an active instance application using Mutex class.</strong></h2>\n\n<pre><code>namespace ClickOnceDemo\n{\n static class Program\n {\n /// summary&gt;\n /// The main entry point for the application.\n /// /summary&gt;\n [STAThread]\n static void Main()\n {\n Application.EnableVisualStyles();\n Application.SetCompatibleTextRenderingDefault( false );\n bool ok;\n var m = new System.Threading.Mutex( true, \"Application\", out ok );\n if ( !ok )\n {\n MessageBox.Show( \"Another instance is already running.\", ApplicationDeployment.CurrentDeployment.CurrentVersion.ToString() );\n return;\n }\n Application.Run( new UpdateProgress() );\n }\n }\n}\n</code></pre>\n\n<h2><strong>Step 2: Handle update programmatically</strong></h2>\n\n<p>Before we do that, we should disable the automatic ClickOnce update checking (in the Publish -- Updates... dialog). </p>\n\n<p>Then we create two forms: UpdateProgress and mainForm, where UpdateProgress indicates download progress and mainForm represents the main application. </p>\n\n<p>When a user runs the application, updateProgress will be launched firstly to check for updates. When updating completes, mainForm will start and updateProgress will be hidden. </p>\n\n<pre><code>namespace ClickOnceDemo\n{\npublic partial class UpdateProgress : Form\n {\n public UpdateProgress()\n {\n InitializeComponent();\n Text = \"Checking for updates...\";\n\n ApplicationDeployment ad = ApplicationDeployment.CurrentDeployment;\n ad.CheckForUpdateCompleted += OnCheckForUpdateCompleted;\n ad.CheckForUpdateProgressChanged += OnCheckForUpdateProgressChanged;\n\n ad.CheckForUpdateAsync();\n }\n\n private void OnCheckForUpdateProgressChanged(object sender, DeploymentProgressChangedEventArgs e)\n {\n lblStatus.Text = String.Format( \"Downloading: {0}. {1:D}K of {2:D}K downloaded.\", GetProgressString( e.State ), e.BytesCompleted / 1024, e.BytesTotal / 1024 );\n progressBar1.Value = e.ProgressPercentage;\n }\n\n string GetProgressString( DeploymentProgressState state )\n {\n if ( state == DeploymentProgressState.DownloadingApplicationFiles )\n {\n return \"application files\";\n }\n if ( state == DeploymentProgressState.DownloadingApplicationInformation )\n {\n return \"application manifest\";\n }\n return \"deployment manifest\";\n }\n\n private void OnCheckForUpdateCompleted(object sender, CheckForUpdateCompletedEventArgs e)\n {\n if ( e.Error != null )\n {\n MessageBox.Show( \"ERROR: Could not retrieve new version of the application. Reason: \\n\" + e.Error.Message + \"\\nPlease report this error to the system administrator.\" );\n return;\n }\n if ( e.Cancelled )\n {\n MessageBox.Show( \"The update was cancelled.\" );\n }\n\n // Ask the user if they would like to update the application now.\n if ( e.UpdateAvailable )\n {\n if ( !e.IsUpdateRequired )\n {\n long updateSize = e.UpdateSizeBytes;\n DialogResult dr = MessageBox.Show( string.Format(\"An update ({0}K) is available. Would you like to update the application now?\", updateSize/1024), \"Update Available\", MessageBoxButtons.OKCancel );\n if ( DialogResult.OK == dr )\n {\n BeginUpdate();\n }\n }\n else\n {\n MessageBox.Show( \"A mandatory update is available for your application. We will install the update now, after which we will save all of your in-progress data and restart your application.\" );\n BeginUpdate();\n }\n }\n else\n {\n ShowMainForm();\n }\n }\n\n // Show the main application form\n private void ShowMainForm()\n {\n MainForm mainForm = new MainForm ();\n mainForm.Show();\n Hide();\n }\n\n private void BeginUpdate()\n {\n Text = \"Downloading update...\";\n ApplicationDeployment ad = ApplicationDeployment.CurrentDeployment;\n ad.UpdateCompleted += ad_UpdateCompleted;\n ad.UpdateProgressChanged += ad_UpdateProgressChanged;\n\n ad.UpdateAsync();\n }\n\n void ad_UpdateProgressChanged( object sender, DeploymentProgressChangedEventArgs e )\n {\n String progressText = String.Format( \"{0:D}K out of {1:D}K downloaded - {2:D}% complete\", e.BytesCompleted / 1024, e.BytesTotal / 1024, e.ProgressPercentage );\n progressBar1.Value = e.ProgressPercentage;\n lblStatus.Text = progressText;\n }\n\n void ad_UpdateCompleted( object sender, AsyncCompletedEventArgs e )\n {\n if ( e.Cancelled )\n {\n MessageBox.Show( \"The update of the application's latest version was cancelled.\" );\n return;\n }\n if ( e.Error != null )\n {\n MessageBox.Show( \"ERROR: Could not install the latest version of the application. Reason: \\n\" + e.Error.Message + \"\\nPlease report this error to the system administrator.\" );\n return;\n }\n\n DialogResult dr = MessageBox.Show( \"The application has been updated. Restart? (If you do not restart now, the new version will not take effect until after you quit and launch the application again.)\", \"Restart Application\", MessageBoxButtons.OKCancel );\n if ( DialogResult.OK == dr )\n {\n Application.Restart();\n }\n else\n {\n ShowMainForm();\n }\n }\n }\n}\n</code></pre>\n\n<p>The application works well and we hope it is a good solution for the problem.<br>\nSpecial thanks to <a href=\"http://timothywalters-devthoughts.blogspot.com\" rel=\"noreferrer\">Timothy Walters </a> for providing the source code</p>\n" }, { "answer_id": 12252069, "author": "Mark", "author_id": 611244, "author_profile": "https://Stackoverflow.com/users/611244", "pm_score": 0, "selected": false, "text": "<p>I used <a href=\"http://wpfsingleinstance.codeplex.com/\" rel=\"nofollow\">http://wpfsingleinstance.codeplex.com/</a> in my WPF ClickOnce application with great success. I did not have to change anything.</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/248721", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2918/" ]
I need to have a single instance application (as per this [answer](https://stackoverflow.com/questions/19147/what-is-the-correct-way-to-create-a-single-instance-application#19326)), but it needs to be deployed via click once. The problem is that I require that click once doesn't automatically detect an update an attempt to load a newer version while the application is running. If it is running, then I need the other instance to be made active. Usually, when selecting a Click Once link, the very first thing it does is attempt to find an update. I want to intercept this and check for an already running instance **prior** to launching the normal update process. Does anyone know how this is possible within a Click Once deployment scenario?
To tackle the problem, we built a prototype application which has the following two functionalities. 1. Multiple instances on one pc are disabled. A single instance application is deployed via clickonce. When a user tries to start a second instance of the app, a message will pop up indicating that "Another instance is already running". 2. Checks for an update asynchronously, and installs the update if one exists. A message: "An update is available" will pop up if there is an update available when a user runs a new instance. The process to build the demo application is as follows: **Step 1: Detect an active instance application using Mutex class.** -------------------------------------------------------------------- ``` namespace ClickOnceDemo { static class Program { /// summary> /// The main entry point for the application. /// /summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault( false ); bool ok; var m = new System.Threading.Mutex( true, "Application", out ok ); if ( !ok ) { MessageBox.Show( "Another instance is already running.", ApplicationDeployment.CurrentDeployment.CurrentVersion.ToString() ); return; } Application.Run( new UpdateProgress() ); } } } ``` **Step 2: Handle update programmatically** ------------------------------------------ Before we do that, we should disable the automatic ClickOnce update checking (in the Publish -- Updates... dialog). Then we create two forms: UpdateProgress and mainForm, where UpdateProgress indicates download progress and mainForm represents the main application. When a user runs the application, updateProgress will be launched firstly to check for updates. When updating completes, mainForm will start and updateProgress will be hidden. ``` namespace ClickOnceDemo { public partial class UpdateProgress : Form { public UpdateProgress() { InitializeComponent(); Text = "Checking for updates..."; ApplicationDeployment ad = ApplicationDeployment.CurrentDeployment; ad.CheckForUpdateCompleted += OnCheckForUpdateCompleted; ad.CheckForUpdateProgressChanged += OnCheckForUpdateProgressChanged; ad.CheckForUpdateAsync(); } private void OnCheckForUpdateProgressChanged(object sender, DeploymentProgressChangedEventArgs e) { lblStatus.Text = String.Format( "Downloading: {0}. {1:D}K of {2:D}K downloaded.", GetProgressString( e.State ), e.BytesCompleted / 1024, e.BytesTotal / 1024 ); progressBar1.Value = e.ProgressPercentage; } string GetProgressString( DeploymentProgressState state ) { if ( state == DeploymentProgressState.DownloadingApplicationFiles ) { return "application files"; } if ( state == DeploymentProgressState.DownloadingApplicationInformation ) { return "application manifest"; } return "deployment manifest"; } private void OnCheckForUpdateCompleted(object sender, CheckForUpdateCompletedEventArgs e) { if ( e.Error != null ) { MessageBox.Show( "ERROR: Could not retrieve new version of the application. Reason: \n" + e.Error.Message + "\nPlease report this error to the system administrator." ); return; } if ( e.Cancelled ) { MessageBox.Show( "The update was cancelled." ); } // Ask the user if they would like to update the application now. if ( e.UpdateAvailable ) { if ( !e.IsUpdateRequired ) { long updateSize = e.UpdateSizeBytes; DialogResult dr = MessageBox.Show( string.Format("An update ({0}K) is available. Would you like to update the application now?", updateSize/1024), "Update Available", MessageBoxButtons.OKCancel ); if ( DialogResult.OK == dr ) { BeginUpdate(); } } else { MessageBox.Show( "A mandatory update is available for your application. We will install the update now, after which we will save all of your in-progress data and restart your application." ); BeginUpdate(); } } else { ShowMainForm(); } } // Show the main application form private void ShowMainForm() { MainForm mainForm = new MainForm (); mainForm.Show(); Hide(); } private void BeginUpdate() { Text = "Downloading update..."; ApplicationDeployment ad = ApplicationDeployment.CurrentDeployment; ad.UpdateCompleted += ad_UpdateCompleted; ad.UpdateProgressChanged += ad_UpdateProgressChanged; ad.UpdateAsync(); } void ad_UpdateProgressChanged( object sender, DeploymentProgressChangedEventArgs e ) { String progressText = String.Format( "{0:D}K out of {1:D}K downloaded - {2:D}% complete", e.BytesCompleted / 1024, e.BytesTotal / 1024, e.ProgressPercentage ); progressBar1.Value = e.ProgressPercentage; lblStatus.Text = progressText; } void ad_UpdateCompleted( object sender, AsyncCompletedEventArgs e ) { if ( e.Cancelled ) { MessageBox.Show( "The update of the application's latest version was cancelled." ); return; } if ( e.Error != null ) { MessageBox.Show( "ERROR: Could not install the latest version of the application. Reason: \n" + e.Error.Message + "\nPlease report this error to the system administrator." ); return; } DialogResult dr = MessageBox.Show( "The application has been updated. Restart? (If you do not restart now, the new version will not take effect until after you quit and launch the application again.)", "Restart Application", MessageBoxButtons.OKCancel ); if ( DialogResult.OK == dr ) { Application.Restart(); } else { ShowMainForm(); } } } } ``` The application works well and we hope it is a good solution for the problem. Special thanks to [Timothy Walters](http://timothywalters-devthoughts.blogspot.com) for providing the source code
248,748
<p>I'm building a site using ajax and am trying to decide where to put the files that supply the data for the ajax requests.</p> <p>For example, I am going to have a .js file that can be included in a page that will create country/state select boxes. I will have the .js file under /inc/js.</p> <p>However, I am not sure where I want to put the ajax file that supplies the state data based on the country selected. I could put it next to the file it supports, make a folder for ajax data request files, etc.</p> <p>What do you do to keep your ajax requests organized by file?</p>
[ { "answer_id": 248772, "author": "Nikola Stjelja", "author_id": 32582, "author_profile": "https://Stackoverflow.com/users/32582", "pm_score": 0, "selected": false, "text": "<p>Create a separate site (same server or on another) that will serve only as a REST service generating output for your requests. \nWhen you work with AJAX you are in essence consuming published web services.</p>\n" }, { "answer_id": 248775, "author": "Noah Goodrich", "author_id": 20178, "author_profile": "https://Stackoverflow.com/users/20178", "pm_score": 2, "selected": false, "text": "<p>If you're planning on using a Model-View-Controller architecture, then you would place your ajax handler scripts where you maintain the remainder of the your controller scripts for the site.</p>\n\n<p>For example:</p>\n\n<pre>\n/application\n /default\n /controllers\n index.php\n index.ajax.php\n /views\n index.tpl\n index.ajax.tpl\n /admin\n</pre>\n\n<p>Using a model like this, it leaves you free to decide whether it makes more sense to create handler scripts for your ajax calls or to integrate the handler scripts for your ajax calls into the other, existing controller scripts.</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/248748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27580/" ]
I'm building a site using ajax and am trying to decide where to put the files that supply the data for the ajax requests. For example, I am going to have a .js file that can be included in a page that will create country/state select boxes. I will have the .js file under /inc/js. However, I am not sure where I want to put the ajax file that supplies the state data based on the country selected. I could put it next to the file it supports, make a folder for ajax data request files, etc. What do you do to keep your ajax requests organized by file?
If you're planning on using a Model-View-Controller architecture, then you would place your ajax handler scripts where you maintain the remainder of the your controller scripts for the site. For example: ``` /application /default /controllers index.php index.ajax.php /views index.tpl index.ajax.tpl /admin ``` Using a model like this, it leaves you free to decide whether it makes more sense to create handler scripts for your ajax calls or to integrate the handler scripts for your ajax calls into the other, existing controller scripts.
248,753
<p>This is the sequel to <a href="https://stackoverflow.com/questions/248683/how-can-i-do-boolean-logic-on-two-columns-in-mysql">this question</a>.</p> <p>I would like to combine three columns into one on a MySql select. The first two columns are boolean and the third is a string, which is sometimes null. This causes strange results:</p> <pre><code>Select *, (payment1_paid &amp;&amp; ((payment2_paid || payment2_type ="none"))) as paid_in_full from payments </code></pre> <p><strong>Note:</strong> <code>payment1_paid</code> is boolean, <code>payment2_paid</code> is boolean, <code>payment2_type</code> is varchar.</p> <p><strong>Note:</strong> Please ignore how ridiculous the structure of this table is. Behind every piece of bad code there is a long explanation :)</p> <p><strong>Edit:</strong> Null is not interesting to me for the varchar value. I only want to know if it's really "none."</p> <p>Thanks in advance for your help!</p>
[ { "answer_id": 248763, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 1, "selected": false, "text": "<p>I guess you want NULL to be false? Try <code>(payment_paid IS NULL || payment2_type = \"none\")</code></p>\n" }, { "answer_id": 248764, "author": "Bob Probst", "author_id": 12424, "author_profile": "https://Stackoverflow.com/users/12424", "pm_score": 1, "selected": false, "text": "<pre><code>Select *, \n (payment1_paid &amp;&amp; ((payment2_paid || coalesce(payment2_type,\"null\") =\"none\"))) \n as paid_in_full \nfrom payments\n</code></pre>\n" }, { "answer_id": 248791, "author": "David Santamaria", "author_id": 24097, "author_profile": "https://Stackoverflow.com/users/24097", "pm_score": 4, "selected": true, "text": "<p>If null is not interesting then for you then:</p>\n\n<pre><code>Select *, \n (payment1_paid &amp;&amp; ((payment2_paid || (payment_type IS NOT NULL &amp;&amp; payment_type=\"none\"))) \n as paid_in_full \nfrom payments\n</code></pre>\n\n<p>Good luck!</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/248753", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8047/" ]
This is the sequel to [this question](https://stackoverflow.com/questions/248683/how-can-i-do-boolean-logic-on-two-columns-in-mysql). I would like to combine three columns into one on a MySql select. The first two columns are boolean and the third is a string, which is sometimes null. This causes strange results: ``` Select *, (payment1_paid && ((payment2_paid || payment2_type ="none"))) as paid_in_full from payments ``` **Note:** `payment1_paid` is boolean, `payment2_paid` is boolean, `payment2_type` is varchar. **Note:** Please ignore how ridiculous the structure of this table is. Behind every piece of bad code there is a long explanation :) **Edit:** Null is not interesting to me for the varchar value. I only want to know if it's really "none." Thanks in advance for your help!
If null is not interesting then for you then: ``` Select *, (payment1_paid && ((payment2_paid || (payment_type IS NOT NULL && payment_type="none"))) as paid_in_full from payments ``` Good luck!
248,754
<p>Back in the earlier days of the internet I remember that in certain browsers, every time you downloaded an image or a file, the URL of where that file was downloaded from would be written into that file's properties (I guess the summary tab?). I think Netscape v2 did this if I remember correctly.</p> <p>I really miss that kind of functionality as every once in a while I'll run into a neat little program stored somewhere in the depths of my hard drive and wonder where I got it from originally.</p> <p>I googled around but I'm not quite sure what terms to use to describe what I'm looking for. So I'm wondering if anyone knows of a Firefox plug-in or something similar that would do this?</p>
[ { "answer_id": 248794, "author": "Rafe", "author_id": 27497, "author_profile": "https://Stackoverflow.com/users/27497", "pm_score": -1, "selected": false, "text": "<p>For the IE Browser I use the hell out of Fidler to look at all traffic going across the wire. </p>\n\n<p>For FireFox, you can use the FireBug plugin. There is a \"Net\" tab that will show you request information that is going across the wire.</p>\n\n<p>Most of the time you can use one of these tools to see what URL was requested in order to start a download. You can also view all the get and post information that might need to be sent in order to have your request succeed.</p>\n\n<p>Fidler is here: <a href=\"http://www.fiddlertool.com/fiddler/\" rel=\"nofollow noreferrer\">http://www.fiddlertool.com/fiddler/</a></p>\n\n<p>FireBug is here: <a href=\"https://addons.mozilla.org/en-US/firefox/addon/1843\" rel=\"nofollow noreferrer\">https://addons.mozilla.org/en-US/firefox/addon/1843</a></p>\n\n<p>Best of Luck!</p>\n" }, { "answer_id": 248846, "author": "scunliffe", "author_id": 6144, "author_profile": "https://Stackoverflow.com/users/6144", "pm_score": 1, "selected": false, "text": "<p>If you use the <a href=\"https://addons.mozilla.org/en-US/firefox/addon/201\" rel=\"nofollow noreferrer\">DownThemAll</a>! extension for Firefox, you can tell it to prepend the URL of the site to the downloaded file name...</p>\n\n<p>thus you end up with files like:</p>\n\n<pre><code>download.com_utils_compression_ABCD32.exe\n</code></pre>\n\n<p>It also works really well when you want to download/queue a bunch of files.</p>\n" }, { "answer_id": 248871, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 0, "selected": false, "text": "<p>You download <code>http://example.com/foo</code> to <code>~/Desktop/foo</code>, and you want to see the originating URL in the properties of the local file <code>foo</code>?</p>\n\n<p>Back when I used OS X, I remember Safari used to record the original URL in the resource fork of the downloaded file. Can't remember what the named fork is, well, named, but it'll show up in the properties panel from Finder. Since it's there, Spotlight will probably index it, too, but I haven't used OS X since 10.3.</p>\n\n<p>If you use Opera, and haven't cleared the file out from your download manager, select the download and it'll show the original URL that the file is from in the properties pane.</p>\n\n<p>Is this what you want? If so... well, I don't know of a similar Firefox extension, but it'll clarify the question.</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/248754", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1582/" ]
Back in the earlier days of the internet I remember that in certain browsers, every time you downloaded an image or a file, the URL of where that file was downloaded from would be written into that file's properties (I guess the summary tab?). I think Netscape v2 did this if I remember correctly. I really miss that kind of functionality as every once in a while I'll run into a neat little program stored somewhere in the depths of my hard drive and wonder where I got it from originally. I googled around but I'm not quite sure what terms to use to describe what I'm looking for. So I'm wondering if anyone knows of a Firefox plug-in or something similar that would do this?
If you use the [DownThemAll](https://addons.mozilla.org/en-US/firefox/addon/201)! extension for Firefox, you can tell it to prepend the URL of the site to the downloaded file name... thus you end up with files like: ``` download.com_utils_compression_ABCD32.exe ``` It also works really well when you want to download/queue a bunch of files.
248,761
<p>Hopefully I can do the problem justice, because it was too difficult to summarise it in the title! (suggestions are welcome in the comments)</p> <p>Right, so here's my table:</p> <pre><code>Tasks task_id (number) job_id (number) to_do_by_date (date) task_name (varchar / text) status (number) completed_date (date) </code></pre> <p>for arguments sake let's make the values of status:</p> <pre><code>1 = New 2 = InProgress 3 = Done </code></pre> <p>and what I'm having trouble trying to do is create a query that pulls back all of the tasks:</p> <ul> <li>where any of the tasks for a <code>job_id</code> have a <code>status</code> &lt;> Done <ul> <li>except where all tasks for a <code>job_id</code> are are done, but one or more tasks have a <code>completed_date</code> of today</li> </ul></li> <li>ordered by the <code>to_be_done_by</code> date, but grouping all of the job_id tasks together <ul> <li>so the <code>job_id</code> with the next `to_do_by_date' task is shown first</li> </ul></li> </ul> <p>some information about the data:</p> <ul> <li>a <code>job_id</code> can have an arbitrary number of tasks</li> </ul> <p><br /> <strong>Here's an example of the output I'm trying to get:</strong></p> <pre><code>task_id job_id to_do_by_date task_name status completed_date 1 1 yesterday - 3 yesterday 2 1 today - 3 today 3 2 now - 3 today 4 2 2 hours time - 2 {null} 5 2 4 hours time - 2 {null} 6 2 tomorrow - 1 {null} 7 3 3 hours time - 2 {null} 8 3 tomorrow - 1 {null} 9 3 tomorrow - 1 {null} </code></pre> <p><br /> I'm using Oracle 10g, so answers for Oracle or ANSI SQL, or a hint for how to approach this would be ideal, and I can create Views or wrap this in a Stored Procedure to offload logic from the application if your solution calls for it.</p> <p><br /> here's a sql script that will create the example test data shown above:</p> <pre><code>create table tasks (task_id number, job_id number, to_do_by_date date, task_name varchar2(50), status number, completed_date date); insert into tasks values (0,0,sysdate -2, 'Job 0, Task 1 - dont return!', 3, sysdate -2); insert into tasks values (1,1,sysdate -1, 'Job 1, Task 1', 3, sysdate -1); insert into tasks values (2,1,sysdate -2/24, 'Job 1, Task 2', 3, sysdate -2/24); insert into tasks values (3,2,sysdate, 'Job 2, Task 1', 3, sysdate); insert into tasks values (4,2,sysdate +2/24, 'Job 2, Task 2', 2, null); insert into tasks values (5,2,sysdate +4/24, 'Job 2, Task 3', 2, null); insert into tasks values (6,2,sysdate +1, 'Job 2, Task 4', 1, null); insert into tasks values (7,3,sysdate +3/24, 'Job 3, Task 1', 2, null); insert into tasks values (8,3,sysdate +1, 'Job 3, Task 2', 1, null); insert into tasks values (9,3,sysdate +1, 'Job 3, Task 3', 1, null); commit; </code></pre> <p><br /> Many, many thanks for your help :o)</p>
[ { "answer_id": 248831, "author": "Justin Cave", "author_id": 10397, "author_profile": "https://Stackoverflow.com/users/10397", "pm_score": 0, "selected": false, "text": "<p>Given your requirements, it's not obvious to me why job_id 2 should be returned in your results. There is one task with a status of Done, so it fails the first criteria </p>\n\n<blockquote>\n <p>all of the tasks for a job_id have a\n status &lt;> Done</p>\n</blockquote>\n\n<p>And there are tasks with a status other than Done, so it fails the second criteria</p>\n\n<blockquote>\n <p>except where all tasks for a job_id\n are are done, but one or more tasks\n have a completed_date of today</p>\n</blockquote>\n\n<p>Is there some other reason that job_id = 2 should be included?</p>\n\n<pre><code>SQL&gt; ed\nWrote file afiedt.buf\n\n 1 select task_id, job_id, to_do_by_date, task_name, status, completed_date\n 2 from tasks t1\n 3 where not exists( select 1\n 4 from tasks t2\n 5 where t1.job_id = t2.job_id\n 6 and t2.status = 3)\n 7 or ((not exists( select 1\n 8 from tasks t3\n 9 where t1.job_id = t3.job_id\n 10 and t3.status != 3))\n 11 and\n 12 exists (select 1\n 13 from tasks t4\n 14 where t1.job_id = t4.job_id\n 15 and trunc(t4.completed_date) = trunc(sysdate)))\n 16* order by job_id, to_do_by_date\nSQL&gt; /\n\n TASK_ID JOB_ID TO_DO_BY_ TASK_NAME STATUS COMPLETED\n---------- ---------- --------- --------------- ---------- ---------\n 1 1 28-OCT-08 Job 1, Task 1 3 28-OCT-08\n 2 1 29-OCT-08 Job 1, Task 2 3 29-OCT-08\n 7 3 29-OCT-08 Job 3, Task 1 2\n 8 3 30-OCT-08 Job 3, Task 2 1\n 9 3 30-OCT-08 Job 3, Task 3 1\n</code></pre>\n" }, { "answer_id": 248833, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 0, "selected": false, "text": "<p>I don't do Oracle, and I don't have a Sql Server handy - but this should get you fairly close.</p>\n\n<pre><code>SELECT Tasks.*\nFROM Tasks\nJOIN (\n --Undone\n SELECT Job_Id\n FROM Tasks\n WHERE\n Status &lt;&gt; 3\n UNION\n --Done today\n SELECT Job_Id\n FROM Tasks\n WHERE\n Status = 3\n AND Completed_Date = TODAY()\n) as UndoneOrDoneToday ON\n Tasks.Job_Id = UndoneOrDoneToday.Job_Id\nJOIN (\n SELECT Job_Id, MIN(to_do_by_date) as NextToDoByDate\n FROM Tasks\n GROUP BY Job_id\n) as NextJob ON\n Tasks.Job_Id = NextJob.Job_id\nORDER BY\n NextJob.NextToDoByDate, \n Tasks.Job_Id, --If NextToDoByDate isn't unique, this should order jobs together\n Tasks.to_do_by_date, --This may not be needed, but would put eg., task 7 due today higher than task 6 due tomorrow\n Tasks.Task_Id --this should be last\n</code></pre>\n\n<p>Edit: Most other answers seem to sort by job_id, to_do_by. That looks to work for the example data, but does not meet the requirements of:</p>\n\n<blockquote>\n <p>ordered by the to_be_done_by date, but grouping all of the job_id tasks together\n so the job_id with the next to_do_by_date task is shown first</p>\n</blockquote>\n" }, { "answer_id": 248844, "author": "DJ.", "author_id": 10492, "author_profile": "https://Stackoverflow.com/users/10492", "pm_score": 3, "selected": true, "text": "<p>Obviously you will have to fix this up a bit but I hope you get the idea.</p>\n\n<pre><code>SELECT \n task_id, job_id, to_do_by_date, task_name, status, completed_date\nFROM\n Tasks\nWHERE\n job_id IN (\n SELECT job_id \n FROM Tasks \n WHERE status &lt;&gt; 'Done' \n GROUP BY job_id)\n OR\n job_id IN (\n SELECT job_id \n FROM Tasks \n WHERE status = 'Done' AND completed_date = 'Today'\n AND job_id NOT IN (SELECT job_id FROM Tasks WHERE status &lt;&gt; 'Done' GROUP BY job_id)\n GROUP BY job_id)\nORDER BY\n job_id, to_do_by_date\n</code></pre>\n" }, { "answer_id": 248886, "author": "David Aldridge", "author_id": 6742, "author_profile": "https://Stackoverflow.com/users/6742", "pm_score": 2, "selected": false, "text": "<p>I agree with Justin -- I don't get why 2 is returned.</p>\n\n<p>Here's a query using analytic functions to return the right rows according to the logic description.</p>\n\n<pre><code>select * from\n(\nselect t.*,\n min(status) over (partition by job_id) min_status_over_job,\n max(status) over (partition by job_id) max_status_over_job,\n sum(case when trunc(completed_date) = trunc(sysdate)-1 then 1 else 0 end) \n over (partition by job_id) num_complete_yest\nfrom tasks t\n)\nwhere max_status_over_job &lt; 3\n or (min_status_over_job = 3 and num_complete_yest &gt; 0)\n/\n</code></pre>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/248761", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5662/" ]
Hopefully I can do the problem justice, because it was too difficult to summarise it in the title! (suggestions are welcome in the comments) Right, so here's my table: ``` Tasks task_id (number) job_id (number) to_do_by_date (date) task_name (varchar / text) status (number) completed_date (date) ``` for arguments sake let's make the values of status: ``` 1 = New 2 = InProgress 3 = Done ``` and what I'm having trouble trying to do is create a query that pulls back all of the tasks: * where any of the tasks for a `job_id` have a `status` <> Done + except where all tasks for a `job_id` are are done, but one or more tasks have a `completed_date` of today * ordered by the `to_be_done_by` date, but grouping all of the job\_id tasks together + so the `job_id` with the next `to\_do\_by\_date' task is shown first some information about the data: * a `job_id` can have an arbitrary number of tasks **Here's an example of the output I'm trying to get:** ``` task_id job_id to_do_by_date task_name status completed_date 1 1 yesterday - 3 yesterday 2 1 today - 3 today 3 2 now - 3 today 4 2 2 hours time - 2 {null} 5 2 4 hours time - 2 {null} 6 2 tomorrow - 1 {null} 7 3 3 hours time - 2 {null} 8 3 tomorrow - 1 {null} 9 3 tomorrow - 1 {null} ``` I'm using Oracle 10g, so answers for Oracle or ANSI SQL, or a hint for how to approach this would be ideal, and I can create Views or wrap this in a Stored Procedure to offload logic from the application if your solution calls for it. here's a sql script that will create the example test data shown above: ``` create table tasks (task_id number, job_id number, to_do_by_date date, task_name varchar2(50), status number, completed_date date); insert into tasks values (0,0,sysdate -2, 'Job 0, Task 1 - dont return!', 3, sysdate -2); insert into tasks values (1,1,sysdate -1, 'Job 1, Task 1', 3, sysdate -1); insert into tasks values (2,1,sysdate -2/24, 'Job 1, Task 2', 3, sysdate -2/24); insert into tasks values (3,2,sysdate, 'Job 2, Task 1', 3, sysdate); insert into tasks values (4,2,sysdate +2/24, 'Job 2, Task 2', 2, null); insert into tasks values (5,2,sysdate +4/24, 'Job 2, Task 3', 2, null); insert into tasks values (6,2,sysdate +1, 'Job 2, Task 4', 1, null); insert into tasks values (7,3,sysdate +3/24, 'Job 3, Task 1', 2, null); insert into tasks values (8,3,sysdate +1, 'Job 3, Task 2', 1, null); insert into tasks values (9,3,sysdate +1, 'Job 3, Task 3', 1, null); commit; ``` Many, many thanks for your help :o)
Obviously you will have to fix this up a bit but I hope you get the idea. ``` SELECT task_id, job_id, to_do_by_date, task_name, status, completed_date FROM Tasks WHERE job_id IN ( SELECT job_id FROM Tasks WHERE status <> 'Done' GROUP BY job_id) OR job_id IN ( SELECT job_id FROM Tasks WHERE status = 'Done' AND completed_date = 'Today' AND job_id NOT IN (SELECT job_id FROM Tasks WHERE status <> 'Done' GROUP BY job_id) GROUP BY job_id) ORDER BY job_id, to_do_by_date ```
248,768
<p>I am trying to to walk though the tree of PdfItem objects in an existing PDF document using PDFSharp in c#. </p> <p>I want to create a hierarchy of all the objects as I go along -- similar to what the "PDF Explorer" example does -- but I want it to be a tree instead of a flat list of all the objects.</p> <p>The root node is document.Internals.Catalog. And I want to to walk down through all the document.Internals.Catalog.Elements until I have visited every element.</p> <p>One of the problems I run into is that there are circular references in the tree and I can't figure out how to detect them.</p> <p>Any code samples out there?</p>
[ { "answer_id": 255559, "author": "yfeldblum", "author_id": 12349, "author_profile": "https://Stackoverflow.com/users/12349", "pm_score": 0, "selected": false, "text": "<p>Read and analyze the entirety of the collection, and build an in-memory tree of your own. Then walk that tree.</p>\n" }, { "answer_id": 1732265, "author": "Brian Low", "author_id": 46039, "author_profile": "https://Stackoverflow.com/users/46039", "pm_score": 4, "selected": true, "text": "<p>This post by marihanzo on the PDFSharp forums has worked for us:</p>\n\n<p><a href=\"http://forum.pdfsharp.net/viewtopic.php?f=2&amp;t=527&amp;p=1603\" rel=\"noreferrer\">http://forum.pdfsharp.net/viewtopic.php?f=2&amp;t=527&amp;p=1603</a></p>\n\n<p>The only issue we've had was handling fields with \\r\\n in them. Here is a copy of the code in case the forum post gets lost.</p>\n\n<p>PDFParser.cs</p>\n\n<pre><code>public class PDFParser\n{\n /// BT = Beginning of a text object operator\n /// ET = End of a text object operator\n /// Td move to the start of next line\n /// 5 Ts = superscript\n /// -5 Ts = subscript\n\n #region Fields\n\n #region _numberOfCharsToKeep\n /// &lt;summary&gt;\n /// The number of characters to keep, when extracting text.\n /// &lt;/summary&gt;\n private static int _numberOfCharsToKeep = 15;\n #endregion\n\n #endregion\n\n\n\n #region ExtractTextFromPDFBytes\n /// &lt;summary&gt;\n /// This method processes an uncompressed Adobe (text) object\n /// and extracts text.\n /// &lt;/summary&gt;\n /// &lt;param name=\"input\"&gt;uncompressed&lt;/param&gt;\n /// &lt;returns&gt;&lt;/returns&gt;\n public string ExtractTextFromPDFBytes(byte[] input)\n {\n if (input == null || input.Length == 0) return \"\";\n\n try\n {\n string resultString = \"\";\n\n // Flag showing if we are we currently inside a text object\n bool inTextObject = false;\n\n // Flag showing if the next character is literal\n // e.g. '\\\\' to get a '\\' character or '\\(' to get '('\n bool nextLiteral = false;\n\n // () Bracket nesting level. Text appears inside ()\n int bracketDepth = 0;\n\n // Keep previous chars to get extract numbers etc.:\n char[] previousCharacters = new char[_numberOfCharsToKeep];\n for (int j = 0; j &lt; _numberOfCharsToKeep; j++) previousCharacters[j] = ' ';\n\n\n for (int i = 0; i &lt; input.Length; i++)\n {\n char c = (char)input[i];\n\n if (inTextObject)\n {\n // Position the text\n if (bracketDepth == 0)\n {\n if (CheckToken(new string[] { \"TD\", \"Td\" }, previousCharacters))\n {\n resultString += \"\\n\\r\";\n }\n else\n {\n if (CheckToken(new string[] { \"'\", \"T*\", \"\\\"\" }, previousCharacters))\n {\n resultString += \"\\n\";\n }\n else\n {\n if (CheckToken(new string[] { \"Tj\" }, previousCharacters))\n {\n resultString += \" \";\n }\n }\n }\n }\n\n // End of a text object, also go to a new line.\n if (bracketDepth == 0 &amp;&amp;\n CheckToken(new string[] { \"ET\" }, previousCharacters))\n {\n\n inTextObject = false;\n resultString += \" \";\n }\n else\n {\n // Start outputting text\n if ((c == '(') &amp;&amp; (bracketDepth == 0) &amp;&amp; (!nextLiteral))\n {\n bracketDepth = 1;\n }\n else\n {\n // Stop outputting text\n if ((c == ')') &amp;&amp; (bracketDepth == 1) &amp;&amp; (!nextLiteral))\n {\n bracketDepth = 0;\n }\n else\n {\n // Just a normal text character:\n if (bracketDepth == 1)\n {\n // Only print out next character no matter what.\n // Do not interpret.\n if (c == '\\\\' &amp;&amp; !nextLiteral)\n {\n nextLiteral = true;\n }\n else\n {\n if (((c &gt;= ' ') &amp;&amp; (c &lt;= '~')) ||\n ((c &gt;= 128) &amp;&amp; (c &lt; 255)))\n {\n resultString += c.ToString();\n }\n\n nextLiteral = false;\n }\n }\n }\n }\n }\n }\n\n // Store the recent characters for\n // when we have to go back for a checking\n for (int j = 0; j &lt; _numberOfCharsToKeep - 1; j++)\n {\n previousCharacters[j] = previousCharacters[j + 1];\n }\n previousCharacters[_numberOfCharsToKeep - 1] = c;\n\n // Start of a text object\n if (!inTextObject &amp;&amp; CheckToken(new string[] { \"BT\" }, previousCharacters))\n {\n inTextObject = true;\n }\n }\n return resultString;\n }\n catch\n {\n return \"\";\n }\n }\n #endregion\n\n #region CheckToken\n /// &lt;summary&gt;\n /// Check if a certain 2 character token just came along (e.g. BT)\n /// &lt;/summary&gt;\n /// &lt;param name=\"search\"&gt;the searched token&lt;/param&gt;\n /// &lt;param name=\"recent\"&gt;the recent character array&lt;/param&gt;\n /// &lt;returns&gt;&lt;/returns&gt;\n private bool CheckToken(string[] tokens, char[] recent)\n {\n foreach (string token in tokens)\n {\n if (token.Length &gt; 1)\n {\n if ((recent[_numberOfCharsToKeep - 3] == token[0]) &amp;&amp;\n (recent[_numberOfCharsToKeep - 2] == token[1]) &amp;&amp;\n ((recent[_numberOfCharsToKeep - 1] == ' ') ||\n (recent[_numberOfCharsToKeep - 1] == 0x0d) ||\n (recent[_numberOfCharsToKeep - 1] == 0x0a)) &amp;&amp;\n ((recent[_numberOfCharsToKeep - 4] == ' ') ||\n (recent[_numberOfCharsToKeep - 4] == 0x0d) ||\n (recent[_numberOfCharsToKeep - 4] == 0x0a))\n )\n {\n return true;\n }\n }\n else\n {\n return false;\n }\n\n }\n return false;\n }\n #endregion\n}\n</code></pre>\n\n<p>and the calling code:</p>\n\n<pre><code> public override String ExtractText()\n {\n String outputText = \"\";\n try\n {\n PdfDocument inputDocument = PdfReader.Open(this._sDirectory + this._sFileName, PdfDocumentOpenMode.ReadOnly);\n\n foreach (PdfPage page in inputDocument.Pages)\n {\n for (int index = 0; index &lt; page.Contents.Elements.Count; index++)\n {\n\n PdfDictionary.PdfStream stream = page.Contents.Elements.GetDictionary(index).Stream;\n outputText += new PDFParser().ExtractTextFromPDFBytes(stream.Value);\n }\n }\n\n }\n catch (Exception e)\n {\n PDF_ParseException oEx = new PDF_ParseException(this, e);\n oEx.Log();\n oEx.ToPdf(this._sDirectoryException);\n }\n return outputText;\n }\n</code></pre>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/248768", "https://Stackoverflow.com", "https://Stackoverflow.com/users/814/" ]
I am trying to to walk though the tree of PdfItem objects in an existing PDF document using PDFSharp in c#. I want to create a hierarchy of all the objects as I go along -- similar to what the "PDF Explorer" example does -- but I want it to be a tree instead of a flat list of all the objects. The root node is document.Internals.Catalog. And I want to to walk down through all the document.Internals.Catalog.Elements until I have visited every element. One of the problems I run into is that there are circular references in the tree and I can't figure out how to detect them. Any code samples out there?
This post by marihanzo on the PDFSharp forums has worked for us: <http://forum.pdfsharp.net/viewtopic.php?f=2&t=527&p=1603> The only issue we've had was handling fields with \r\n in them. Here is a copy of the code in case the forum post gets lost. PDFParser.cs ``` public class PDFParser { /// BT = Beginning of a text object operator /// ET = End of a text object operator /// Td move to the start of next line /// 5 Ts = superscript /// -5 Ts = subscript #region Fields #region _numberOfCharsToKeep /// <summary> /// The number of characters to keep, when extracting text. /// </summary> private static int _numberOfCharsToKeep = 15; #endregion #endregion #region ExtractTextFromPDFBytes /// <summary> /// This method processes an uncompressed Adobe (text) object /// and extracts text. /// </summary> /// <param name="input">uncompressed</param> /// <returns></returns> public string ExtractTextFromPDFBytes(byte[] input) { if (input == null || input.Length == 0) return ""; try { string resultString = ""; // Flag showing if we are we currently inside a text object bool inTextObject = false; // Flag showing if the next character is literal // e.g. '\\' to get a '\' character or '\(' to get '(' bool nextLiteral = false; // () Bracket nesting level. Text appears inside () int bracketDepth = 0; // Keep previous chars to get extract numbers etc.: char[] previousCharacters = new char[_numberOfCharsToKeep]; for (int j = 0; j < _numberOfCharsToKeep; j++) previousCharacters[j] = ' '; for (int i = 0; i < input.Length; i++) { char c = (char)input[i]; if (inTextObject) { // Position the text if (bracketDepth == 0) { if (CheckToken(new string[] { "TD", "Td" }, previousCharacters)) { resultString += "\n\r"; } else { if (CheckToken(new string[] { "'", "T*", "\"" }, previousCharacters)) { resultString += "\n"; } else { if (CheckToken(new string[] { "Tj" }, previousCharacters)) { resultString += " "; } } } } // End of a text object, also go to a new line. if (bracketDepth == 0 && CheckToken(new string[] { "ET" }, previousCharacters)) { inTextObject = false; resultString += " "; } else { // Start outputting text if ((c == '(') && (bracketDepth == 0) && (!nextLiteral)) { bracketDepth = 1; } else { // Stop outputting text if ((c == ')') && (bracketDepth == 1) && (!nextLiteral)) { bracketDepth = 0; } else { // Just a normal text character: if (bracketDepth == 1) { // Only print out next character no matter what. // Do not interpret. if (c == '\\' && !nextLiteral) { nextLiteral = true; } else { if (((c >= ' ') && (c <= '~')) || ((c >= 128) && (c < 255))) { resultString += c.ToString(); } nextLiteral = false; } } } } } } // Store the recent characters for // when we have to go back for a checking for (int j = 0; j < _numberOfCharsToKeep - 1; j++) { previousCharacters[j] = previousCharacters[j + 1]; } previousCharacters[_numberOfCharsToKeep - 1] = c; // Start of a text object if (!inTextObject && CheckToken(new string[] { "BT" }, previousCharacters)) { inTextObject = true; } } return resultString; } catch { return ""; } } #endregion #region CheckToken /// <summary> /// Check if a certain 2 character token just came along (e.g. BT) /// </summary> /// <param name="search">the searched token</param> /// <param name="recent">the recent character array</param> /// <returns></returns> private bool CheckToken(string[] tokens, char[] recent) { foreach (string token in tokens) { if (token.Length > 1) { if ((recent[_numberOfCharsToKeep - 3] == token[0]) && (recent[_numberOfCharsToKeep - 2] == token[1]) && ((recent[_numberOfCharsToKeep - 1] == ' ') || (recent[_numberOfCharsToKeep - 1] == 0x0d) || (recent[_numberOfCharsToKeep - 1] == 0x0a)) && ((recent[_numberOfCharsToKeep - 4] == ' ') || (recent[_numberOfCharsToKeep - 4] == 0x0d) || (recent[_numberOfCharsToKeep - 4] == 0x0a)) ) { return true; } } else { return false; } } return false; } #endregion } ``` and the calling code: ``` public override String ExtractText() { String outputText = ""; try { PdfDocument inputDocument = PdfReader.Open(this._sDirectory + this._sFileName, PdfDocumentOpenMode.ReadOnly); foreach (PdfPage page in inputDocument.Pages) { for (int index = 0; index < page.Contents.Elements.Count; index++) { PdfDictionary.PdfStream stream = page.Contents.Elements.GetDictionary(index).Stream; outputText += new PDFParser().ExtractTextFromPDFBytes(stream.Value); } } } catch (Exception e) { PDF_ParseException oEx = new PDF_ParseException(this, e); oEx.Log(); oEx.ToPdf(this._sDirectoryException); } return outputText; } ```
248,769
<p>I currently use Notepad++ for most of my development. I have been checking out other, more full-featured options and would like to switch (I'm in particular a fan of Aptana so far) but there is one thing about Notepad++ that I really like and I haven't been able to get so far. </p> <p>My current workflow is something like this: <a href="http://evanalyze.com/images/workflow" rel="nofollow noreferrer">Workflow</a> (I tried to embed this image and it showed up in previews but not in the post, sorry) <a href="http://evanalyze.com/images/workflow.jpg" rel="nofollow noreferrer">Workflow http://evanalyze.com/images/workflow.jpg</a></p> <p>The process is this:</p> <ol> <li>Download file from web server</li> <li>Make edits in NP++</li> <li>Save (this automatically saves a local copy in my default directory, which is also the folder I have setup using Subversion with Tourtise SVN)</li> <li>When I want to commit a change to SVN, go through the local folder that has an up to date copy</li> </ol> <p>What I can't figure out how to do with Aptana is automatically store a local copy of a file I download from my server, edit and save back to the server. Is there some way to do this? If so, that would solve my problem immediately.</p> <p>Other options would be a suggestion for a better way to manage the relationship between my server, my editor and my SVN repository. I know Aptana can access my SVN repository too. Is there an easy way to commit changes from within Aptana when I want to (which means I could take Tourtise out of the equation I guess)?</p> <p>Any suggestions appreciated. Thanks.</p>
[ { "answer_id": 248793, "author": "Matt Mitchell", "author_id": 364, "author_profile": "https://Stackoverflow.com/users/364", "pm_score": 2, "selected": false, "text": "<p>Not too sure but I found <a href=\"http://www.nusphere.com/\" rel=\"nofollow noreferrer\">PhpEd</a> better than Zend for this kind of stuff - especially easy save to FTP.</p>\n" }, { "answer_id": 248822, "author": "user27987", "author_id": 27987, "author_profile": "https://Stackoverflow.com/users/27987", "pm_score": 0, "selected": false, "text": "<p>Eclipse has a plugin called <a href=\"http://www.eclipse.org/dsdp/tm/\" rel=\"nofollow noreferrer\">RSE</a> allow you to work on remote sources thru ssh,ftp etc.\nYou can use <a href=\"http://www.eclipse.org/pdt\" rel=\"nofollow noreferrer\">PDT</a> but I guess it may work on Aptana as well.</p>\n\n<p>I'm using the Zend Studio For Eclipse which has both SVN and RSE built in.\nI'm guessing it's the same in PDT (after installing the RSE plugin), you can either work directly in the RSE perspective or add a remove folder to your project (you can do this only after adding connections in the RSE)</p>\n\n<p>BTW, I found the following link that can give you some more options for remote machine:\n<a href=\"http://wiki.eclipse.org/index.php/TM_and_RSE_FAQ#Working_with_TM_.2F_RSE_as_a_User\" rel=\"nofollow noreferrer\">http://wiki.eclipse.org/index.php/TM_and_RSE_FAQ#Working_with_TM_.2F_RSE_as_a_User</a></p>\n" }, { "answer_id": 248840, "author": "user21582", "author_id": 21582, "author_profile": "https://Stackoverflow.com/users/21582", "pm_score": 1, "selected": false, "text": "<p>If you want free general purpose IDE (which supports many languages,as well as Php) - then you should give a try to PsPad www.pspad.com. It can handle ftp very well\nIf you going to do alot of Php programming - then you have several dedicated (but not free) Php IDEs. PhpEd, PhpEdit, Php Designer, WeBuilder - each one of them have their pros and cons , all of them support ftp .</p>\n" }, { "answer_id": 248861, "author": "Noah Goodrich", "author_id": 20178, "author_profile": "https://Stackoverflow.com/users/20178", "pm_score": 0, "selected": false, "text": "<p>I currently have Eclipse installed with the Aptana plug-in so I have access to all of the cool features of Aptana. </p>\n\n<p>You can either install Subclipse or Subversive for Eclipse which would effectively take care of needing TortoiseSVN. See: <a href=\"http://subclipse.tigris.org/install.html\" rel=\"nofollow noreferrer\"><a href=\"http://subclipse.tigris.org/install.html\" rel=\"nofollow noreferrer\">http://subclipse.tigris.org/install.html</a></a></p>\n\n<p>Additionally, you can choose between installing and configuring PDT for Eclipse or using the Aptana PHP plugin (I've used both and I don't find that I necessarily prefer one over the other).</p>\n\n<p>Lastly, both Aptana and Eclipse provide ftp and sftp support:</p>\n\n<p><a href=\"http://www.aptana.com/plugins\" rel=\"nofollow noreferrer\"><a href=\"http://www.aptana.com/plugins\" rel=\"nofollow noreferrer\">http://www.aptana.com/plugins</a></a></p>\n\n<p><a href=\"http://www.eclipseplugincentral.com/Web_Links-index-req-viewlink-cid-857.html\" rel=\"nofollow noreferrer\"><a href=\"http://www.eclipseplugincentral.com/Web_Links-index-req-viewlink-cid-857.html\" rel=\"nofollow noreferrer\">http://www.eclipseplugincentral.com/Web_Links-index-req-viewlink-cid-857.html</a></a></p>\n" }, { "answer_id": 248898, "author": "lImbus", "author_id": 32490, "author_profile": "https://Stackoverflow.com/users/32490", "pm_score": 0, "selected": false, "text": "<p>I found <a href=\"http://www.scootersoftware.com/\" rel=\"nofollow noreferrer\">Beyond Compare of Scooter Software</a> to be a great tool for such needs.<br>\nBeyond Compare is a very valuable file and directory differ and merger for Windows and Linux which also is able to have one of the directories as ftp-link.</p>\n\n<p>Beyond Compare even has a special plugin for source control systems, which unfortunately does not interact with the server, but is able to understand conflicts, for example.</p>\n" }, { "answer_id": 248944, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 4, "selected": true, "text": "<p>I think you're doing things a bit strange.</p>\n\n<p>You already have all your information in an SVN repository, so why not take advantage of that?</p>\n\n<p>You keep a working copy on your computer for development and testing. Save and commit your changes to SVN. On your server, do an SVN <code>export</code> (or <code>checkout</code>, with appropriate server rules to block web access to the <code>.svn</code> folders), and you're sweet!</p>\n\n<pre>\n---------------------- ------------ ---------------\n| Local Working Copy | &lt;---> | SVN Repo | &lt;---> | Live server |\n---------------------- ------------ ---------------\n</pre>\n\n<p>This means you never have to worry about FTP, or have to figure out which files have been changed locally and hence need to be updated.</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/248769", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30098/" ]
I currently use Notepad++ for most of my development. I have been checking out other, more full-featured options and would like to switch (I'm in particular a fan of Aptana so far) but there is one thing about Notepad++ that I really like and I haven't been able to get so far. My current workflow is something like this: [Workflow](http://evanalyze.com/images/workflow) (I tried to embed this image and it showed up in previews but not in the post, sorry) [Workflow http://evanalyze.com/images/workflow.jpg](http://evanalyze.com/images/workflow.jpg) The process is this: 1. Download file from web server 2. Make edits in NP++ 3. Save (this automatically saves a local copy in my default directory, which is also the folder I have setup using Subversion with Tourtise SVN) 4. When I want to commit a change to SVN, go through the local folder that has an up to date copy What I can't figure out how to do with Aptana is automatically store a local copy of a file I download from my server, edit and save back to the server. Is there some way to do this? If so, that would solve my problem immediately. Other options would be a suggestion for a better way to manage the relationship between my server, my editor and my SVN repository. I know Aptana can access my SVN repository too. Is there an easy way to commit changes from within Aptana when I want to (which means I could take Tourtise out of the equation I guess)? Any suggestions appreciated. Thanks.
I think you're doing things a bit strange. You already have all your information in an SVN repository, so why not take advantage of that? You keep a working copy on your computer for development and testing. Save and commit your changes to SVN. On your server, do an SVN `export` (or `checkout`, with appropriate server rules to block web access to the `.svn` folders), and you're sweet! ``` ---------------------- ------------ --------------- | Local Working Copy | <---> | SVN Repo | <---> | Live server | ---------------------- ------------ --------------- ``` This means you never have to worry about FTP, or have to figure out which files have been changed locally and hence need to be updated.
248,789
<p>So I'm reading The Art &amp; Science of Javascript, which is a good book, and it has a good section on JSONP. I've been reading all I can about it today, and even looking through every question here on StackOverflow. JSONP is a great idea, but it only seems to resolve the "Same Origin Problem" for <i>getting</i> data, but doesn't address it for <i>changing</i> data. </p> <p>Did I just miss all the blogs that talked about this, or is JSONP <strong>not</strong> the solution I was hoping for?</p>
[ { "answer_id": 248813, "author": "Duncan", "author_id": 25035, "author_profile": "https://Stackoverflow.com/users/25035", "pm_score": 3, "selected": true, "text": "<p>JSONP results in a SCRIPT tag being generated to another server with any parameters that might be required as a GET request. e.g.</p>\n\n<pre><code>&lt;script src=\"http://myserver.com/getjson?customer=232&amp;callback=jsonp543354\" type=\"text/javascript\"&gt;\n&lt;/script&gt;\n</code></pre>\n\n<p>There is technically nothing to stop this sort of request altering data on the server, e.g. specifying newName=Tony. Your response could then be whether the update succeeded or not. You will be limited by whatever you can fit on a querystring. If you are going with this approach add some random element as a parameter so that proxy's won't cache it.</p>\n\n<p>Some people may consider this goes against the way GET's are supposed to work i.e. they shouldn't cause data to change.</p>\n" }, { "answer_id": 249007, "author": "goldenratio", "author_id": 31307, "author_profile": "https://Stackoverflow.com/users/31307", "pm_score": 0, "selected": false, "text": "<p>Yes, and honestly I would like to stick to that paradigm. However, I might bend the rule and say that, requests which do not alter/deal with CRUCIAL data will be accessible via GET calls... hm...</p>\n\n<p>For instance, I am building a shopping cart system, and I think that allowing the adding/removing/etc of items to/from a cart could very easily be exposed via GETs, since even though you can change data, you cannot do anything critical with it. If someone maliciously added 1,000 flatscreen monitors to your shopping cart, there would be at least one verification step that would NOT be vulnerable to any attacks (a standard ASP.NET page at that point, with verification and all that jazz).</p>\n\n<p>Is this a good/workable solution in anyones' opinion?</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/248789", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31307/" ]
So I'm reading The Art & Science of Javascript, which is a good book, and it has a good section on JSONP. I've been reading all I can about it today, and even looking through every question here on StackOverflow. JSONP is a great idea, but it only seems to resolve the "Same Origin Problem" for *getting* data, but doesn't address it for *changing* data. Did I just miss all the blogs that talked about this, or is JSONP **not** the solution I was hoping for?
JSONP results in a SCRIPT tag being generated to another server with any parameters that might be required as a GET request. e.g. ``` <script src="http://myserver.com/getjson?customer=232&callback=jsonp543354" type="text/javascript"> </script> ``` There is technically nothing to stop this sort of request altering data on the server, e.g. specifying newName=Tony. Your response could then be whether the update succeeded or not. You will be limited by whatever you can fit on a querystring. If you are going with this approach add some random element as a parameter so that proxy's won't cache it. Some people may consider this goes against the way GET's are supposed to work i.e. they shouldn't cause data to change.
248,830
<p>Recently I wrote a function to generate certain sequences with nontrivial constraints. The problem came with a natural recursive solution. Now it happens that, even for relatively small input, the sequences are several thousands, thus I would prefer to use my algorithm as a generator instead of using it to fill a list with all the sequences.</p> <p>Here is an example. Suppose we want to compute all the permutations of a string with a recursive function. The following naive algorithm takes an extra argument 'storage' and appends a permutation to it whenever it finds one:</p> <pre><code>def getPermutations(string, storage, prefix=""): if len(string) == 1: storage.append(prefix + string) # &lt;----- else: for i in range(len(string)): getPermutations(string[:i]+string[i+1:], storage, prefix+string[i]) storage = [] getPermutations("abcd", storage) for permutation in storage: print permutation </code></pre> <p>(Please don't care about inefficiency, this is only an example.)</p> <p>Now I want to turn my function into a generator, i.e. to yield a permutation instead of appending it to the storage list:</p> <pre><code>def getPermutations(string, prefix=""): if len(string) == 1: yield prefix + string # &lt;----- else: for i in range(len(string)): getPermutations(string[:i]+string[i+1:], prefix+string[i]) for permutation in getPermutations("abcd"): print permutation </code></pre> <p>This code does <em>not</em> work (the function behaves like an empty generator).</p> <p>Am I missing something? Is there a way to turn the above recursive algorithm into a generator <em>without replacing it with an iterative one</em>?</p>
[ { "answer_id": 248854, "author": "Markus Jarderot", "author_id": 22364, "author_profile": "https://Stackoverflow.com/users/22364", "pm_score": 8, "selected": true, "text": "<pre><code>def getPermutations(string, prefix=\"\"):\n if len(string) == 1:\n yield prefix + string\n else:\n for i in xrange(len(string)):\n for perm in getPermutations(string[:i] + string[i+1:], prefix+string[i]):\n yield perm\n</code></pre>\n\n<p>Or without an accumulator:</p>\n\n<pre><code>def getPermutations(string):\n if len(string) == 1:\n yield string\n else:\n for i in xrange(len(string)):\n for perm in getPermutations(string[:i] + string[i+1:]):\n yield string[i] + perm\n</code></pre>\n" }, { "answer_id": 248857, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 4, "selected": false, "text": "<p>The interior call to getPermutations -- it's a generator, too.</p>\n\n<pre><code>def getPermutations(string, prefix=\"\"):\n if len(string) == 1:\n yield prefix + string \n else:\n for i in range(len(string)):\n getPermutations(string[:i]+string[i+1:], prefix+string[i]) # &lt;-----\n</code></pre>\n\n<p>You need to iterate through that with a for-loop (see @MizardX posting, which edged me out by seconds!)</p>\n" }, { "answer_id": 252199, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 5, "selected": false, "text": "<p>This avoids the <code>len(string)</code>-deep recursion, and is in general a nice way to handle generators-inside-generators:</p>\n\n<pre><code>from types import GeneratorType\n\ndef flatten(*stack):\n stack = list(stack)\n while stack:\n try: x = stack[0].next()\n except StopIteration:\n stack.pop(0)\n continue\n if isinstance(x, GeneratorType): stack.insert(0, x)\n else: yield x\n\ndef _getPermutations(string, prefix=\"\"):\n if len(string) == 1: yield prefix + string\n else: yield (_getPermutations(string[:i]+string[i+1:], prefix+string[i])\n for i in range(len(string)))\n\ndef getPermutations(string): return flatten(_getPermutations(string))\n\nfor permutation in getPermutations(\"abcd\"): print permutation\n</code></pre>\n\n<p><code>flatten</code> allows us to continue progress in another generator by simply <code>yield</code>ing it, instead of iterating through it and <code>yield</code>ing each item manually.</p>\n\n<hr>\n\n<p>Python 3.3 will add <a href=\"http://docs.python.org/dev/whatsnew/3.3.html#pep-380-syntax-for-delegating-to-a-subgenerator\" rel=\"noreferrer\"><code>yield from</code></a> to the syntax, which allows for natural delegation to a sub-generator:</p>\n\n<pre><code>def getPermutations(string, prefix=\"\"):\n if len(string) == 1:\n yield prefix + string\n else:\n for i in range(len(string)):\n yield from getPermutations(string[:i]+string[i+1:], prefix+string[i])\n</code></pre>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/248830", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18770/" ]
Recently I wrote a function to generate certain sequences with nontrivial constraints. The problem came with a natural recursive solution. Now it happens that, even for relatively small input, the sequences are several thousands, thus I would prefer to use my algorithm as a generator instead of using it to fill a list with all the sequences. Here is an example. Suppose we want to compute all the permutations of a string with a recursive function. The following naive algorithm takes an extra argument 'storage' and appends a permutation to it whenever it finds one: ``` def getPermutations(string, storage, prefix=""): if len(string) == 1: storage.append(prefix + string) # <----- else: for i in range(len(string)): getPermutations(string[:i]+string[i+1:], storage, prefix+string[i]) storage = [] getPermutations("abcd", storage) for permutation in storage: print permutation ``` (Please don't care about inefficiency, this is only an example.) Now I want to turn my function into a generator, i.e. to yield a permutation instead of appending it to the storage list: ``` def getPermutations(string, prefix=""): if len(string) == 1: yield prefix + string # <----- else: for i in range(len(string)): getPermutations(string[:i]+string[i+1:], prefix+string[i]) for permutation in getPermutations("abcd"): print permutation ``` This code does *not* work (the function behaves like an empty generator). Am I missing something? Is there a way to turn the above recursive algorithm into a generator *without replacing it with an iterative one*?
``` def getPermutations(string, prefix=""): if len(string) == 1: yield prefix + string else: for i in xrange(len(string)): for perm in getPermutations(string[:i] + string[i+1:], prefix+string[i]): yield perm ``` Or without an accumulator: ``` def getPermutations(string): if len(string) == 1: yield string else: for i in xrange(len(string)): for perm in getPermutations(string[:i] + string[i+1:]): yield string[i] + perm ```
248,838
<p>I need to write an extension method on a byte[]. Is that possible?</p>
[ { "answer_id": 248843, "author": "Greg Beech", "author_id": 13552, "author_profile": "https://Stackoverflow.com/users/13552", "pm_score": 1, "selected": false, "text": "<p>Sure, just make the first parameter of type <code>byte[]</code>.</p>\n" }, { "answer_id": 248866, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 4, "selected": true, "text": "<p>yes, just do :</p>\n\n<pre><code>public static class Extensions\n{\n public static void Method(this byte[] current)\n {\n\n }\n}\n</code></pre>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/248838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3279/" ]
I need to write an extension method on a byte[]. Is that possible?
yes, just do : ``` public static class Extensions { public static void Method(this byte[] current) { } } ```
248,864
<p>I have a MySQL database table with a couple thousand rows. The table is setup like so:</p> <p><code>id | text</code></p> <p>The <code>id</code> column is an auto-incrementing integer, and the <code>text</code> column is a 200-character varchar.</p> <p>Say I have the following rows:</p> <p><code>3 | I think I'll have duck tonight</code></p> <p><code>4 | Maybe the chicken will be alright</code></p> <p><code>5 | I have a pet duck now, awesome!</code></p> <p><code>6 | I love duck</code></p> <p>Then the list I'm wanting to generate might be something like:</p> <ul> <li>3 occurrences of 'duck'</li> <li>3 occurrences of 'I'</li> <li>2 occurrences of 'have'</li> <li>1 occurrences of 'chicken'</li> <li>.etc .etc</li> </ul> <p>Plus, I'll probably want to maintain a list of substrings to ignore from the list, like 'I', 'will' and 'have. It's important to note that I do not know what people will post.</p> <p>I do not have a list of words that I want to monitor, I just want to find the most common substrings. I'll then filter out any erroneous substrings that are not interesting from the list manually by editing the query.</p> <p>Can anyone suggest the best way to do this? Thanks everyone!</p>
[ { "answer_id": 248873, "author": "Corey Trager", "author_id": 9328, "author_profile": "https://Stackoverflow.com/users/9328", "pm_score": 0, "selected": false, "text": "<p>Extract to flat file and then use your favorite quick language, perl, python, ruby, etc to process the flat file.</p>\n\n<p>If you don't have one these languages as part of your skillset, this is a perfect little task to start using one, and it won't take you long.</p>\n\n<p>Some database tasks are just so much easier to do OUTSIDE of the database.</p>\n" }, { "answer_id": 248887, "author": "Bob Probst", "author_id": 12424, "author_profile": "https://Stackoverflow.com/users/12424", "pm_score": 0, "selected": false, "text": "<p>You might want to look into the MySQL <a href=\"http://dev.mysql.com/doc/refman/5.1/en/plugin-full-text-plugins.html\" rel=\"nofollow noreferrer\">Full-Text Parser Plugins</a></p>\n" }, { "answer_id": 249366, "author": "rwired", "author_id": 17492, "author_profile": "https://Stackoverflow.com/users/17492", "pm_score": 3, "selected": true, "text": "<p>MySQL already does this for you.</p>\n\n<p>First make sure your table is a MyISAM table</p>\n\n<p>Define a FULLTEXT index on your column</p>\n\n<p>On a shell command line navigate to the folder where your MySQL data is stored, then type:</p>\n\n<pre><code>myisam_ftdump -c yourtablename 1 &gt;wordfreq.dump\n</code></pre>\n\n<p>You can then process wordfreq.dump to eliminate the unwanted column and sort by frequency decending.</p>\n\n<p>You could do all the above with a single command line and some sed/awk wizardry no doubt.\nAnd you could incorporate it into your program without needing a dump file.</p>\n\n<p>More info on myisam_ftdump here: \n<a href=\"http://dev.mysql.com/doc/refman/5.0/en/myisam-ftdump.html\" rel=\"nofollow noreferrer\">http://dev.mysql.com/doc/refman/5.0/en/myisam-ftdump.html</a></p>\n\n<p>Oh... one more thing, the stopwords for MySQL are precompiled into the engine.\nAnd words with 3 or less characters are not indexed.\nThe full list is here:</p>\n\n<p><a href=\"http://dev.mysql.com/doc/refman/5.0/en/fulltext-stopwords.html\" rel=\"nofollow noreferrer\">http://dev.mysql.com/doc/refman/5.0/en/fulltext-stopwords.html</a></p>\n\n<p>If this list isn't adequate for your needs, or you need words with less than 3 characters to count, the only way is to recompile MySQL with different rules for FULLTEXT. I don't recommend that!</p>\n" } ]
2008/10/29
[ "https://Stackoverflow.com/questions/248864", "https://Stackoverflow.com", "https://Stackoverflow.com/users/326176/" ]
I have a MySQL database table with a couple thousand rows. The table is setup like so: `id | text` The `id` column is an auto-incrementing integer, and the `text` column is a 200-character varchar. Say I have the following rows: `3 | I think I'll have duck tonight` `4 | Maybe the chicken will be alright` `5 | I have a pet duck now, awesome!` `6 | I love duck` Then the list I'm wanting to generate might be something like: * 3 occurrences of 'duck' * 3 occurrences of 'I' * 2 occurrences of 'have' * 1 occurrences of 'chicken' * .etc .etc Plus, I'll probably want to maintain a list of substrings to ignore from the list, like 'I', 'will' and 'have. It's important to note that I do not know what people will post. I do not have a list of words that I want to monitor, I just want to find the most common substrings. I'll then filter out any erroneous substrings that are not interesting from the list manually by editing the query. Can anyone suggest the best way to do this? Thanks everyone!
MySQL already does this for you. First make sure your table is a MyISAM table Define a FULLTEXT index on your column On a shell command line navigate to the folder where your MySQL data is stored, then type: ``` myisam_ftdump -c yourtablename 1 >wordfreq.dump ``` You can then process wordfreq.dump to eliminate the unwanted column and sort by frequency decending. You could do all the above with a single command line and some sed/awk wizardry no doubt. And you could incorporate it into your program without needing a dump file. More info on myisam\_ftdump here: <http://dev.mysql.com/doc/refman/5.0/en/myisam-ftdump.html> Oh... one more thing, the stopwords for MySQL are precompiled into the engine. And words with 3 or less characters are not indexed. The full list is here: <http://dev.mysql.com/doc/refman/5.0/en/fulltext-stopwords.html> If this list isn't adequate for your needs, or you need words with less than 3 characters to count, the only way is to recompile MySQL with different rules for FULLTEXT. I don't recommend that!
248,900
<p>When I press the standard Ctrl + E, C (an other variants) in VS2008 whilst editing a CSS file, it says that command is not available. How do I setup a shortcut to apply a plain old /* */ comment to selected text in VS? Thanks</p>
[ { "answer_id": 249339, "author": "Jeff Hillman", "author_id": 3950, "author_profile": "https://Stackoverflow.com/users/3950", "pm_score": 4, "selected": true, "text": "<p>Within Visual Studio, hit Alt-F11 to open the Macro IDE and add a new module by right-clicking on MyMacros and selecting Add|Add Module...</p>\n\n<p>Paste the following in the source editor:</p>\n\n<pre><code>Imports System\nImports EnvDTE\nImports EnvDTE80\nImports EnvDTE90\nImports System.Diagnostics\n\nPublic Module CommentCSS\n Sub CommentCSS()\n Dim selection As TextSelection\n selection = DTE.ActiveDocument.Selection\n\n Dim selectedText As String\n selectedText = selection.Text\n\n If selectedText.Length &gt; 0 Then\n selection.Text = \"/*\" + selectedText + \"*/\"\n End If\n End Sub\nEnd Module\n</code></pre>\n\n<p>You can create a keyboard shortcut by going to Tools|Options... and selecting <strong>Keyboard</strong> under the <strong>Environment</strong> section in the navigation on the left. Select your macro and assign any shortcut you like. </p>\n\n<p>You can also add your macro to a menu or toolbar by going to Tools|Customize... and selecting the <strong>Macros</strong> section in the navigation on the left. Once you locate your macro in the list, you can drag it to any menu or toolbar, where it its text or icon can be customized to whatever you want.</p>\n" }, { "answer_id": 1080342, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>here's an even simpler solution:</p>\n\n<pre><code>Sub CommentCSS()\n DTE.ActiveDocument.Selection.StartOfLine(VsStartOfLineOptions.VsStartOfLineOptionsFirstText)\n DTE.ActiveDocument.Selection.Text = \"/*\"\n DTE.ActiveDocument.Selection.EndOfLine()\n DTE.ActiveDocument.Selection.Text = \"*/\"\nEnd Sub\n</code></pre>\n\n<p>you can record it yourself using ctrl+shift+R</p>\n\n<ol>\n<li>place the cursor on the line you want to comment</li>\n<li>press \"Home\" on your keyboard</li>\n<li>type /*</li>\n<li>press \"End\" on your keyboard</li>\n<li>type */</li>\n<li>save your recording</li>\n</ol>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/248900", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1692/" ]
When I press the standard Ctrl + E, C (an other variants) in VS2008 whilst editing a CSS file, it says that command is not available. How do I setup a shortcut to apply a plain old /\* \*/ comment to selected text in VS? Thanks
Within Visual Studio, hit Alt-F11 to open the Macro IDE and add a new module by right-clicking on MyMacros and selecting Add|Add Module... Paste the following in the source editor: ``` Imports System Imports EnvDTE Imports EnvDTE80 Imports EnvDTE90 Imports System.Diagnostics Public Module CommentCSS Sub CommentCSS() Dim selection As TextSelection selection = DTE.ActiveDocument.Selection Dim selectedText As String selectedText = selection.Text If selectedText.Length > 0 Then selection.Text = "/*" + selectedText + "*/" End If End Sub End Module ``` You can create a keyboard shortcut by going to Tools|Options... and selecting **Keyboard** under the **Environment** section in the navigation on the left. Select your macro and assign any shortcut you like. You can also add your macro to a menu or toolbar by going to Tools|Customize... and selecting the **Macros** section in the navigation on the left. Once you locate your macro in the list, you can drag it to any menu or toolbar, where it its text or icon can be customized to whatever you want.
248,903
<p>Is there any way to determine if an object is a generic list? I'm not going to know the type of the list, I just know it's a list. How can I determine that?</p>
[ { "answer_id": 248912, "author": "bioskope", "author_id": 29414, "author_profile": "https://Stackoverflow.com/users/29414", "pm_score": -1, "selected": false, "text": "<p>Theres a GetType() function in the System.Object class. Have you tried that?</p>\n" }, { "answer_id": 248915, "author": "Andrew Theken", "author_id": 32238, "author_profile": "https://Stackoverflow.com/users/32238", "pm_score": 2, "selected": false, "text": "<p>Try:</p>\n\n<pre><code>if(yourList.GetType().IsGenericType)\n{\n var genericTypeParams = yourList.GetType().GetGenericArguments;\n //do something interesting with the types..\n}\n</code></pre>\n" }, { "answer_id": 248918, "author": "Timothy Khouri", "author_id": 11917, "author_profile": "https://Stackoverflow.com/users/11917", "pm_score": 6, "selected": true, "text": "<p>This will return \"True\"</p>\n\n<pre><code>List&lt;int&gt; myList = new List&lt;int&gt;();\n\nConsole.Write(myList.GetType().IsGenericType &amp;&amp; myList is IEnumerable);\n</code></pre>\n\n<p>Do you care to know if it's exactly a \"List\"... or are you ok with it being IEnumerable, and Generic?</p>\n" }, { "answer_id": 248922, "author": "Nathan Baulch", "author_id": 8799, "author_profile": "https://Stackoverflow.com/users/8799", "pm_score": 3, "selected": false, "text": "<p>The following method will return the item type of a generic collection type.\nIf the type does not implement ICollection&lt;> then null is returned.</p>\n\n<pre><code>static Type GetGenericCollectionItemType(Type type)\n{\n if (type.IsGenericType)\n {\n var args = type.GetGenericArguments();\n if (args.Length == 1 &amp;&amp;\n typeof(ICollection&lt;&gt;).MakeGenericType(args).IsAssignableFrom(type))\n {\n return args[0];\n }\n }\n return null;\n}\n</code></pre>\n\n<p><strong>Edit:</strong> The above solution assumes that the specified type has a generic parameter of its own. This will not work for types that implement ICollection&lt;> with a hard coded generic parameter, for example:</p>\n\n<pre><code>class PersonCollection : List&lt;Person&gt; {}\n</code></pre>\n\n<p>Here is a new implementation that will handle this case. </p>\n\n<pre><code>static Type GetGenericCollectionItemType(Type type)\n{\n return type.GetInterfaces()\n .Where(face =&gt; face.IsGenericType &amp;&amp;\n face.GetGenericTypeDefinition() == typeof(ICollection&lt;&gt;))\n .Select(face =&gt; face.GetGenericArguments()[0])\n .FirstOrDefault();\n}\n</code></pre>\n" }, { "answer_id": 250239, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 0, "selected": false, "text": "<p>The question is ambiguous.</p>\n\n<p>The answer depends on what you mean by a generic list.</p>\n\n<ul>\n<li><p>A List&lt;SomeType&gt; ?</p></li>\n<li><p>A class that derives from List&lt;SomeType&gt; ?</p></li>\n<li><p>A class that implements IList&lt;SomeType&gt; (in which case an array can be considered to be a generic list - e.g. int[] implements IList&lt;int&gt;)?</p></li>\n<li><p>A class that is generic and implements IEnumerable (this is the test proposed in the <a href=\"https://stackoverflow.com/questions/248903/if-object-is-generic-list#248918\">accepted answer</a>)? But this will also consider the following rather pathological class to be a generic list:</p></li>\n</ul>\n\n<p>.</p>\n\n<pre><code>public class MyClass&lt;T&gt; : IEnumerable\n{\n IEnumerator IEnumerable.GetEnumerator()\n {\n return null;\n }\n}\n</code></pre>\n\n<p>The best solution (e.g. whether to use GetType, IsAssignableFrom, etc) will depend on what you mean.</p>\n" }, { "answer_id": 35539113, "author": "Stanislav Trifan", "author_id": 1653988, "author_profile": "https://Stackoverflow.com/users/1653988", "pm_score": 2, "selected": false, "text": "<p>The accepted answer doesn't guarantee the type of IList&lt;>.\nCheck this version, it works for me:</p>\n\n<pre><code>private static bool IsList(object value)\n{\n var type = value.GetType();\n var targetType = typeof (IList&lt;&gt;);\n return type.GetInterfaces().Any(i =&gt; i.IsGenericType \n &amp;&amp; i.GetGenericTypeDefinition() == targetType);\n}\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/248903", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11137/" ]
Is there any way to determine if an object is a generic list? I'm not going to know the type of the list, I just know it's a list. How can I determine that?
This will return "True" ``` List<int> myList = new List<int>(); Console.Write(myList.GetType().IsGenericType && myList is IEnumerable); ``` Do you care to know if it's exactly a "List"... or are you ok with it being IEnumerable, and Generic?
248,911
<p>I have a single HW interface I want to use from two applications (processes) on the same workstation. The HW requires a single initialization call then either app uses the same function (in the same library) to do many transactions with the HW. </p> <p>So each app should act like this:</p> <pre><code>main() // I don't know if another app already init'ed the HW ret = hw_init_lock(non-blocking) if ret = OK // no one else has done this, I have to init_hw() else //someone else has already init'ed the HW, I gotta make sure it stays that way //as long as I'm alive increment_hw_init_ref_counter() hw_trans_lock(blocking) hw_trans() hw_trans_unlock() .... //exit app, uninit hw if we are last out ret = decrement_hw_init_ref_counter() if ret == 0 uninit_hw() exit(0) </code></pre> <p>What is the mechanism I can use in the lock and reference count calls that is shared between two applications? I'm thinking named pipes i.e. mkfifo(). </p>
[ { "answer_id": 248930, "author": "florin", "author_id": 18308, "author_profile": "https://Stackoverflow.com/users/18308", "pm_score": 2, "selected": false, "text": "<p>Use the <a href=\"http://www.opengroup.org/onlinepubs/000095399/basedefs/semaphore.h.html\" rel=\"nofollow noreferrer\">POSIX semaphores</a>.</p>\n" }, { "answer_id": 248980, "author": "kenny", "author_id": 3225, "author_profile": "https://Stackoverflow.com/users/3225", "pm_score": 2, "selected": false, "text": "<p>Since you only need a semaphore count of one, a mutex suffices.</p>\n" }, { "answer_id": 249072, "author": "albertb", "author_id": 26715, "author_profile": "https://Stackoverflow.com/users/26715", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://linux.die.net/man/7/sem_overview\" rel=\"noreferrer\">POSIX semaphore</a> is the way to go. Since you want to share the same semaphore across processes, you need to use a named semaphore.:</p>\n\n<blockquote>\n <p>A named semaphore is identified by a\n name of the form /somename. Two\n processes can operate on the same\n named semaphore by passing the same\n name to sem_open(3).</p>\n</blockquote>\n" }, { "answer_id": 249081, "author": "Andrew Edgecombe", "author_id": 11694, "author_profile": "https://Stackoverflow.com/users/11694", "pm_score": 1, "selected": false, "text": "<p>I assume that </p>\n\n<blockquote>\n <p>...that is shared between two applications?</p>\n</blockquote>\n\n<p>means that you want these two things to be running as separate processes? If that's not true, and they are running as a single process (with multiple threads), then the suggestions of semaphores and mutexes are the best option and should be quite straightforward.</p>\n\n<p>Note that the answer will depend on exactly how you're accessing this hardware. For example, if it's exposed through a file then normal file locking can be used.</p>\n\n<p>However if you're attempting to synchronise access to the hardware across two processes that's a different matter.\nI guess the first thing to say is that it's going to be easier to synchronise, if you can, to have a single process in charge of accessing the hardware. In this model you might have one process that acts as a server for the hardware - accepting requests from other processes and performing the reads and writes on their behalf.\nJust about any form of interprocess communications will be suitable, but for simplicity something like the message queue (<a href=\"http://tldp.org/LDP/tlk/ipc/ipc.html\" rel=\"nofollow noreferrer\">link</a>) may be appropriate with some appropriate data structure (eg. a flag to indicate whether it's a read or write operation, offset from base address of your hardware, number of bytes, buffer (in case of a write))</p>\n\n<p>If putting all of the direct hardware access into a single process isn't appropriate then you'll have to use a proper synchronisation scheme.\nI would investigate the use of either file locks (and implement a rudimentary mutex scheme), or using named semaphores (as albertb has suggested)</p>\n" }, { "answer_id": 249400, "author": "bog", "author_id": 20909, "author_profile": "https://Stackoverflow.com/users/20909", "pm_score": 2, "selected": false, "text": "<p>Semaphores and Mutexes/condition variables are good, very high-performance primitives which are appropriate for use in between threads or in between processes.</p>\n\n<p>All of these are based on the idea (and usually, on the reality) of test-and-set or other atomic operations performed upon shared memory.</p>\n\n<p>If you expect to distribute your processes over the network, then semaphores and mutexes may not be right for you--they only work on a single machine. Pipes and sockets are more generally network-extensible.</p>\n\n<p>A brief summary of mutexes, condition variables and semaphores:</p>\n\n<p><strong>Mutexes</strong></p>\n\n<p>A mutex is a primitive which can be either locked, or unlocked. The process/thread which locked it must be the one to unlock it. This <em>ownership</em> aspect allows the operating system to apply some interesting optimizations, such as priority inheritance and priority ceiling protocol (to avoid priority inversion). <strong>however</strong>, the mutex does not have a count associated with it. You can't lock an already locked-mutex, in general, and retain memory that it was \"locked twice\" (there are some extensions that allow this, I think, but they are not available everywhere)</p>\n\n<p><strong>Condition Variables</strong></p>\n\n<p>A mutex is great for...well, MUTual EXclusion. But what if you need to block on a condition associated with the object to which you have mutual exclusion? For this, you use a condition variable, or CV. A CV is associated with a mutex. For example, say I have a queue of input data which my processes want to access. One grabs the mutex so it can look at the queue without fear of interference. However, it finds the queue empty and wants to wait for something to come in on the queue. It therefore waits on the \"queue not empty\" condition variable. The interesting part here is that, because the CV is associated with the mutex, the mutex gets <em>automatically re-acquired</em> once the condition variable is signalled. Thus, once the process wakes up after waiting on the CV, it knows that it has exclusive access again to the queue. What it does <em>not</em> know is whether the queue really has anything on it--perhaps two processes waited on the CV--one thing came in--and the first priority got in and dequeued the \"thing\" before the second thing woke up. Thus, whenever you use a CV, you need to RECHECK the condition, like this:</p>\n\n<pre><code>mutex_enter(m);\nwhile (! condition) {\n cond_wait(m, c); // drop mutex lock; wait on cv; reacquire mutex\n}\n//processing related to condition\nmutex_exit(m);\n</code></pre>\n\n<p><strong>Semaphores</strong></p>\n\n<p>OK, that is mutexes and condition variables. Semaphores are simpler. They can be incremented and decremented by any processes. They have memory--they count--so you can use them to determine how many of a condition have occurred. Not so with condiiton variables. Also, because semaphores can be decremented by one process and incremented by another, they do not have the ownership aspect--so no priority inheritance, no priority inversion avoidance is possible.</p>\n\n<p>Now, finally--all of these mechanisms require shared memory for an efficient implementation. This may be fine for you, but be aware--if you believe that your appliction may eventually be distributed, then mutexes, condition variables and semaphores may not be for you. Pipes and sockets, while much higher-overhead, have the possibility of being extended over the network fairly straightforwardly.</p>\n" }, { "answer_id": 29265167, "author": "Ritesh", "author_id": 2073349, "author_profile": "https://Stackoverflow.com/users/2073349", "pm_score": 2, "selected": false, "text": "<p>I think if we want to synchronize the multiple running processes, then we can use a very easy technique called file locks.</p>\n\n<p>Please refer to this article for more details:\n<a href=\"http://blog.markedup.com/2014/07/easy-mode-synchronizing-multiple-processes-with-file-locks/\" rel=\"nofollow\">http://blog.markedup.com/2014/07/easy-mode-synchronizing-multiple-processes-with-file-locks/</a></p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/248911", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23961/" ]
I have a single HW interface I want to use from two applications (processes) on the same workstation. The HW requires a single initialization call then either app uses the same function (in the same library) to do many transactions with the HW. So each app should act like this: ``` main() // I don't know if another app already init'ed the HW ret = hw_init_lock(non-blocking) if ret = OK // no one else has done this, I have to init_hw() else //someone else has already init'ed the HW, I gotta make sure it stays that way //as long as I'm alive increment_hw_init_ref_counter() hw_trans_lock(blocking) hw_trans() hw_trans_unlock() .... //exit app, uninit hw if we are last out ret = decrement_hw_init_ref_counter() if ret == 0 uninit_hw() exit(0) ``` What is the mechanism I can use in the lock and reference count calls that is shared between two applications? I'm thinking named pipes i.e. mkfifo().
[POSIX semaphore](http://linux.die.net/man/7/sem_overview) is the way to go. Since you want to share the same semaphore across processes, you need to use a named semaphore.: > > A named semaphore is identified by a > name of the form /somename. Two > processes can operate on the same > named semaphore by passing the same > name to sem\_open(3). > > >
248,938
<p>I am looking to parse a URL to obtain a collection of the querystring parameters in Java. To be clear, I need to parse a given URL(or string value of a URL object), not the URL from a servlet request. </p> <p>It looks as if the <code>javax.servlet.http.HttpUtils.parseQueryString</code> method would be the obvious choice, but it has been deprecated.</p> <p>Is there an alternative method that I am missing, or has it just been deprecated without an equivalent replacement/enhanced function?</p>
[ { "answer_id": 248965, "author": "Vincent Ramdhanie", "author_id": 27439, "author_profile": "https://Stackoverflow.com/users/27439", "pm_score": 3, "selected": false, "text": "<p>I think the idea is to use the HttpServletRequest instead. There is the getParameterMap(), getParameterNames() and getParameterValues() methods to start.</p>\n\n<p>There is also the getParameter(String paramname) method to get the value of a specific method.</p>\n\n<p>These make no distinction between querystring parameters and form parameters though so if your intention was to look for a querystring in aparticular then I guess this wouldn't help.</p>\n" }, { "answer_id": 249774, "author": "Jack Leow", "author_id": 31506, "author_profile": "https://Stackoverflow.com/users/31506", "pm_score": 0, "selected": false, "text": "<p>As far as I know, there isn't one.</p>\n\n<p>It shouldn't be too difficult to write one yourself though. The hardest part, I imagine, would be decoding the URL name/values (which really isn't that hard, if you think about it), and you can use <a href=\"http://java.sun.com/j2se/1.4.2/docs/api/java/net/URLDecoder.html#decode(java.lang.String,%20java.lang.String)\" rel=\"nofollow noreferrer\"><code>java.net.URLDecoder#decodeURL(String,String)</code></a> for that.</p>\n" }, { "answer_id": 249781, "author": "gizmo", "author_id": 9396, "author_profile": "https://Stackoverflow.com/users/9396", "pm_score": 3, "selected": true, "text": "<p>Well, as you mention that the URL does not come from a servlet request, the right answer is, as usual, <strong>it depends</strong>.</p>\n\n<p>The problem with query part of an url is that there is no clear specification about how to handle parameters duplication.</p>\n\n<p>For example, consider an url like this one:</p>\n\n<pre><code>http://www.example.com?param1=value1&amp;param2=value2&amp;param1=value3\n</code></pre>\n\n<p>What do you expect as a value for param1? the first value, the last one, an array? The issue is that, according to the specs, all these answers are valid and server vendor are free to support one of these or another. Some use the param1[] notation to indicate that it has to be treated as an array, but again, this is not a unified solution.</p>\n\n<p>So the \"best\" solution is to know how your destination handle parameters, and mimic the behaviour with a self-made utility class.</p>\n" }, { "answer_id": 5972858, "author": "Mark St. John", "author_id": 749806, "author_profile": "https://Stackoverflow.com/users/749806", "pm_score": 2, "selected": false, "text": "<p>Use <a href=\"http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/client/utils/URLEncodedUtils.html#parse%28org.apache.http.HttpEntity%29\" rel=\"nofollow\">org.apache.http.client.utils.URLEncodedUtils.html#parse(org.apache.http.HttpEntity)</a></p>\n" }, { "answer_id": 59140594, "author": "Richard", "author_id": 565319, "author_profile": "https://Stackoverflow.com/users/565319", "pm_score": 0, "selected": false, "text": "<p>For all Kotlin lovers i came up with this:</p>\n\n<pre><code>fun splitQuery(url: URL): Map&lt;String, List&lt;String?&gt;&gt; = url.query?.let {\n it.split(\"&amp;\").map {\n it.split(\"=\").let {\n Pair(it[0], it.getOrNull(1))\n }\n }.groupBy({ it.first }, {\n it.second\n })\n } ?: emptyMap()\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/248938", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14419/" ]
I am looking to parse a URL to obtain a collection of the querystring parameters in Java. To be clear, I need to parse a given URL(or string value of a URL object), not the URL from a servlet request. It looks as if the `javax.servlet.http.HttpUtils.parseQueryString` method would be the obvious choice, but it has been deprecated. Is there an alternative method that I am missing, or has it just been deprecated without an equivalent replacement/enhanced function?
Well, as you mention that the URL does not come from a servlet request, the right answer is, as usual, **it depends**. The problem with query part of an url is that there is no clear specification about how to handle parameters duplication. For example, consider an url like this one: ``` http://www.example.com?param1=value1&param2=value2&param1=value3 ``` What do you expect as a value for param1? the first value, the last one, an array? The issue is that, according to the specs, all these answers are valid and server vendor are free to support one of these or another. Some use the param1[] notation to indicate that it has to be treated as an array, but again, this is not a unified solution. So the "best" solution is to know how your destination handle parameters, and mimic the behaviour with a self-made utility class.
248,949
<p>We have a character LCD (www.cloverlcd.com/pdf/S6A0069.pdf) that we got to work in 8 bit mode. However, now we are trying to get it to work in 4 bit mode but it doesn't seem to be displaying anything. I think the function set instruction isn't been written. Can somebody please check if I am approaching this the right way? I'll post my 8 bit code (which is working) and my 4 bit code (which I'm trying to get to work)</p> <pre> //8 bit working COMPortC(0x3C); //function set Delay1KTCYx(10); COMPortC(0x0F); //Turn on display and configure cursor settings Delay1KTCYx(10); COMPortC(0x01); //clear display Delay1KTCYx(10); COMPortC(0x06); //increment mode and increment direction (entry mode set) Delay1KTCYx(10); COMPortC(0x02); //Return Home //4 bit COMPortC(0x20); //function set Delay1KTCYx(10); COMPortC(0x20); //function set Delay1KTCYx(10); COMPortC(0x80); //function set Delay1KTCYx(10); COMPortC(0x00); //Turn on display and configure cursor settings Delay1KTCYx(10); COMPortC(0xF0); //Turn on display and configure cursor settings Delay1KTCYx(10); </pre>
[ { "answer_id": 248975, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 1, "selected": false, "text": "<p>It looks okay up to a point but I wonder about a couple of things:</p>\n\n<p>1/ Why do you output 0x20 twice to set the CGRAM address in the 4-bit section? Surely this is needed only once.</p>\n\n<p>2/ The other two writes (0x00 and 0xf0), I don't understand from the docs. Can you fix up the comments to indicate what they're meant to be doing?</p>\n\n<p>3/ Once you switch to 4-bit mode, do you need to redo the other instructions (the increment and return home)? It may be that switching modes resets all the data.</p>\n\n<p>4/ One thing I did notice is that the busy flag indicates the system cannot yet receive another instruction. It may be that you're passing them in too fast. What happens when you increase the delays from 10 to 100.</p>\n\n<p>Just some things to try - let us know the outcomes.</p>\n\n<p>=====</p>\n\n<p>RESPONSE:</p>\n\n<p>Thanks for the reply</p>\n\n<p>1 and 2) I am writing these values based on page 29 of the datasheet (www.cloverlcd.com/pdf/S6A0069.pdf).</p>\n\n<p>3) You are right, I do need to do the other instructions as well but for now, I am just trying to get the cursor to blink in 4 bit mode (so the first two instructions are sufficient)</p>\n\n<p>4) I just tried the 100 delays, it didn't work.</p>\n\n<p>Sorry for the bad comments, I'll try to post better code next time.</p>\n\n<p>Thanks</p>\n\n<p>=====</p>\n\n<p>EDIT:</p>\n\n<p>I see how it works now. In 4-bit mode, it only uses d7,d6,d5,d4 but every instruction is 2 writes (to make a 8-bit instruction). So it uses a trick to write the instruction 20 (in 8-bit mode) or 22 (2020 in 4-bit mode) both of which set the mode to 4-bit. Very clever, Samsung, I'm impressed.</p>\n\n<p>Try to go through the entire init sequence. It may be that the display doesn't fully start until initialization is complete.</p>\n\n<p>So you need to output (hex) 20,20,80,00,f0,<strong>00,10,00,60,00,20</strong>. The bold ones are the ones you need to add.</p>\n\n<p>Also, I need to ask two more questions (please reply as a comment to this answer rather than posting another answer)</p>\n\n<p>1/ Does COMPortC() actually check the busy signal before outputting data?</p>\n\n<p>2/ The delay of 10, what unit is it in, millisecs, microsecs, etc?</p>\n" }, { "answer_id": 248986, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>1 and 2) I am writing these values based on page 29 of the datasheet (www.cloverlcd.com/pdf/S6A0069.pdf).</p>\n\n<p>3) You are right, I do need to do the other instructions as well but for now, I am just trying to get the cursor to blink in 4 bit mode (so the first two instructions are sufficient)</p>\n\n<p>4) I just tried the 100 delays, it didn't work.</p>\n" }, { "answer_id": 249038, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Here is a better commented piece of code for the 4 bit mode</p>\n\n<pre>\n COMPortC(0x20); //function set first nibble \n Delay1KTCYx(10);\n COMPortC(0x20); //function set second nibble \n Delay1KTCYx(10);\n COMPortC(0x80); //function set third nibble \n Delay1KTCYx(10);\n\n COMPortC(0x00); //Turn on display and configure cursor settings first nibble\n Delay1KTCYx(10);\n COMPortC(0xF0); //Turn on display and configure cursor settings second nibble\n Delay1KTCYx(10);\n</pre>\n\n<p>I still don't know what's wrong. Also, on page 18 of the datasheet, it shows a timing diagram that is almost identical to the timing diagram of the 8 bit mode, except that there is an AC3. What does that AC3 mean?</p>\n" }, { "answer_id": 249284, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<pre>\nvoid LCDInitialization(void)\n{\n\n COMPortCWithoutBusy(0x20); //function set first nibble \n Delay1KTCYx(10);\n COMPortCWithoutBusy(0x20); //function set second nibble \n Delay1KTCYx(10);\n BusyEnable();\n Delay1KTCYx(10);\n\n COMPortCWithoutBusy(0x80); //function set third nibble \n Delay1KTCYx(10);\n BusyEnable();\n Delay1KTCYx(10);\n\n COMPortCWithoutBusy(0x00); //Turn on display and configure cursor settings first nibble\n Delay1KTCYx(10);\n COMPortCWithoutBusy(0xF0); //Turn on display and configure cursor settings second nibble\n Delay1KTCYx(10);\n BusyEnable();\n Delay1KTCYx(10);\n\n COMPortCWithoutBusy(0x00); //disp clear first nibble \n Delay1KTCYx(10);\n COMPortCWithoutBusy(0x10); //disp clear second nibble \n Delay1KTCYx(10);\n BusyEnable();\n Delay1KTCYx(10);\n\n COMPortCWithoutBusy(0x00); //entry mode set first nibble \n Delay1KTCYx(10);\n COMPortCWithoutBusy(0x60); //entry mode set second nibble \n Delay1KTCYx(10);\n BusyEnable();\n Delay1KTCYx(10);\n\n COMPortCWithoutBusy(0x20); //20 first nibble \n Delay1KTCYx(10);\n BusyEnable();\n Delay1KTCYx(10);\n}</pre>\n" }, { "answer_id": 249541, "author": "kenny", "author_id": 3225, "author_profile": "https://Stackoverflow.com/users/3225", "pm_score": 1, "selected": false, "text": "<p>I'm not sure how your 4 bits are hooked up, but my guess is.... Since you are sending the bits on the upper nibble (0x*0 - where the star is), that you likely want to use the lower or least significant nibble which would be 0x0*.</p>\n\n<pre><code>COMPortCWithoutBusy(0x02); //function set first nibble \nDelay1KTCYx(10);\nCOMPortCWithoutBusy(0x02); //function set second nibble \nDelay1KTCYx(10);\nBusyEnable();\nDelay1KTCYx(10);\n...\n</code></pre>\n" }, { "answer_id": 799357, "author": "Adam Davis", "author_id": 2915, "author_profile": "https://Stackoverflow.com/users/2915", "pm_score": 0, "selected": false, "text": "<p>This is just another variant of the HD44780 LCD driver, and as such it should work fine with the following initialization routine:</p>\n\n<pre><code>void initlcd(void)\n{\n delayms(20); // Wait for LCD to power up ( &gt;15ms )\n RS=0; // Set RS low for instruction \n write4(3); // Set interface to 8 bits \n delayms(5); // Wait for LCD execute instruction ( &gt;4.1ms )\n write4(3); // Set interface to 8 bits \n delayms(1); // Wait for LCD execute instruction ( &gt;100us )\n write4(3); // Set interface to 8 bits \n delayms(5); // Wait for LCD execute instruction (At this point \n // we could actually start using the busy flag) \n write4(2); // Set the display to 4 bit interface \n delayms(5); // Wait for LCD execute instruction \n write8(0x28); // Set the display to two line and ???\n delayms(5); // Wait for LCD execute instruction \n write8(6); // ???\n delayms(5); // Wait for LCD execute instruction \n write8(1); // Clear the LCD\n delayms(5); // Wait for LCD execute instruction\n write8(0xf); // ???\n delayms(5); // Wait for LCD execute instruction\n return;\n}\n</code></pre>\n\n<p>You'll need to define your own write4, write8, and delayms functions, but they are relatively easy. Make sure you have the register select (RS) set to command mode. write4 sends one 4 bit command, while write 8 sends two four bit commands in a row, high nibble first, then low nibble:</p>\n\n<pre><code>void write8(uns8 byte)\n{\n uns8 nibble;\n nibble = (byte &amp; 0xf0) &gt;&gt; 4; // Rotate the high 4 bits (7-4) of byte into bits (3-0) of nibble\n write4(nibble); // Write the high 4 bits to the LCD\n nibble = byte &amp; 0xf; // Copy the low four bits of byte into the low four bits of nibble\n write4(nibble); // Write the low 4 bits to the LCD\n}\n</code></pre>\n\n<p>The <a href=\"http://ubasics.com/adam/electronics/lcd/cc5xlcd.c\" rel=\"nofollow noreferrer\">code</a> I wrote is meant for the PIC microcontroller, using the free version of the cc5x compiler. Should be understandable and portable to other languages.</p>\n\n<p>The initialization routine has borrowed heavily from many others through many years of LCD initialization - finding and overcoming the various quirks of the HD44780 and variants. It should work well for most similar LCDs.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/248949", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
We have a character LCD (www.cloverlcd.com/pdf/S6A0069.pdf) that we got to work in 8 bit mode. However, now we are trying to get it to work in 4 bit mode but it doesn't seem to be displaying anything. I think the function set instruction isn't been written. Can somebody please check if I am approaching this the right way? I'll post my 8 bit code (which is working) and my 4 bit code (which I'm trying to get to work) ``` //8 bit working COMPortC(0x3C); //function set Delay1KTCYx(10); COMPortC(0x0F); //Turn on display and configure cursor settings Delay1KTCYx(10); COMPortC(0x01); //clear display Delay1KTCYx(10); COMPortC(0x06); //increment mode and increment direction (entry mode set) Delay1KTCYx(10); COMPortC(0x02); //Return Home //4 bit COMPortC(0x20); //function set Delay1KTCYx(10); COMPortC(0x20); //function set Delay1KTCYx(10); COMPortC(0x80); //function set Delay1KTCYx(10); COMPortC(0x00); //Turn on display and configure cursor settings Delay1KTCYx(10); COMPortC(0xF0); //Turn on display and configure cursor settings Delay1KTCYx(10); ```
It looks okay up to a point but I wonder about a couple of things: 1/ Why do you output 0x20 twice to set the CGRAM address in the 4-bit section? Surely this is needed only once. 2/ The other two writes (0x00 and 0xf0), I don't understand from the docs. Can you fix up the comments to indicate what they're meant to be doing? 3/ Once you switch to 4-bit mode, do you need to redo the other instructions (the increment and return home)? It may be that switching modes resets all the data. 4/ One thing I did notice is that the busy flag indicates the system cannot yet receive another instruction. It may be that you're passing them in too fast. What happens when you increase the delays from 10 to 100. Just some things to try - let us know the outcomes. ===== RESPONSE: Thanks for the reply 1 and 2) I am writing these values based on page 29 of the datasheet (www.cloverlcd.com/pdf/S6A0069.pdf). 3) You are right, I do need to do the other instructions as well but for now, I am just trying to get the cursor to blink in 4 bit mode (so the first two instructions are sufficient) 4) I just tried the 100 delays, it didn't work. Sorry for the bad comments, I'll try to post better code next time. Thanks ===== EDIT: I see how it works now. In 4-bit mode, it only uses d7,d6,d5,d4 but every instruction is 2 writes (to make a 8-bit instruction). So it uses a trick to write the instruction 20 (in 8-bit mode) or 22 (2020 in 4-bit mode) both of which set the mode to 4-bit. Very clever, Samsung, I'm impressed. Try to go through the entire init sequence. It may be that the display doesn't fully start until initialization is complete. So you need to output (hex) 20,20,80,00,f0,**00,10,00,60,00,20**. The bold ones are the ones you need to add. Also, I need to ask two more questions (please reply as a comment to this answer rather than posting another answer) 1/ Does COMPortC() actually check the busy signal before outputting data? 2/ The delay of 10, what unit is it in, millisecs, microsecs, etc?
248,961
<p>I am just looking at the using statement, I have always known what it does but until now not tried using it, I have come up with the below code:</p> <pre><code> using (SqlCommand cmd = new SqlCommand(reportDataSource, new SqlConnection(Settings.Default.qlsdat_extensionsConnectionString))) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("@Year", SqlDbType.Char, 4).Value = year; cmd.Parameters.Add("@startDate", SqlDbType.DateTime).Value = start; cmd.Parameters.Add("@endDate", SqlDbType.DateTime).Value = end; cmd.Connection.Open(); DataSet dset = new DataSet(); new SqlDataAdapter(cmd).Fill(dset); this.gridDataSource.DataSource = dset.Tables[0]; } </code></pre> <p>This seems to work but is there any point in this since as far as I can tell I would still need to enclose this in a try catch block to catch unforseen errors e.g. sql server down. Am I missing something?</p> <p>As far as I can currently see it just stops me closing and disposing of cmd but there will be more lines of code due to the try catch still being needed.</p>
[ { "answer_id": 248967, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 2, "selected": false, "text": "<p>using isn't about catching exceptions. It's about properly disposing of resources that are outside the view of the garbage collector.</p>\n" }, { "answer_id": 248968, "author": "JamesSugrue", "author_id": 1075, "author_profile": "https://Stackoverflow.com/users/1075", "pm_score": 2, "selected": false, "text": "<p>Yes you would still need to catch exceptions. The benefit of the using block is you are adding scope to your code. You are saying, \"Within this block of code do some stuff and when it gets to the end, close and dispose of resources\"</p>\n\n<p>It's not completely necessary at all, but it does define your intentions to anyone else using your code, and it also helps not leaving connections etc open by mistake.</p>\n" }, { "answer_id": 248984, "author": "TheSoftwareJedi", "author_id": 18941, "author_profile": "https://Stackoverflow.com/users/18941", "pm_score": 5, "selected": true, "text": "<p>This code should be as follows to ensure timely closing of the connection. Closing just the command doesn't close the connection:</p>\n\n<pre><code>using (SqlConnection con = new SqlConnection(Settings.Default.qlsdat_extensionsConnectionString))\nusing (SqlCommand cmd = new SqlCommand(reportDataSource, con))\n {\n cmd.CommandType = CommandType.StoredProcedure;\n cmd.Parameters.Add(\"@Year\", SqlDbType.Char, 4).Value = year;\n cmd.Parameters.Add(\"@startDate\", SqlDbType.DateTime).Value = start;\n cmd.Parameters.Add(\"@endDate\", SqlDbType.DateTime).Value = end;\n cmd.Connection.Open();\n\n DataSet dset = new DataSet();\n new SqlDataAdapter(cmd).Fill(dset);\n this.gridDataSource.DataSource = dset.Tables[0];\n }\n</code></pre>\n\n<p>To answer your question, you can do the same in a finally block, but this scopes the code nicely and ensures that you remember to clean up.</p>\n" }, { "answer_id": 248996, "author": "Jason Jackson", "author_id": 13103, "author_profile": "https://Stackoverflow.com/users/13103", "pm_score": 6, "selected": false, "text": "<p>When doing IO work I code to <em>expect</em> an exception.</p>\n\n<pre><code>SqlConnection conn = null;\nSqlCommand cmd = null;\n\ntry\n{\n conn = new SqlConnection(Settings.Default.qlsdat_extensionsConnectionString)\n cmd = new SqlCommand(reportDataSource, conn);\n cmd.CommandType = CommandType.StoredProcedure;\n cmd.Parameters.Add(\"@Year\", SqlDbType.Char, 4).Value = year;\n cmd.Parameters.Add(\"@startDate\", SqlDbType.DateTime).Value = start;\n cmd.Parameters.Add(\"@endDate\", SqlDbType.DateTime).Value = end;\n\n conn.Open(); //opens connection\n\n DataSet dset = new DataSet();\n new SqlDataAdapter(cmd).Fill(dset);\n this.gridDataSource.DataSource = dset.Tables[0];\n}\ncatch(Exception ex)\n{\n Logger.Log(ex);\n throw;\n}\nfinally\n{\n if(conn != null)\n conn.Dispose();\n\n if(cmd != null)\n cmd.Dispose();\n}\n</code></pre>\n\n<p><strong>Edit:</strong> To be explicit, I avoid the <em>using</em> block here because I believe it to be important to log in situations like this. Experience has taught me that you never know what kind of weird exception might pop up. Logging in this situation might help you detect a deadlock, or find where a schema change is impacting a little used and little tested part of you code base, or any number of other problems.</p>\n\n<p><strong>Edit 2:</strong> One can argue that a using block could wrap a try/catch in this situation, and this is completely valid and functionally equivalent. This really boils down to preference. Do you want to avoid the extra nesting at the cost of handling your own disposal? Or do you incur the extra nesting to have auto-disposal. I feel that the former is cleaner so I do it that way. However, I don't rewrite the latter if I find it in the code base in which I am working.</p>\n\n<p><strong>Edit 3:</strong> I really, really wish MS had created a more explicit version of using() that made it more intuitive what was really happening and given more flexibility in this case. Consider the following, imaginary code:</p>\n\n<pre><code>SqlConnection conn = null;\nSqlCommand cmd = null;\n\nusing(conn = new SqlConnection(Settings.Default.qlsdat_extensionsConnectionString),\n cmd = new SqlCommand(reportDataSource, conn)\n{\n conn = new SqlConnection(Settings.Default.qlsdat_extensionsConnectionString);\n cmd = new SqlCommand(reportDataSource, conn);\n cmd.CommandType = CommandType.StoredProcedure;\n cmd.Parameters.Add(\"@Year\", SqlDbType.Char, 4).Value = year;\n cmd.Parameters.Add(\"@startDate\", SqlDbType.DateTime).Value = start;\n cmd.Parameters.Add(\"@endDate\", SqlDbType.DateTime).Value = end;\n cmd.Open();\n\n DataSet dset = new DataSet();\n new SqlDataAdapter(cmd).Fill(dset);\n this.gridDataSource.DataSource = dset.Tables[0];\n}\ncatch(Exception ex)\n{\n Logger.Log(ex);\n throw;\n}\n</code></pre>\n\n<p>A using statement just creates a try/finally with Dispose() calls in the finally. Why not give the developer a unified way of doing disposal and exception handling?</p>\n" }, { "answer_id": 248999, "author": "Chris Ballance", "author_id": 1551, "author_profile": "https://Stackoverflow.com/users/1551", "pm_score": 1, "selected": false, "text": "<p>The using statement is actually changed into a try/finally block by the compiler in which the parameter of the using block is disposed of so long as it implements the IDisposable interface. Aside from ensuring the specified objects are properly disposed when they fall out of scope, there is really no error capturing gained by using this construct.</p>\n\n<p>As is mentioned by <em>TheSoftwareJedi</em> above, you will want to make sure both the SqlConnection and SqlCommand objects are disposed of properly. Stacking both into a single using block is a bit messy, and might not do what you think it does.</p>\n\n<p>Also, be mindful of using the try/catch block as logic. It's a code smell that my nose has a particular dislike for, and often used by newbies or those of us in a big hurry to meet a deadline.</p>\n" }, { "answer_id": 249099, "author": "Charles Bretana", "author_id": 32632, "author_profile": "https://Stackoverflow.com/users/32632", "pm_score": 1, "selected": false, "text": "<p>FYI, in this specific example, because you're using an ADO.net connection and Command object, be aware that the using statement just executes the Command.Dispose, and the Connection.Dispose() which do not actually close the connection, but simply releases it back into the ADO.net Connection pool to be reused by the next connection.open ... which is good, and the absolutely correct thing to do, bc if you don't, the connection will remain unuseable until the garbage collector releases it back to the pool, which might not be until numerous other connection requests, which would otherwise be forced to create new connections even though there's an unused one waiting to be garbage collected. </p>\n" }, { "answer_id": 249128, "author": "Kevin Haines", "author_id": 10410, "author_profile": "https://Stackoverflow.com/users/10410", "pm_score": 3, "selected": false, "text": "<p>Elaborating on what Chris Ballance said, the C# specification (ECMA-334 version 4) section 15.13 states \"A using statement is translated into three parts: acquisition, usage, and disposal. Usage of the resource is implicitly enclosed in a try statement that includes a finally clause. This finally clause disposes of the resource. If a null resource is acquired, then no call to Dispose is made, and no exception is thrown.\"</p>\n\n<p>The description is close to 2 pages - worth a read.</p>\n\n<p>In my experience, SqlConnection/SqlCommand can generate errors in so many ways that you almost need to handle the exceptions thrown more than handle the expected behaviour. I'm not sure I'd want the using clause here, as I'd want to be able to handle the null resource case myself.</p>\n" }, { "answer_id": 249139, "author": "Timothy Khouri", "author_id": 11917, "author_profile": "https://Stackoverflow.com/users/11917", "pm_score": 2, "selected": false, "text": "<p>There are a lot of great answers here, but I don't think this has been said yet.</p>\n\n<p>No matter what... the \"Dispose\" method WILL be called on the object in the \"using\" block. If you put a return statement, or throw an error, the \"Dispose\" will be called.</p>\n\n<p>Example:</p>\n\n<p>I made a class called \"MyDisposable\", and it implements IDisposable and simply does a Console.Write. It <em>always</em> writes to the console even in all these scenarios:</p>\n\n<pre><code>using (MyDisposable blah = new MyDisposable())\n{\n int.Parse(\"!\"); // &lt;- calls \"Dispose\" after the error.\n\n return; // &lt;-- calls Dispose before returning.\n}\n</code></pre>\n" }, { "answer_id": 249176, "author": "jop", "author_id": 11830, "author_profile": "https://Stackoverflow.com/users/11830", "pm_score": 3, "selected": false, "text": "<p>If your code looks like this:</p>\n\n<pre><code>using (SqlCommand cmd = new SqlCommand(...))\n{\n try\n {\n /* call stored procedure */\n }\n catch (SqlException ex)\n {\n /* handles the exception. does not rethrow the exception */\n }\n}\n</code></pre>\n\n<p>Then I would refactor it to use try.. catch.. finally instead.</p>\n\n<pre><code>SqlCommand cmd = new SqlCommand(...)\ntry\n{\n /* call stored procedure */\n}\ncatch (SqlException ex)\n{\n /* handles the exception and does not ignore it */\n}\nfinally\n{\n if (cmd!=null) cmd.Dispose();\n}\n</code></pre>\n\n<p>In this scenario, I would be handling the exception so I have no choice but to add in that try..catch, I might as well put in the finally clause and save myself another nesting level. Note that I must be doing something in the catch block and not just ignoring the exception.</p>\n" }, { "answer_id": 249211, "author": "Andrew Kennan", "author_id": 22506, "author_profile": "https://Stackoverflow.com/users/22506", "pm_score": 0, "selected": false, "text": "<p>If the caller of your function is responsible for dealing with any exceptions the using statement is a nice way of ensuring resources are cleaned up no matter the outcome. </p>\n\n<p>It allows you to place exception handling code at layer/assembly boundaries and helps prevent other functions becoming too cluttered.</p>\n\n<p>Of course, it really depends on the types of exceptions thrown by your code. Sometimes you should use try-catch-finally rather than a using statement. My habit is to always start with a using statement for IDisposables (or have classes that contain IDisposables also implement the interface) and add try-catch-finally as needed.</p>\n" }, { "answer_id": 249242, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 4, "selected": false, "text": "<p>There may be no advantage to using a <code>using</code> statement in this case if you're going to have a <code>try</code>/<code>catch</code>/<code>finally</code> block anyway. As you know, the <code>using</code> statement is syntactic sugar for a <code>try</code>/<code>finally</code> that disposes of the <code>IDisposable</code> object. If you're going to have your own <code>try</code>/<code>finally</code> anyway, you can certainly do the <code>Dispose</code> yourself.</p>\n\n<p>This really mainly boils down to style - your team may be more comfortable with <code>using</code> statements or <code>using</code> statements may make the code look cleaner.</p>\n\n<p>But, if the boilerplate the <code>using</code> statement would be hiding is there anyway, go ahead and handle things yourself if that's your preference.</p>\n" }, { "answer_id": 2517618, "author": "Craig", "author_id": 301898, "author_profile": "https://Stackoverflow.com/users/301898", "pm_score": 0, "selected": false, "text": "<p>So, basically, \"using\" is the exact same as \"Try/catch/finally\" only much more flexible for error handling.</p>\n" }, { "answer_id": 3471218, "author": "John Saunders", "author_id": 76337, "author_profile": "https://Stackoverflow.com/users/76337", "pm_score": 0, "selected": false, "text": "<p>Minor correction to the example: <code>SqlDataAdapter</code> also needs to be instantiated in a <code>using</code> statement:</p>\n\n<pre><code>using (SqlConnection con = new SqlConnection(Settings.Default.qlsdat_extensionsConnectionString))\nusing (SqlCommand cmd = new SqlCommand(reportDataSource, con))\n{\n cmd.CommandType = CommandType.StoredProcedure;\n cmd.Parameters.Add(\"@Year\", SqlDbType.Char, 4).Value = year;\n cmd.Parameters.Add(\"@startDate\", SqlDbType.DateTime).Value = start;\n cmd.Parameters.Add(\"@endDate\", SqlDbType.DateTime).Value = end;\n con.Open();\n\n DataSet dset = new DataSet();\n using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))\n {\n adapter.Fill(dset);\n }\n this.gridDataSource.DataSource = dset.Tables[0];\n}\n</code></pre>\n" }, { "answer_id": 6432498, "author": "Rick", "author_id": 809328, "author_profile": "https://Stackoverflow.com/users/809328", "pm_score": 2, "selected": false, "text": "<p>one issue with \"using\" is that it doesn't handles exceptions.\nif the designers of \"using\" would add \"catch\" optionally to its syntax like below pseudocode, it would be much more useful:</p>\n\n<pre><code>using (...MyDisposableObj...)\n{\n\n ... use MyDisposableObj ...\n\ncatch (exception)\n\n ... handle exception ...\n\n}\n\nit could even have an optional \"finally\" clause to cleanup anything other than the \"MyDisposableObj\" allocated at the beginning of the \"using\" statement... like:\n\nusing (...MyDisposableObj...)\n{\n\n ... use MyDisposableObj ...\n ... open a file or db connection ...\n\ncatch (exception)\n\n ... handle exception ...\n\nfinally\n\n ... close the file or db connection ...\n\n}\n</code></pre>\n\n<p>still there'll be no need to write code to dispose of <code>MyDisposableObj</code> b/c it'd be handled by <code>using</code>...</p>\n\n<p>How do like that?</p>\n" }, { "answer_id": 6513092, "author": "SteveK", "author_id": 819987, "author_profile": "https://Stackoverflow.com/users/819987", "pm_score": 1, "selected": false, "text": "<p>I would make my decision on when to and when not to use the using statement dependant on the resource I am dealing with. In the case of a limited resource, such as an ODBC connection I would prefer to use T/C/F so I can log meaningful errors at the point they occurred. Letting database driver errors bubble back to the client and potentially be lost in the higher level exception wrapping is sub optimal. </p>\n\n<p>T/C/F gives you peace of mind that the resource is being handled the way you want it to. As some have already mentioned, the using statement does not provide exception handling it just ensures the resource is destructed. Exception handling is an underuitilised and underestimated language structure that is often the difference between the success and failure of a solution. </p>\n" }, { "answer_id": 31089141, "author": "T.J. Crowder", "author_id": 157247, "author_profile": "https://Stackoverflow.com/users/157247", "pm_score": 0, "selected": false, "text": "<p>First, your code example should be:</p>\n\n<pre><code>using (SqlConnection conn = new SqlConnection(Settings.Default.qlsdat_extensionsConnectionString))\nusing (SqlCommand cmd = new SqlCommand(reportDataSource, conn))\n{\n cmd.CommandType = CommandType.StoredProcedure;\n cmd.Parameters.Add(\"@Year\", SqlDbType.Char, 4).Value = year;\n cmd.Parameters.Add(\"@startDate\", SqlDbType.DateTime).Value = start;\n cmd.Parameters.Add(\"@endDate\", SqlDbType.DateTime).Value = end;\n cmd.Connection.Open();\n\n DataSet dset = new DataSet();\n new SqlDataAdapter(cmd).Fill(dset);\n this.gridDataSource.DataSource = dset.Tables[0];\n}\n</code></pre>\n\n<p>With the code in your question, an exception creating the command will result in the just-created connection not being disposed. With the above, the connection is properly disposed.</p>\n\n<p>If you need to handle exceptions in <em>construction</em> of the connection and command (as well as when using them), yes, you have to wrap the entire thing in a try/catch:</p>\n\n<pre><code>try\n{\n using (SqlConnection conn = new SqlConnection(Settings.Default.qlsdat_extensionsConnectionString))\n using (SqlCommand cmd = new SqlCommand(reportDataSource, conn))\n {\n cmd.CommandType = CommandType.StoredProcedure;\n cmd.Parameters.Add(\"@Year\", SqlDbType.Char, 4).Value = year;\n cmd.Parameters.Add(\"@startDate\", SqlDbType.DateTime).Value = start;\n cmd.Parameters.Add(\"@endDate\", SqlDbType.DateTime).Value = end;\n cmd.Connection.Open();\n\n DataSet dset = new DataSet();\n new SqlDataAdapter(cmd).Fill(dset);\n this.gridDataSource.DataSource = dset.Tables[0];\n }\n}\ncatch (RelevantException ex)\n{\n // ...handling...\n}\n</code></pre>\n\n<p>But you don't need to handle cleaning up <code>conn</code> or <code>cmd</code>; it's already been done for you.</p>\n\n<p>Contrast with the same thing without <code>using</code>:</p>\n\n<pre><code>SqlConnection conn = null;\nSqlCommand cmd = null;\ntry\n{\n conn = new SqlConnection(Settings.Default.qlsdat_extensionsConnectionString);\n cmd = new SqlCommand(reportDataSource, conn);\n cmd.CommandType = CommandType.StoredProcedure;\n cmd.Parameters.Add(\"@Year\", SqlDbType.Char, 4).Value = year;\n cmd.Parameters.Add(\"@startDate\", SqlDbType.DateTime).Value = start;\n cmd.Parameters.Add(\"@endDate\", SqlDbType.DateTime).Value = end;\n cmd.Connection.Open();\n\n DataSet dset = new DataSet();\n new SqlDataAdapter(cmd).Fill(dset);\n this.gridDataSource.DataSource = dset.Tables[0];\n}\ncatch (RelevantException ex)\n{\n // ...handling...\n}\nfinally\n{\n if (cmd != null)\n {\n try\n {\n cmd.Dispose();\n }\n catch { }\n cmd = null;\n }\n if (conn != null)\n {\n try\n {\n conn.Dispose();\n }\n catch { }\n conn = null;\n }\n}\n// And note that `cmd` and `conn` are still in scope here, even though they're useless\n</code></pre>\n\n<p>I know which I'd rather write. :-)</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/248961", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16989/" ]
I am just looking at the using statement, I have always known what it does but until now not tried using it, I have come up with the below code: ``` using (SqlCommand cmd = new SqlCommand(reportDataSource, new SqlConnection(Settings.Default.qlsdat_extensionsConnectionString))) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("@Year", SqlDbType.Char, 4).Value = year; cmd.Parameters.Add("@startDate", SqlDbType.DateTime).Value = start; cmd.Parameters.Add("@endDate", SqlDbType.DateTime).Value = end; cmd.Connection.Open(); DataSet dset = new DataSet(); new SqlDataAdapter(cmd).Fill(dset); this.gridDataSource.DataSource = dset.Tables[0]; } ``` This seems to work but is there any point in this since as far as I can tell I would still need to enclose this in a try catch block to catch unforseen errors e.g. sql server down. Am I missing something? As far as I can currently see it just stops me closing and disposing of cmd but there will be more lines of code due to the try catch still being needed.
This code should be as follows to ensure timely closing of the connection. Closing just the command doesn't close the connection: ``` using (SqlConnection con = new SqlConnection(Settings.Default.qlsdat_extensionsConnectionString)) using (SqlCommand cmd = new SqlCommand(reportDataSource, con)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("@Year", SqlDbType.Char, 4).Value = year; cmd.Parameters.Add("@startDate", SqlDbType.DateTime).Value = start; cmd.Parameters.Add("@endDate", SqlDbType.DateTime).Value = end; cmd.Connection.Open(); DataSet dset = new DataSet(); new SqlDataAdapter(cmd).Fill(dset); this.gridDataSource.DataSource = dset.Tables[0]; } ``` To answer your question, you can do the same in a finally block, but this scopes the code nicely and ensures that you remember to clean up.
248,973
<p>I'd like to stick a class down in my folder hierarchy. The scenario is too trivial to warrant it's own project or separate website. However, I hate to clutter my top-level App_Code with something that's used by a tiny corner of the site.</p> <p>Is there a way in web.config to include another file or folder in the compilation process?</p>
[ { "answer_id": 249005, "author": "tsilb", "author_id": 11112, "author_profile": "https://Stackoverflow.com/users/11112", "pm_score": 1, "selected": true, "text": "<pre><code>&lt;configuration&gt;\n &lt;system.web&gt;\n &lt;compilation&gt;\n &lt;assemblies&gt;\n &lt;add assembly=\"&lt;AssemblyName&gt;, Version=&lt;Version&gt;, Culture=&lt;Culture&gt;, PublicKeyToken=&lt;PublicKeyToken&gt;\"/&gt;\n &lt;/assemblies&gt;\n &lt;/compilation&gt;\n &lt;/system.web&gt;\n&lt;/configuration&gt;\n</code></pre>\n" }, { "answer_id": 249055, "author": "DuckMaestro", "author_id": 29152, "author_profile": "https://Stackoverflow.com/users/29152", "pm_score": 1, "selected": false, "text": "<p>It sounds like you are using the \"Web Site\" project type. You might consider switching to the \"Web Application\" project type which works more like a traditional project, allowing you to have a much more flexible folder structure (code can go anywhere you like, and App_Code isn't a special folder).</p>\n\n<p>This post has a brief discussion and links on the pros/cons of Web Site vs. Web Application projects:</p>\n\n<p><a href=\"http://forums.asp.net/p/1233004/2232697.aspx#2232697\" rel=\"nofollow noreferrer\">http://forums.asp.net/p/1233004/2232697.aspx#2232697</a></p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/248973", "https://Stackoverflow.com", "https://Stackoverflow.com/users/337/" ]
I'd like to stick a class down in my folder hierarchy. The scenario is too trivial to warrant it's own project or separate website. However, I hate to clutter my top-level App\_Code with something that's used by a tiny corner of the site. Is there a way in web.config to include another file or folder in the compilation process?
``` <configuration> <system.web> <compilation> <assemblies> <add assembly="<AssemblyName>, Version=<Version>, Culture=<Culture>, PublicKeyToken=<PublicKeyToken>"/> </assemblies> </compilation> </system.web> </configuration> ```
248,982
<p>I have an app which could benefit from the user being able to choose to set an image as the wallpaper (the background image on the "slide to unlock" screen). </p> <p>Is there a way for non-jailbreak third-party apps to do this? A search for "wallpaper" in the iPhone documentation returns nothing. </p>
[ { "answer_id": 249005, "author": "tsilb", "author_id": 11112, "author_profile": "https://Stackoverflow.com/users/11112", "pm_score": 1, "selected": true, "text": "<pre><code>&lt;configuration&gt;\n &lt;system.web&gt;\n &lt;compilation&gt;\n &lt;assemblies&gt;\n &lt;add assembly=\"&lt;AssemblyName&gt;, Version=&lt;Version&gt;, Culture=&lt;Culture&gt;, PublicKeyToken=&lt;PublicKeyToken&gt;\"/&gt;\n &lt;/assemblies&gt;\n &lt;/compilation&gt;\n &lt;/system.web&gt;\n&lt;/configuration&gt;\n</code></pre>\n" }, { "answer_id": 249055, "author": "DuckMaestro", "author_id": 29152, "author_profile": "https://Stackoverflow.com/users/29152", "pm_score": 1, "selected": false, "text": "<p>It sounds like you are using the \"Web Site\" project type. You might consider switching to the \"Web Application\" project type which works more like a traditional project, allowing you to have a much more flexible folder structure (code can go anywhere you like, and App_Code isn't a special folder).</p>\n\n<p>This post has a brief discussion and links on the pros/cons of Web Site vs. Web Application projects:</p>\n\n<p><a href=\"http://forums.asp.net/p/1233004/2232697.aspx#2232697\" rel=\"nofollow noreferrer\">http://forums.asp.net/p/1233004/2232697.aspx#2232697</a></p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/248982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27951/" ]
I have an app which could benefit from the user being able to choose to set an image as the wallpaper (the background image on the "slide to unlock" screen). Is there a way for non-jailbreak third-party apps to do this? A search for "wallpaper" in the iPhone documentation returns nothing.
``` <configuration> <system.web> <compilation> <assemblies> <add assembly="<AssemblyName>, Version=<Version>, Culture=<Culture>, PublicKeyToken=<PublicKeyToken>"/> </assemblies> </compilation> </system.web> </configuration> ```
248,983
<p>I have databound a listbox to a simple custom object collection. Next, I added a button to remove the selected item from the object collection. The problem is that when certain items are removed and the listbox is showing the vertical scroll bar, the scrollbar appears to reset to a new position, although what I really think is happening is that the control is repainting.</p> <p>The folowing code sample demonstrates the problem. Add this code to a form, making sure that the vertical scrollbar appears. Select an item in the middle of the collection so that the scrollbar is centered and press the remove button. When the control repaints, the items and scrollbar are in a different position. I would like for the listbox to behave as it would with non-databound items. Am I better off not using databinding, or is there a solution that allows me to keep the contol bound?</p> <p>Thanks.</p> <pre><code>public partial class Form1 : Form { private BindingList&lt;ItemData&gt; m_bList = new BindingList&lt;ItemData&gt;(); public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { for (int i = 0; i &lt; 50; i++) { m_bList.Add(new ItemData("Name " + i.ToString(), i)); } this.listBox1.DisplayMember = "Name"; this.listBox1.DataSource = m_bList; } private void btnRemove_Click(object sender, EventArgs e) { m_bList.Remove(listBox1.SelectedItem as ItemData); } } public class ItemData { public string Name { get; set; } public int Position { get; set; } public ItemData(string name, int position) { Name = name; Position = position; } } </code></pre>
[ { "answer_id": 249076, "author": "bioskope", "author_id": 29414, "author_profile": "https://Stackoverflow.com/users/29414", "pm_score": 0, "selected": false, "text": "<p>I can think of one way to dampen the error (note this might not be the most accurate solution) . I just added a few things to the button click event. I am not sure if they solve your requirements completely since you would be the best judge of that, but nonetheless here you go. </p>\n\n<pre><code> private void btnRemove_Click(object sender, EventArgs e)\n {\n int s = listBox1.SelectedIndex;\n m_bList.Remove(listBox1.SelectedItem as ItemData);\n listBox1.Refresh();\n listBox1.SelectedIndex = s;\n }\n</code></pre>\n" }, { "answer_id": 253109, "author": "Lee", "author_id": 13943, "author_profile": "https://Stackoverflow.com/users/13943", "pm_score": 2, "selected": false, "text": "<p>You need to preserve the TopIndex property of the listbox when removing the item. Preserving SelectedIndex does not stop the scrollbar from jumping. The code below does what I think you want.</p>\n\n<pre><code> private void btnRemove_Click(object sender,EventArgs e)\n {\n int topIndex = listBox1.TopIndex;\n\n m_bList.Remove(listBox1.SelectedItem as ItemData);\n\n if(listBox1.Items.Count&gt;topIndex)\n listBox1.TopIndex = topIndex;\n }\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/248983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have databound a listbox to a simple custom object collection. Next, I added a button to remove the selected item from the object collection. The problem is that when certain items are removed and the listbox is showing the vertical scroll bar, the scrollbar appears to reset to a new position, although what I really think is happening is that the control is repainting. The folowing code sample demonstrates the problem. Add this code to a form, making sure that the vertical scrollbar appears. Select an item in the middle of the collection so that the scrollbar is centered and press the remove button. When the control repaints, the items and scrollbar are in a different position. I would like for the listbox to behave as it would with non-databound items. Am I better off not using databinding, or is there a solution that allows me to keep the contol bound? Thanks. ``` public partial class Form1 : Form { private BindingList<ItemData> m_bList = new BindingList<ItemData>(); public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { for (int i = 0; i < 50; i++) { m_bList.Add(new ItemData("Name " + i.ToString(), i)); } this.listBox1.DisplayMember = "Name"; this.listBox1.DataSource = m_bList; } private void btnRemove_Click(object sender, EventArgs e) { m_bList.Remove(listBox1.SelectedItem as ItemData); } } public class ItemData { public string Name { get; set; } public int Position { get; set; } public ItemData(string name, int position) { Name = name; Position = position; } } ```
You need to preserve the TopIndex property of the listbox when removing the item. Preserving SelectedIndex does not stop the scrollbar from jumping. The code below does what I think you want. ``` private void btnRemove_Click(object sender,EventArgs e) { int topIndex = listBox1.TopIndex; m_bList.Remove(listBox1.SelectedItem as ItemData); if(listBox1.Items.Count>topIndex) listBox1.TopIndex = topIndex; } ```
248,985
<p>I'm writing an application that does async loading of images onto the screen. I have it set up to be NOT concurrent (that is, it spawns a thread and executes them one at a time), so I've only overridden the <code>[NSOperation main]</code> function in my NSOperation subclass. </p> <p>Anyway, so when I add all of these operations, I want to be able later to access the queued operations to change their priorities. Unfortunately, whenever I call <code>-[NSOperationQueue operations]</code>, all I get back is an empty array. The best part is that after putting in some console print statements, threads are still in the queue and executing (indicated by prints) despite the array being empty! </p> <p>What gives? I also took a look at theadcount just to make sure they're all not executing at once and that does not appear to be the case. </p> <p>Any ideas? Pulling my hair out on this one.</p> <p>EDIT: Also worth mentioning that the same code provides a full array when run in the simulator :(</p>
[ { "answer_id": 255661, "author": "Dave Verwer", "author_id": 4496, "author_profile": "https://Stackoverflow.com/users/4496", "pm_score": 0, "selected": false, "text": "<p>No idea why you are seeing this behaviour but as a pure workaround you could keep your own references to the individual operations as they are added into the queue.</p>\n" }, { "answer_id": 260656, "author": "Louis Gerbarg", "author_id": 30506, "author_profile": "https://Stackoverflow.com/users/30506", "pm_score": 1, "selected": false, "text": "<p>I just do not believe there is enough context here to say what is going on. Clearly something is wrong, but you do not say how you are limiting concurrency, how you are testing to see the objects are running, etc.</p>\n\n<p>As for the simulator vs the iPhone, NSOperations can act quite differently between the two, since all Intel based Macs are multiprocessor, and no iPhones are. Depending on how you are attempting to limit the concurrency you might be in a situation where not being able to execute on a second core prevents stuff from running, etc. But without more details it is impossible to know.</p>\n" }, { "answer_id": 265098, "author": "Stephen Darlington", "author_id": 2998, "author_profile": "https://Stackoverflow.com/users/2998", "pm_score": 0, "selected": false, "text": "<p>I've seen similar behaviour in low memory situations. How much memory are you using? Are you correctly clearing out caches and other temporary data when you get a <em>didReceiveMemoryWarning</em> message?</p>\n" }, { "answer_id": 608484, "author": "Dave Lee", "author_id": 73429, "author_profile": "https://Stackoverflow.com/users/73429", "pm_score": 3, "selected": false, "text": "<p>I stepped through <code>-operations</code>, and found that it's basically doing:</p>\n\n<pre><code>[self-&gt;data-&gt;lock lock];\nNSString* copy = [[self-&gt;data-&gt;operations copy] autorelease];\n[self-&gt;data-&gt;lock unlock];\nreturn copy;\n</code></pre>\n\n<p>except, after calling <code>-autorelease</code>, the subsequent instructions overwrite the register containing the only pointer to the new copy of the operations queue. The caller then just gets a <code>nil</code> return value. The \"<code>data</code>\" field is an instance of an internal class named <code>_NSOperationQueueData</code> which has fields:</p>\n\n<pre><code>NSRecursiveLock* lock;\nNSArray* operations;\n</code></pre>\n\n<p>My solution was to subclass and override <code>-operations</code>, following the same logic, but actually returning the array copy. I added some sanity checks to bail out if the internals of <code>NSOperationQueue</code> are not compatible with this fix. This reimplementation is only called if a call to <code>[super operations]</code> does in fact return <code>nil</code>.</p>\n\n<p>This could break in future OS releases if Apple were to change the internal structure, yet somehow avoid actually fixing this bug.</p>\n\n<pre><code>#if TARGET_OS_IPHONE\n\n#import &lt;objc/runtime.h&gt;\n\n@interface _DLOperationQueueData : NSObject {\n@public\n id lock; // &lt;NSLocking&gt;\n NSArray* operations;\n}\n@end\n@implementation _DLOperationQueueData; @end\n\n@interface _DLOperationQueueFix : NSObject {\n@public\n _DLOperationQueueData* data;\n}\n@end\n@implementation _DLOperationQueueFix; @end\n\n#endif\n\n\n@implementation DLOperationQueue\n\n#if TARGET_OS_IPHONE\n\n-(NSArray*) operations\n{\n NSArray* operations = [super operations];\n if (operations != nil) {\n return operations;\n }\n\n _DLOperationQueueFix* fix = (_DLOperationQueueFix*) self;\n _DLOperationQueueData* data = fix-&gt;data;\n\n if (strcmp(class_getName([data class]), \"_NSOperationQueueData\") != 0) {\n // this hack knows only the structure of _NSOperationQueueData\n // anything else, bail\n return operations;\n }\n if ([data-&gt;lock conformsToProtocol: @protocol(NSLocking)] == NO) {\n return operations; // not a lock, bail\n }\n\n [data-&gt;lock lock];\n operations = [[data-&gt;operations copy] autorelease];\n [data-&gt;lock unlock];\n return operations; // you forgot something, Apple.\n}\n\n#endif\n\n@end\n</code></pre>\n\n<p>The header file is:</p>\n\n<pre><code>@interface DLOperationQueue : NSOperationQueue {}\n#if TARGET_OS_IPHONE\n-(NSArray*) operations;\n#endif\n@end\n</code></pre>\n" }, { "answer_id": 860865, "author": "Tom Andersen", "author_id": 69948, "author_profile": "https://Stackoverflow.com/users/69948", "pm_score": 0, "selected": false, "text": "<p>I just ran into the same problem. Simpler code than I use on an OS X application, and yet [myoperationqueue operations] always returns nil. I was planning on using that to avoid duplicating the queries. This is on iPhone OS 2.2.1. Sure seems like a bug. Thanks for the code, I may use it, or just use my own mirror of the queue.</p>\n\n<p>This is not on the simulator, and I confirm that i add 20 or exact same copies of the job, which all line up nicely and do the job 19 times too many! </p>\n\n<p>It is really pretty simple code. I am not using hardly any memory - this is on launch of an app that has no ui yet. </p>\n\n<p>--Tom</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/248985", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28019/" ]
I'm writing an application that does async loading of images onto the screen. I have it set up to be NOT concurrent (that is, it spawns a thread and executes them one at a time), so I've only overridden the `[NSOperation main]` function in my NSOperation subclass. Anyway, so when I add all of these operations, I want to be able later to access the queued operations to change their priorities. Unfortunately, whenever I call `-[NSOperationQueue operations]`, all I get back is an empty array. The best part is that after putting in some console print statements, threads are still in the queue and executing (indicated by prints) despite the array being empty! What gives? I also took a look at theadcount just to make sure they're all not executing at once and that does not appear to be the case. Any ideas? Pulling my hair out on this one. EDIT: Also worth mentioning that the same code provides a full array when run in the simulator :(
I stepped through `-operations`, and found that it's basically doing: ``` [self->data->lock lock]; NSString* copy = [[self->data->operations copy] autorelease]; [self->data->lock unlock]; return copy; ``` except, after calling `-autorelease`, the subsequent instructions overwrite the register containing the only pointer to the new copy of the operations queue. The caller then just gets a `nil` return value. The "`data`" field is an instance of an internal class named `_NSOperationQueueData` which has fields: ``` NSRecursiveLock* lock; NSArray* operations; ``` My solution was to subclass and override `-operations`, following the same logic, but actually returning the array copy. I added some sanity checks to bail out if the internals of `NSOperationQueue` are not compatible with this fix. This reimplementation is only called if a call to `[super operations]` does in fact return `nil`. This could break in future OS releases if Apple were to change the internal structure, yet somehow avoid actually fixing this bug. ``` #if TARGET_OS_IPHONE #import <objc/runtime.h> @interface _DLOperationQueueData : NSObject { @public id lock; // <NSLocking> NSArray* operations; } @end @implementation _DLOperationQueueData; @end @interface _DLOperationQueueFix : NSObject { @public _DLOperationQueueData* data; } @end @implementation _DLOperationQueueFix; @end #endif @implementation DLOperationQueue #if TARGET_OS_IPHONE -(NSArray*) operations { NSArray* operations = [super operations]; if (operations != nil) { return operations; } _DLOperationQueueFix* fix = (_DLOperationQueueFix*) self; _DLOperationQueueData* data = fix->data; if (strcmp(class_getName([data class]), "_NSOperationQueueData") != 0) { // this hack knows only the structure of _NSOperationQueueData // anything else, bail return operations; } if ([data->lock conformsToProtocol: @protocol(NSLocking)] == NO) { return operations; // not a lock, bail } [data->lock lock]; operations = [[data->operations copy] autorelease]; [data->lock unlock]; return operations; // you forgot something, Apple. } #endif @end ``` The header file is: ``` @interface DLOperationQueue : NSOperationQueue {} #if TARGET_OS_IPHONE -(NSArray*) operations; #endif @end ```
248,989
<p>I have some code that raises <code>PropertyChanged</code> events and I would like to be able to unit test that the events are being raised correctly.</p> <p>The code that is raising the events is like</p> <pre><code>public class MyClass : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; protected void NotifyPropertyChanged(String info) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(info)); } } public string MyProperty { set { if (_myProperty != value) { _myProperty = value; NotifyPropertyChanged("MyProperty"); } } } } </code></pre> <p>I get a nice green test from the following code in my unit tests, that uses delegates:</p> <pre><code>[TestMethod] public void Test_ThatMyEventIsRaised() { string actual = null; MyClass myClass = new MyClass(); myClass.PropertyChanged += delegate(object sender, PropertyChangedEventArgs e) { actual = e.PropertyName; }; myClass.MyProperty = "testing"; Assert.IsNotNull(actual); Assert.AreEqual("MyProperty", actual); } </code></pre> <p>However, if I then try and chain the setting of properties together like so:</p> <pre><code>public string MyProperty { set { if (_myProperty != value) { _myProperty = value; NotifyPropertyChanged("MyProperty"); MyOtherProperty = "SomeValue"; } } } public string MyOtherProperty { set { if (_myOtherProperty != value) { _myOtherProperty = value; NotifyPropertyChanged("MyOtherProperty"); } } } </code></pre> <p>My test for the event fails - the event that it captures is the event for the MyOtherProperty.</p> <p>I'm pretty sure the event fires, my UI reacts like it does, but my delegate only captures the last event to fire.</p> <p>So I'm wondering:<br> 1. Is my method of testing events correct?<br> 2. Is my method of raising <em>chained</em> events correct? </p>
[ { "answer_id": 249042, "author": "Andrew Stapleton", "author_id": 28506, "author_profile": "https://Stackoverflow.com/users/28506", "pm_score": 9, "selected": true, "text": "<p>Everything you've done is correct, providing you want your test to ask \"What is the last event that was raised?\"</p>\n\n<p>Your code is firing these two events, in this order </p>\n\n<ul>\n<li>Property Changed (... \"My Property\" ...)</li>\n<li>Property Changed (... \"MyOtherProperty\" ...)</li>\n</ul>\n\n<p>Whether this is \"correct\" or not depends upon the purpose of these events.</p>\n\n<p>If you want to test the number of events that gets raised, and the order they get raised in, you can easily extend your existing test:</p>\n\n<pre><code>[TestMethod]\npublic void Test_ThatMyEventIsRaised()\n{\n List&lt;string&gt; receivedEvents = new List&lt;string&gt;();\n MyClass myClass = new MyClass();\n\n myClass.PropertyChanged += delegate(object sender, PropertyChangedEventArgs e)\n {\n receivedEvents.Add(e.PropertyName);\n };\n\n myClass.MyProperty = \"testing\";\n Assert.AreEqual(2, receivedEvents.Count);\n Assert.AreEqual(\"MyProperty\", receivedEvents[0]);\n Assert.AreEqual(\"MyOtherProperty\", receivedEvents[1]);\n}\n</code></pre>\n" }, { "answer_id": 2698702, "author": "Tim Lloyd", "author_id": 189516, "author_profile": "https://Stackoverflow.com/users/189516", "pm_score": 5, "selected": false, "text": "<p>If you're doing TDD then event testing can start to generate a <em>lot</em> of repetitive code. I wrote an event monitor that enables a much cleaner approach to unit test writing for these situations.</p>\n\n<pre><code>var publisher = new PropertyChangedEventPublisher();\n\nAction test = () =&gt;\n{\n publisher.X = 1;\n publisher.Y = 2;\n};\n\nvar expectedSequence = new[] { \"X\", \"Y\" };\n\nEventMonitor.Assert(test, publisher, expectedSequence);\n</code></pre>\n\n<p>Please see my answer to the following for more details.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/2567047/unit-testing-that-an-event-is-raised-in-c-using-reflection/2697721#2697721\">Unit testing that an event is raised in C#, using reflection</a></p>\n" }, { "answer_id": 4370949, "author": "Damir Arh", "author_id": 197913, "author_profile": "https://Stackoverflow.com/users/197913", "pm_score": 3, "selected": false, "text": "<p>Below is a slightly changed Andrew's code which instead of just logging the sequence of raised events rather counts how many times a specific event has been called. Although it is based on his code I find it more useful in my tests.</p>\n\n<pre><code>[TestMethod]\npublic void Test_ThatMyEventIsRaised()\n{\n Dictionary&lt;string, int&gt; receivedEvents = new Dictionary&lt;string, int&gt;();\n MyClass myClass = new MyClass();\n\n myClass.PropertyChanged += delegate(object sender, PropertyChangedEventArgs e)\n {\n if (receivedEvents.ContainsKey(e.PropertyName))\n receivedEvents[e.PropertyName]++;\n else\n receivedEvents.Add(e.PropertyName, 1);\n };\n\n myClass.MyProperty = \"testing\";\n Assert.IsTrue(receivedEvents.ContainsKey(\"MyProperty\"));\n Assert.AreEqual(1, receivedEvents[\"MyProperty\"]);\n Assert.IsTrue(receivedEvents.ContainsKey(\"MyOtherProperty\"));\n Assert.AreEqual(1, receivedEvents[\"MyOtherProperty\"]);\n}\n</code></pre>\n" }, { "answer_id": 18216715, "author": "Samuel", "author_id": 2416394, "author_profile": "https://Stackoverflow.com/users/2416394", "pm_score": 4, "selected": false, "text": "<p>This is very old and probably wont even be read but with some cool new .net features I have created an INPC Tracer class that allows that:</p>\n\n<pre><code>[Test]\npublic void Test_Notify_Property_Changed_Fired()\n{\n var p = new Project();\n\n var tracer = new INCPTracer();\n\n // One event\n tracer.With(p).CheckThat(() =&gt; p.Active = true).RaisedEvent(() =&gt; p.Active);\n\n // Two events in exact order\n tracer.With(p).CheckThat(() =&gt; p.Path = \"test\").RaisedEvent(() =&gt; p.Path).RaisedEvent(() =&gt; p.Active);\n}\n</code></pre>\n\n<p>See gist: <a href=\"https://gist.github.com/Seikilos/6224204\" rel=\"noreferrer\">https://gist.github.com/Seikilos/6224204</a></p>\n" }, { "answer_id": 33972226, "author": "nico", "author_id": 5615318, "author_profile": "https://Stackoverflow.com/users/5615318", "pm_score": 1, "selected": false, "text": "<p>Based on this article, i have created this simple assertion helper :</p>\n\n<pre><code>private void AssertPropertyChanged&lt;T&gt;(T instance, Action&lt;T&gt; actionPropertySetter, string expectedPropertyName) where T : INotifyPropertyChanged\n {\n string actual = null;\n instance.PropertyChanged += delegate (object sender, PropertyChangedEventArgs e)\n {\n actual = e.PropertyName;\n };\n actionPropertySetter.Invoke(instance);\n Assert.IsNotNull(actual);\n Assert.AreEqual(propertyName, actual);\n }\n</code></pre>\n\n<p>With this method helper, the test becomes really simple.</p>\n\n<pre><code>[TestMethod()]\npublic void Event_UserName_PropertyChangedWillBeFired()\n{\n var user = new User();\n AssertPropertyChanged(user, (x) =&gt; x.UserName = \"Bob\", \"UserName\");\n}\n</code></pre>\n" }, { "answer_id": 34786740, "author": "WhileTrueSleep", "author_id": 2294294, "author_profile": "https://Stackoverflow.com/users/2294294", "pm_score": 1, "selected": false, "text": "<p>Don't write a test for each member - this is much work</p>\n\n<p>(maybe this solution is not perfect for every situation - but it shows a possible way. You might need to adapt it for your use case)</p>\n\n<p>It's possible to use reflection in a library to test if your members are all responding to your property changed event correctly:</p>\n\n<ul>\n<li>PropertyChanged event is raised on setter access</li>\n<li>Event is raised correct (name of property equals argument of raised event)</li>\n</ul>\n\n<p>The following code can be used as a library and shows how to test the following generic class</p>\n\n<pre><code>using System.ComponentModel;\nusing System.Linq;\n\n/// &lt;summary&gt;\n/// Check if every property respons to INotifyPropertyChanged with the correct property name\n/// &lt;/summary&gt;\npublic static class NotificationTester\n {\n public static object GetPropertyValue(object src, string propName)\n {\n return src.GetType().GetProperty(propName).GetValue(src, null);\n }\n\n public static bool Verify&lt;T&gt;(T inputClass) where T : INotifyPropertyChanged\n {\n var properties = inputClass.GetType().GetProperties().Where(x =&gt; x.CanWrite);\n var index = 0;\n\n var matchedName = 0;\n inputClass.PropertyChanged += (o, e) =&gt;\n {\n if (properties.ElementAt(index).Name == e.PropertyName)\n {\n matchedName++;\n }\n\n index++;\n };\n\n foreach (var item in properties)\n { \n // use setter of property\n item.SetValue(inputClass, GetPropertyValue(inputClass, item.Name));\n }\n\n return matchedName == properties.Count();\n }\n }\n</code></pre>\n\n<p>The tests of your class can now be written as. (maybe you want to split the test into \"event is there\" and \"event raised with correct name\" - you can do this yourself)</p>\n\n<pre><code>[TestMethod]\npublic void EveryWriteablePropertyImplementsINotifyPropertyChangedCorrect()\n{\n var viewModel = new TestMyClassWithINotifyPropertyChangedInterface();\n Assert.AreEqual(true, NotificationTester.Verify(viewModel));\n}\n</code></pre>\n\n<p>Class</p>\n\n<pre><code>using System.ComponentModel;\n\npublic class TestMyClassWithINotifyPropertyChangedInterface : INotifyPropertyChanged\n{\n public event PropertyChangedEventHandler PropertyChanged;\n\n protected void NotifyPropertyChanged(string name)\n {\n if (PropertyChanged != null)\n {\n PropertyChanged(this, new PropertyChangedEventArgs(name));\n }\n }\n\n private int id;\n\n public int Id\n {\n get { return id; }\n set { id = value;\n NotifyPropertyChanged(\"Id\");\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 42299063, "author": "Mr.B", "author_id": 1002613, "author_profile": "https://Stackoverflow.com/users/1002613", "pm_score": 0, "selected": false, "text": "<p>I've made an extension here:</p>\n\n<pre><code>public static class NotifyPropertyChangedExtensions\n{\n private static bool _isFired = false;\n private static string _propertyName;\n\n public static void NotifyPropertyChangedVerificationSettingUp(this INotifyPropertyChanged notifyPropertyChanged,\n string propertyName)\n {\n _isFired = false;\n _propertyName = propertyName;\n notifyPropertyChanged.PropertyChanged += OnPropertyChanged;\n }\n\n private static void OnPropertyChanged(object sender, PropertyChangedEventArgs e)\n {\n if (e.PropertyName == _propertyName)\n {\n _isFired = true;\n }\n }\n\n public static bool IsNotifyPropertyChangedFired(this INotifyPropertyChanged notifyPropertyChanged)\n {\n _propertyName = null;\n notifyPropertyChanged.PropertyChanged -= OnPropertyChanged;\n return _isFired;\n }\n}\n</code></pre>\n\n<p>There is the usage:</p>\n\n<pre><code> [Fact]\n public void FilesRenameViewModel_Rename_Apply_Execute_Verify_NotifyPropertyChanged_If_Succeeded_Through_Extension_Test()\n {\n // Arrange\n _filesViewModel.FolderPath = ConstFolderFakeName;\n _filesViewModel.OldNameToReplace = \"Testing\";\n //After the command's execution OnPropertyChanged for _filesViewModel.AllFilesFiltered should be raised\n _filesViewModel.NotifyPropertyChangedVerificationSettingUp(nameof(_filesViewModel.AllFilesFiltered));\n //Act\n _filesViewModel.ApplyRenamingCommand.Execute(null);\n // Assert\n Assert.True(_filesViewModel.IsNotifyPropertyChangedFired());\n\n }\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/248989", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2660/" ]
I have some code that raises `PropertyChanged` events and I would like to be able to unit test that the events are being raised correctly. The code that is raising the events is like ``` public class MyClass : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; protected void NotifyPropertyChanged(String info) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(info)); } } public string MyProperty { set { if (_myProperty != value) { _myProperty = value; NotifyPropertyChanged("MyProperty"); } } } } ``` I get a nice green test from the following code in my unit tests, that uses delegates: ``` [TestMethod] public void Test_ThatMyEventIsRaised() { string actual = null; MyClass myClass = new MyClass(); myClass.PropertyChanged += delegate(object sender, PropertyChangedEventArgs e) { actual = e.PropertyName; }; myClass.MyProperty = "testing"; Assert.IsNotNull(actual); Assert.AreEqual("MyProperty", actual); } ``` However, if I then try and chain the setting of properties together like so: ``` public string MyProperty { set { if (_myProperty != value) { _myProperty = value; NotifyPropertyChanged("MyProperty"); MyOtherProperty = "SomeValue"; } } } public string MyOtherProperty { set { if (_myOtherProperty != value) { _myOtherProperty = value; NotifyPropertyChanged("MyOtherProperty"); } } } ``` My test for the event fails - the event that it captures is the event for the MyOtherProperty. I'm pretty sure the event fires, my UI reacts like it does, but my delegate only captures the last event to fire. So I'm wondering: 1. Is my method of testing events correct? 2. Is my method of raising *chained* events correct?
Everything you've done is correct, providing you want your test to ask "What is the last event that was raised?" Your code is firing these two events, in this order * Property Changed (... "My Property" ...) * Property Changed (... "MyOtherProperty" ...) Whether this is "correct" or not depends upon the purpose of these events. If you want to test the number of events that gets raised, and the order they get raised in, you can easily extend your existing test: ``` [TestMethod] public void Test_ThatMyEventIsRaised() { List<string> receivedEvents = new List<string>(); MyClass myClass = new MyClass(); myClass.PropertyChanged += delegate(object sender, PropertyChangedEventArgs e) { receivedEvents.Add(e.PropertyName); }; myClass.MyProperty = "testing"; Assert.AreEqual(2, receivedEvents.Count); Assert.AreEqual("MyProperty", receivedEvents[0]); Assert.AreEqual("MyOtherProperty", receivedEvents[1]); } ```
248,990
<p>I have a table like as follows:</p> <pre> SoftwareName Count Country Project 15 Canada Visio 12 Canada Project 10 USA Visio 5 USA </pre> <p>How do I query it to give me a summary like...</p> <pre> SoftwareName Canada USA Total Project 15 10 25 Visio 12 5 17 </pre> <p>How to do in T-SQL?</p>
[ { "answer_id": 249020, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 4, "selected": true, "text": "<pre><code>SELECT SoftwareName, \n SUM( CASE Country WHEN 'Canada' THEN [Count] ELSE 0 END ) AS Canada,\n SUM( CASE Country WHEN 'USA' THEN [Count] ELSE 0 END ) AS USA,\n SUM( [Count] ) AS Total\nFROM [Table] \nGROUP BY SoftwareName;\n</code></pre>\n" }, { "answer_id": 249028, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 1, "selected": false, "text": "<p>This is called table pivoting. In your simple case, there are just two columns; in general, there could be 200 countries or so, in which case, the pivoting becomes rather hard.</p>\n\n<p>There are many resources online describing how to do it: Google for 'pivot table sql'.</p>\n" }, { "answer_id": 249144, "author": "Charles Bretana", "author_id": 32632, "author_profile": "https://Stackoverflow.com/users/32632", "pm_score": 1, "selected": false, "text": "<p>in SQL 2005 or later there-SQL keyword \"Pivot\" that does this for you,\nCheck out the following link:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms177410.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms177410.aspx</a> </p>\n" }, { "answer_id": 249272, "author": "MarlonRibunal", "author_id": 10385, "author_profile": "https://Stackoverflow.com/users/10385", "pm_score": 2, "selected": false, "text": "<p>OK...Here's how to do it using PIVOT:</p>\n\n<pre><code>SELECT Softwarename, Canada, USA, Canada + USA As TOTAL from SoftwareDemo \nPIVOT \n (\n SUM([Count])\n FOR Country\n IN (Canada, USA)\n ) AS x\n\n\nSoftwarename Canada USA TOTAL\n-------------------------------------------------- ----------- ----------- -----------\nProject 15 10 25\nVisio 12 5 17\n\n(2 row(s) affected)\n</code></pre>\n" }, { "answer_id": 18809920, "author": "Ardalan Shahgholi", "author_id": 2063547, "author_profile": "https://Stackoverflow.com/users/2063547", "pm_score": 0, "selected": false, "text": "<p>i think you can use this Link :</p>\n\n<p><a href=\"https://stackoverflow.com/questions/17165381/sum-of-unique-records-better-performance-than-a-cursor/18657739#18657739\">Sum of unique records - better performance than a cursor</a></p>\n\n<p>and i think using PIVOT Function have a best performance rater SUM() function.!</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/248990", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31026/" ]
I have a table like as follows: ``` SoftwareName Count Country Project 15 Canada Visio 12 Canada Project 10 USA Visio 5 USA ``` How do I query it to give me a summary like... ``` SoftwareName Canada USA Total Project 15 10 25 Visio 12 5 17 ``` How to do in T-SQL?
``` SELECT SoftwareName, SUM( CASE Country WHEN 'Canada' THEN [Count] ELSE 0 END ) AS Canada, SUM( CASE Country WHEN 'USA' THEN [Count] ELSE 0 END ) AS USA, SUM( [Count] ) AS Total FROM [Table] GROUP BY SoftwareName; ```
248,998
<p>This is really weird... When I open the following simple HTML document in Internet Explorer 7.0.5730.11 (on Windows Server 2003 Web Edition SP2)</p> <pre><code>&lt;html&gt; &lt;body&gt; &lt;p&gt;+&lt;/p&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>it shows me a totally blank page. FWIW, this is just a trivial "repro" sample. In real HTML documents, I observed other, even more bizzarre effects caused by presense of the "plus" character that follows a tag.</p> <p><strong>NB:</strong> The problem appears to be extremely ittermittent. Most of the time it does work properly (i.e. displays the "plus" character), and I still can't find any way to reproduce this problem at will.</p> <p>Some additional details based on recent comments:</p> <ul> <li><p>There was no server involved. I was opening a file on disk (i.e. used <strong>file://</strong> protocol).</p></li> <li><p>The file did not contain anything except five lines shown above. No document type declarations, no character encodings, no nothings.</p></li> </ul> <p>Looks like a bug in IE. Did anybody encounter the same or similar problem?</p> <p><strong>NB:</strong> I appreciate all the responses received so far, but neither of respondednts encountered this problem. Something tells me that 99.(9)% of StackOverflow audience will not be able to reproduce it. :-)</p>
[ { "answer_id": 249040, "author": "mhawke", "author_id": 21945, "author_profile": "https://Stackoverflow.com/users/21945", "pm_score": 1, "selected": false, "text": "<p>Does it work if you use the numeric character reference notation?</p>\n\n<pre><code>&lt;html&gt;\n &lt;body&gt;\n &lt;p&gt;&amp;#43;&lt;/p&gt;\n &lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n" }, { "answer_id": 250632, "author": "Ross", "author_id": 2025, "author_profile": "https://Stackoverflow.com/users/2025", "pm_score": 0, "selected": false, "text": "<p>Does it work if you use a Doctype? IE does get a bit picky if you don't use a doctype (insert no-right-to-be-picky pun here).</p>\n\n<p>By intermittent do you mean using the same code it appears and doesn't? That sounds <em>really</em> strange.</p>\n\n<p><em>CLOSED - NOT REPRO</em>... er I mean I only get the +, no matter how many times I refresh. I suggest using the HTML entity reference - but this might be a problem with your system/browser if others can't reproduce either.</p>\n" }, { "answer_id": 253213, "author": "Onorio Catenacci", "author_id": 2820, "author_profile": "https://Stackoverflow.com/users/2820", "pm_score": 0, "selected": false, "text": "<p>For whatever it's worth, I just tested this on IE 7 (7.0.5730.13C0) and it consistently displays the \"+\" even with several refreshes (at least 10 or 12). You didn't mention an OS but in my case it's Windows XP SP2 (Help About displays Version 5.1 (Build 2600.xpsp_sp2_qfe.070227-2300: Service Pack 2). The OS may make a difference in this case. </p>\n" }, { "answer_id": 291617, "author": "eswald", "author_id": 21229, "author_profile": "https://Stackoverflow.com/users/21229", "pm_score": 0, "selected": false, "text": "<p>It's possible that this is due to the server, particularly if it's trying to parse the page as a script. To check:</p>\n\n<ul>\n<li>What HTTP headers do you see when the effect occurs?</li>\n<li>When you \"View Source\" at that point, what do you see?</li>\n<li>Does the effect ever occur when you load the page directly as a file?</li>\n<li>Does the effect ever occur in other browsers?</li>\n</ul>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/248998", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31415/" ]
This is really weird... When I open the following simple HTML document in Internet Explorer 7.0.5730.11 (on Windows Server 2003 Web Edition SP2) ``` <html> <body> <p>+</p> </body> </html> ``` it shows me a totally blank page. FWIW, this is just a trivial "repro" sample. In real HTML documents, I observed other, even more bizzarre effects caused by presense of the "plus" character that follows a tag. **NB:** The problem appears to be extremely ittermittent. Most of the time it does work properly (i.e. displays the "plus" character), and I still can't find any way to reproduce this problem at will. Some additional details based on recent comments: * There was no server involved. I was opening a file on disk (i.e. used **file://** protocol). * The file did not contain anything except five lines shown above. No document type declarations, no character encodings, no nothings. Looks like a bug in IE. Did anybody encounter the same or similar problem? **NB:** I appreciate all the responses received so far, but neither of respondednts encountered this problem. Something tells me that 99.(9)% of StackOverflow audience will not be able to reproduce it. :-)
Does it work if you use the numeric character reference notation? ``` <html> <body> <p>&#43;</p> </body> </html> ```
249,009
<p>I mean other than using it when required for functions, classes, if, while, switch, try-catch.</p> <p>I didn't know that it could be done like <a href="https://stackoverflow.com/questions/241088/what-do-curly-braces-by-themselves-mean-in-java">this until I saw this SO question</a>.</p> <p>In the above link, Eli mentioned that "They use it to fold up their code in logical sections that don't fall into a function, class, loop, etc. that would usually be folded up."</p> <p>What other uses are there besides those mentioned? </p> <p>Is it a good idea to use curly braces to limit the scope of your variables and expand the scope only if required (working on a "need-to-access" basis)? Or is it actually silly? </p> <p>How about using scopes just so that you can use the same variable names in different scopes but in the same bigger scope? Or is it a better practise to reuse the same variable (if you want to use the same variable name) and save on deallocating and allocating (I think some compilers can optimise on this?)? Or is it better to use different variable names altogether?</p>
[ { "answer_id": 249013, "author": "agartzke", "author_id": 18402, "author_profile": "https://Stackoverflow.com/users/18402", "pm_score": 5, "selected": false, "text": "<p>I would not use curly braces for that purpose for a couple reasons.</p>\n\n<ol>\n<li><p>If your particular function is big enough that you need to do various scoping tricks, perhaps break the function into smaller sub-functions.</p></li>\n<li><p>Introducing braces for scoping to reuse variable names is only going to lead to confusion and trouble in code.</p></li>\n</ol>\n\n<p>Just my 2 cents, but I have seen a lot of these types of things in other best practice materials.</p>\n" }, { "answer_id": 249014, "author": "Adam Pierce", "author_id": 5324, "author_profile": "https://Stackoverflow.com/users/5324", "pm_score": 7, "selected": true, "text": "<p>I do if I am using a resource which I want to free at a specific time eg:</p>\n\n<pre><code>void myfunction()\n{\n {\n // Open serial port\n SerialPort port(\"COM1\", 9600);\n port.doTransfer(data);\n } // Serial port gets closed here.\n\n for(int i = 0; i &lt; data.size(); i++)\n doProcessData(data[i]);\n etc...\n}\n</code></pre>\n" }, { "answer_id": 249016, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 3, "selected": false, "text": "<p>It can be a boon to code generators. Suppose you have an Embedded SQL (ESQL) compiler; it might want to convert an SQL statement into a block of code that needs local variables. By using a block, it can reuse fixed variable names over and over, rather than having to create all the variables with separate names. Granted, that's not too hard, but it is harder than necessary.</p>\n" }, { "answer_id": 249017, "author": "Jasper Bekkers", "author_id": 31486, "author_profile": "https://Stackoverflow.com/users/31486", "pm_score": 3, "selected": false, "text": "<p>I only use it when I need to release something by the means of RAII and even then only when it should be released as early as I possibly can (releasing a lock for example).</p>\n" }, { "answer_id": 249029, "author": "Greg Rogers", "author_id": 5963, "author_profile": "https://Stackoverflow.com/users/5963", "pm_score": 4, "selected": false, "text": "<p><strong>C++</strong>:</p>\n\n<p>Sometimes you need to introduce an extra brace level of scope to reuse variable names when it makes sense to do so:</p>\n\n<pre><code>switch (x) {\n case 0:\n int i = 0;\n foo(i);\n break;\n case 1:\n int i = 1;\n bar(i);\n break;\n}\n</code></pre>\n\n<p>The code above doesn't compile. You need to make it:</p>\n\n<pre><code>switch (x) {\n case 0:\n {\n int i = 0;\n foo(i);\n }\n break;\n case 1:\n {\n int i = 1;\n bar(i);\n }\n break;\n}\n</code></pre>\n" }, { "answer_id": 249051, "author": "Peter", "author_id": 5496, "author_profile": "https://Stackoverflow.com/users/5496", "pm_score": 0, "selected": false, "text": "<p>I agree with agartzke. If you feel that you need to segment larger logical code blocks for readability, you should consider refactoring to clean up busy and cluttered members.</p>\n" }, { "answer_id": 249059, "author": "Drew Hall", "author_id": 23934, "author_profile": "https://Stackoverflow.com/users/23934", "pm_score": 3, "selected": false, "text": "<p>As others have said, this is fairly common in C++ due to the all-powerful RAII (resource acquisition is initialization) idiom/pattern.</p>\n\n<p>For Java programmers (and maybe C#, I don't know) this will be a foreign concept because heap-based objects and GC kills RAII. IMHO, being able to put objects on the stack is the greatest single advantage of C++ over Java and makes well-written C++ code MUCH cleaner than well-written Java code.</p>\n" }, { "answer_id": 249136, "author": "Dave Sherohman", "author_id": 18914, "author_profile": "https://Stackoverflow.com/users/18914", "pm_score": 0, "selected": false, "text": "<p>It has its place, but I don't think that doing it so that $foo can be one variable <em>here</em> and a different variable <em>there</em>, within the same function or other (logical, rather than lexical) scope is a good idea. Even though the compiler may understand that perfectly, it seems too likely to make life difficult for humans trying to read the code.</p>\n" }, { "answer_id": 250161, "author": "Marcin", "author_id": 22724, "author_profile": "https://Stackoverflow.com/users/22724", "pm_score": 4, "selected": false, "text": "<p>The most common \"non-standard\" use of scoping that I use regularly is to utilize a scoped mutex.</p>\n\n<pre><code>void MyClass::Somefun()\n{\n //do some stuff\n {\n // example imlementation that has a mutex passed into a lock object:\n scopedMutex lockObject(m_mutex); \n\n // protected code here\n\n } // mutex is unlocked here\n // more code here\n}\n</code></pre>\n\n<p>This has many benefits, but the most important is that the lock will always be cleaned up, even if an exception is thrown in the protected code.</p>\n" }, { "answer_id": 250187, "author": "Graeme Perrow", "author_id": 1821, "author_profile": "https://Stackoverflow.com/users/1821", "pm_score": 4, "selected": false, "text": "<p>The most common use, as others have said, is to ensure that destructors run when you want them to. It's also handy for making platform-specific code a little clearer:</p>\n\n<pre><code>#if defined( UNIX )\n if( some unix-specific condition )\n#endif\n {\n // This code should always run on Windows but \n // only if the above condition holds on unix\n }\n</code></pre>\n\n<p>Code built for Windows doesn't see the if, only the braces. This is much clearer than:</p>\n\n<pre><code>#if defined( UNIX )\n if( some unix-specific condition ) {\n#endif\n // This code should always run on Windows but \n // only if the above condition holds on unix\n#if defined( UNIX )\n }\n#endif\n</code></pre>\n" }, { "answer_id": 255538, "author": "piyo", "author_id": 28524, "author_profile": "https://Stackoverflow.com/users/28524", "pm_score": 1, "selected": false, "text": "<p>Yes, I use this technique because of RAII. I also use this technique in plain <strong>C</strong> since it brings the variables closer together. Of course, I should be thinking about breaking up the functions even more.</p>\n\n<p>One thing I do that is probably stylistically controversial is put the opening curly brace on the line of the declaration or put a comment right on it. <a href=\"http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Vertical_Whitespace\" rel=\"nofollow noreferrer\">I want to decrease the amount of wasted vertical space. This is based on the Google C++ Style Guide recommendation.</a>.</p>\n\n<pre><code>/// c++ code\n/// references to boost::test\nBOOST_TEST_CASE( curly_brace )\n{\n // init\n MyClass instance_to_test( \"initial\", TestCase::STUFF ); {\n instance_to_test.permutate(42u);\n instance_to_test.rotate_left_face();\n instance_to_test.top_gun();\n }\n { // test check\n const uint8_t kEXP_FAP_BOOST = 240u;\n BOOST_CHECK_EQUAL( instance_to_test.get_fap_boost(), kEXP_FAP_BOOST);\n }\n}\n</code></pre>\n" }, { "answer_id": 256060, "author": "Lawrence Dol", "author_id": 8946, "author_profile": "https://Stackoverflow.com/users/8946", "pm_score": 2, "selected": false, "text": "<p>Programming in Java I have quite often wanted to limit scope within a method, but it never occurred to me to use a label. Since I uppercase my labels when using them as the target of a break, using a mixed case labeled block like you have suggested is just what I have wanted on these occasions.</p>\n\n<p>Often the code blocks are too short to break out into a small method, and often the code in a framework method (like startup(), or shutdown()) and it's actually better to keep the code together in one method.</p>\n\n<p>Personally I hate the plain floating/dangling braces (though that's because we are a strict banner style indent shop), and I hate the comment marker:</p>\n\n<pre><code>// yuk!\nsome code\n{\nscoped code\n}\nmore code\n\n// also yuk!\nsome code\n/* do xyz */ {\n scoped code\n }\nsome more code\n\n// this I like\nsome code\nDoXyz: {\n scoped code\n }\nsome more code\n</code></pre>\n\n<p>We considered using \"if(true) {\" because the Java spec specifically says these will be optimized away in compilation (as will the entire content of an if(false) - it's a debugging feature), but I hated that in the few places I tried it.</p>\n\n<p>So I think your idea is a good one, not at all silly. I always thought I was the only one who wanted to do this.</p>\n" }, { "answer_id": 3638092, "author": "blizpasta", "author_id": 20646, "author_profile": "https://Stackoverflow.com/users/20646", "pm_score": 0, "selected": false, "text": "<p>The company I'm working at has a static analysis policy to keep local variable declarations near the beginning of a function. Many times, the usage is many lines after the first line of a function so I cannot see the declaration and the first reference at the same time on the screen. What I do to 'circumvent' the policy is to keep the declaration near the reference, but provide additional scope by using curly braces. It increases indentation though, and some may argue that it makes the code uglier.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249009", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20646/" ]
I mean other than using it when required for functions, classes, if, while, switch, try-catch. I didn't know that it could be done like [this until I saw this SO question](https://stackoverflow.com/questions/241088/what-do-curly-braces-by-themselves-mean-in-java). In the above link, Eli mentioned that "They use it to fold up their code in logical sections that don't fall into a function, class, loop, etc. that would usually be folded up." What other uses are there besides those mentioned? Is it a good idea to use curly braces to limit the scope of your variables and expand the scope only if required (working on a "need-to-access" basis)? Or is it actually silly? How about using scopes just so that you can use the same variable names in different scopes but in the same bigger scope? Or is it a better practise to reuse the same variable (if you want to use the same variable name) and save on deallocating and allocating (I think some compilers can optimise on this?)? Or is it better to use different variable names altogether?
I do if I am using a resource which I want to free at a specific time eg: ``` void myfunction() { { // Open serial port SerialPort port("COM1", 9600); port.doTransfer(data); } // Serial port gets closed here. for(int i = 0; i < data.size(); i++) doProcessData(data[i]); etc... } ```
249,010
<p>cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;</p> <p>in this method</p> <pre><code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath; </code></pre> <p>but I can only see it when I select that cell otherwise it's not visible.and it work perfectly when background is white. I am sure that I need to set a property, but I don't know which property I need to change to make this thing work.</p> <p>thanks in advance.</p> <p>cheers.</p>
[ { "answer_id": 249145, "author": "Ben Gottlieb", "author_id": 6694, "author_profile": "https://Stackoverflow.com/users/6694", "pm_score": 4, "selected": true, "text": "<p>It would appear that the disclosure indicator is a gray, high-alpha image, so overlaying that over a black background makes it invisible. If you want to do this, you'll need to add your own UIImageView to the cell's contentView.</p>\n" }, { "answer_id": 1249948, "author": "Adam Prall", "author_id": 1822483, "author_profile": "https://Stackoverflow.com/users/1822483", "pm_score": 3, "selected": false, "text": "<p>I ran into this same issue, and just create a UIImageView out of a UIView’s imageWithName @\"AccDisclosure.png\" using the following hastily mocked-up graphic which you're free to copy: <a href=\"http://thinkingman.com/db/downloads/AccDisclosure.png\" rel=\"noreferrer\">http://thinkingman.com/db/downloads/AccDisclosure.png</a> (if you just click that link, you'll probably see nothing, as it's a white image with a transparent background, but if you save it and view against a dark background, you'll see the alpha).</p>\n" }, { "answer_id": 2598410, "author": "John Dell'Aera", "author_id": 311711, "author_profile": "https://Stackoverflow.com/users/311711", "pm_score": 1, "selected": false, "text": "<p>The following code allows me to set the background color of the arrow tip in a table row:</p>\n\n<pre><code>@property (nonatomic,retain) UILabel *backgroundLabel;\n\nUILabel *label = [[UILabel alloc] initWithFrame:CGRectZero];\nlabel.backgroundColor = [UIColor orangeColor]; \nself.backgroundLabel = label;\n[self.contentView addSubview:label];\n[label release];\n\nCGRect labelRect = CGRectOffset(contentRect,0, 0);\nlabelRect.size.height = contentRect.size.height - 1; // show white line\nlabelRect.size.width = contentRect.size.width + 50; // cover arrow tip background\nbackgroundLabel.frame = labelRect; \nbackgroundLabel.highlightedTextColor = [UIColor whiteColor];\n</code></pre>\n" }, { "answer_id": 2898177, "author": "Henrik Erlandsson", "author_id": 343825, "author_profile": "https://Stackoverflow.com/users/343825", "pm_score": 0, "selected": false, "text": "<p>I made a solution where I added an ImageView with addSubView in the normal fashion, with an image that was not black (in my case, a grey filled circle) at the position where the accessory appears. </p>\n\n<p>That allows the arrow to be seen and still have a dark/black table cell background color.</p>\n\n<p>Maybe not the most kosher solution, but it makes the arrow visible, and I get notified of accessory clicks without subclassing or writing lots of code.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249010", "https://Stackoverflow.com", "https://Stackoverflow.com/users/451867/" ]
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; in this method ``` - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath; ``` but I can only see it when I select that cell otherwise it's not visible.and it work perfectly when background is white. I am sure that I need to set a property, but I don't know which property I need to change to make this thing work. thanks in advance. cheers.
It would appear that the disclosure indicator is a gray, high-alpha image, so overlaying that over a black background makes it invisible. If you want to do this, you'll need to add your own UIImageView to the cell's contentView.
249,022
<p>I have an method which save files to the internet, it works but just slow. Then I'd like to make the user interface more smooth, so I create an NSThread to handle the slow task. </p> <p>I am seeing a list of errors like:</p> <pre><code>_NSAutoreleaseNoPool(): Object 0x18a140 of class NSCFString autoreleased with no pool in place - just leaking </code></pre> <p>Without NSThread, I call the method like:</p> <pre><code>[self save:self.savedImg]; </code></pre> <p>And I used the following to use NSThread to call the method:</p> <pre><code>NSThread* thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(save:) object:self.savedImg]; [thread1 start]; </code></pre> <p>Thanks. </p>
[ { "answer_id": 249061, "author": "Kendall Helmstetter Gelner", "author_id": 6330, "author_profile": "https://Stackoverflow.com/users/6330", "pm_score": 0, "selected": false, "text": "<p>Within the thread, you need to create a new autorelease pool before you do anything else, otherwise the network operations will have issues as you saw.</p>\n" }, { "answer_id": 249083, "author": "Louis Gerbarg", "author_id": 30506, "author_profile": "https://Stackoverflow.com/users/30506", "pm_score": 3, "selected": false, "text": "<p>You need to mainly create an autorelease pool for the thread. Try changing your save method to be like this:</p>\n\n<pre><code>- (void) save:(id)arg {\n NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];\n\n //Existing code\n\n [pool drain];\n}\n</code></pre>\n\n<p>You will not you that the above does not call release on the NSAutoreleasePool. This is a special case. For NSAutoreleasePool drain is equivalent to release when running without GC, and converts to a hint to collector that it might be good point to run a collection.</p>\n" }, { "answer_id": 249224, "author": "Chris Lundie", "author_id": 20685, "author_profile": "https://Stackoverflow.com/users/20685", "pm_score": 2, "selected": false, "text": "<p>You may need to create a run loop. I will add to Louis's solution:</p>\n\n<pre><code>BOOL done = NO;\n\nNSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];\n[NSRunLoop currentRunLoop];\n\n// Start the HTTP connection here. When it's completed,\n// you could stop the run loop and then the thread will end.\n\ndo {\n SInt32 result = CFRunLoopRunInMode(kCFRunLoopDefaultMode, 1, YES);\n if ((result == kCFRunLoopRunStopped) || (result == kCFRunLoopRunFinished)) {\n done = YES;\n }\n} while (!done);\n\n[pool release];\n</code></pre>\n" }, { "answer_id": 249250, "author": "keremk", "author_id": 29475, "author_profile": "https://Stackoverflow.com/users/29475", "pm_score": 5, "selected": true, "text": "<p>Well first of all, you are both creating a new thread for your saving code and then using NSUrlConnection asynchronously. NSUrlConnection in its own implementation would also spin-off another thread and call you back on your newly created thread, which mostly is not something you are trying to do. I assume you are just trying to make sure that your UI does not block while you are saving... </p>\n\n<p>NSUrlConnection also has synchronous version which will block on your thread and it would be better to use that if you want to launch your own thread for doing things. The signature is </p>\n\n<pre><code>+ sendSynchronousRequest:returningResponse:error:\n</code></pre>\n\n<p>Then when you get the response back, you can call back into your UI thread. Something like below should work:</p>\n\n<pre><code>- (void) beginSaving {\n // This is your UI thread. Call this API from your UI.\n // Below spins of another thread for the selector \"save\"\n [NSThread detachNewThreadSelector:@selector(save:) toTarget:self withObject:nil]; \n\n}\n\n- (void) save {\n NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; \n\n // ... calculate your post request...\n // Initialize your NSUrlResponse and NSError\n\n NSUrlConnection *conn = [NSUrlConnection sendSyncronousRequest:postRequest:&amp;response error:&amp;error];\n // Above statement blocks until you get the response, but you are in another thread so you \n // are not blocking UI. \n\n // I am assuming you have a delegate with selector saveCommitted to be called back on the\n // UI thread.\n if ( [delegate_ respondsToSelector:@selector(saveCommitted)] ) {\n // Make sure you are calling back your UI on the UI thread as below:\n [delegate_ performSelectorOnMainThread:@selector(saveCommitted) withObject:nil waitUntilDone:NO];\n }\n\n [pool release];\n}\n</code></pre>\n" }, { "answer_id": 252630, "author": "Peter Hosey", "author_id": 30461, "author_profile": "https://Stackoverflow.com/users/30461", "pm_score": 0, "selected": false, "text": "<p>I don't see any reason for you to use threads for this. Simply doing it asynchronously on the run loop should work without blocking the UI.</p>\n\n<p>Trust in the run loop. It's <em>always</em> easier than threading, and is designed to provide the same result (a never-blocked UI).</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249022", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32096/" ]
I have an method which save files to the internet, it works but just slow. Then I'd like to make the user interface more smooth, so I create an NSThread to handle the slow task. I am seeing a list of errors like: ``` _NSAutoreleaseNoPool(): Object 0x18a140 of class NSCFString autoreleased with no pool in place - just leaking ``` Without NSThread, I call the method like: ``` [self save:self.savedImg]; ``` And I used the following to use NSThread to call the method: ``` NSThread* thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(save:) object:self.savedImg]; [thread1 start]; ``` Thanks.
Well first of all, you are both creating a new thread for your saving code and then using NSUrlConnection asynchronously. NSUrlConnection in its own implementation would also spin-off another thread and call you back on your newly created thread, which mostly is not something you are trying to do. I assume you are just trying to make sure that your UI does not block while you are saving... NSUrlConnection also has synchronous version which will block on your thread and it would be better to use that if you want to launch your own thread for doing things. The signature is ``` + sendSynchronousRequest:returningResponse:error: ``` Then when you get the response back, you can call back into your UI thread. Something like below should work: ``` - (void) beginSaving { // This is your UI thread. Call this API from your UI. // Below spins of another thread for the selector "save" [NSThread detachNewThreadSelector:@selector(save:) toTarget:self withObject:nil]; } - (void) save { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; // ... calculate your post request... // Initialize your NSUrlResponse and NSError NSUrlConnection *conn = [NSUrlConnection sendSyncronousRequest:postRequest:&response error:&error]; // Above statement blocks until you get the response, but you are in another thread so you // are not blocking UI. // I am assuming you have a delegate with selector saveCommitted to be called back on the // UI thread. if ( [delegate_ respondsToSelector:@selector(saveCommitted)] ) { // Make sure you are calling back your UI on the UI thread as below: [delegate_ performSelectorOnMainThread:@selector(saveCommitted) withObject:nil waitUntilDone:NO]; } [pool release]; } ```
249,027
<p>I would like to implement a command line interface for a Java application. This wouldn't be too difficult to do, except I would like the command line program to affect the state of another Java GUI program. So for example, I could type:</p> <pre><code>java CliMain arg1 arg2 </code></pre> <p>And another running GUI instance would perform an appropriate action.</p> <p>What is the easiest way of implementing something like this?</p>
[ { "answer_id": 249036, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 3, "selected": true, "text": "<p>You could have the GUI application listen on a TCP port (on the <code>localhost</code> interface) and the CLI application would connect to it.</p>\n\n<p>One way to do this would be to use REST over HTTP.</p>\n" }, { "answer_id": 249041, "author": "Will Hartung", "author_id": 13663, "author_profile": "https://Stackoverflow.com/users/13663", "pm_score": 0, "selected": false, "text": "<p>Another way is through JMX. It gives you a lot of stuff \"for free\" (in the simple case you just implement a bean and register it -- very simple), and is particularly well suited to this task.</p>\n" }, { "answer_id": 249082, "author": "anjanb", "author_id": 11142, "author_profile": "https://Stackoverflow.com/users/11142", "pm_score": 0, "selected": false, "text": "<p>you can have the GUI application(like an editor) listen on</p>\n\n<p>1) clipboard event of a certain type <br>\n if the event is of a type that you are interested in, then get the clipboard contents.<br><br>\n2) server socket on a certain port<br>\n listen on a server socket. when the CLI program starts, it connects to the server socket at a known port, sends info and quits.<br><br>\n3) queue <br>\n you can enque from the CLI program and deque from the GUI program.</p>\n\n<p>if you want to investigate further, many professional editors like emacs use the same mechanism. <a href=\"http://www.emacswiki.org/emacs/EmacsClient\" rel=\"nofollow noreferrer\">http://www.emacswiki.org/emacs/EmacsClient</a></p>\n" }, { "answer_id": 249365, "author": "Daniel Hiller", "author_id": 16193, "author_profile": "https://Stackoverflow.com/users/16193", "pm_score": 0, "selected": false, "text": "<p>Your application could be controlled via <a href=\"http://java.sun.com/docs/books/tutorial/rmi/index.html\" rel=\"nofollow noreferrer\">RMI</a>. The application would implement a control interface, register its service on localhost and the command line application would get an rmi proxy and call the desired control methods...</p>\n\n<p>Seems hard at first, but when you've tried out you'll quickly see how easy that is. And it also supports encryption via <a href=\"http://java.sun.com/j2se/1.5.0/docs/guide/rmi/socketfactory/SSLInfo.html\" rel=\"nofollow noreferrer\">SSL</a>. So you could secure your data exchange if there was security relevant data online.</p>\n" }, { "answer_id": 249389, "author": "Claudiu", "author_id": 15055, "author_profile": "https://Stackoverflow.com/users/15055", "pm_score": 0, "selected": false, "text": "<p>The easiest way would be for the GUI to listen for commands on a TCP port. The command line would send commands, and the GUI would interpret them. </p>\n\n<p>Maybe you could do it with named pipes as well, but I'm not sure how you'd go about implementing that in Java.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23845/" ]
I would like to implement a command line interface for a Java application. This wouldn't be too difficult to do, except I would like the command line program to affect the state of another Java GUI program. So for example, I could type: ``` java CliMain arg1 arg2 ``` And another running GUI instance would perform an appropriate action. What is the easiest way of implementing something like this?
You could have the GUI application listen on a TCP port (on the `localhost` interface) and the CLI application would connect to it. One way to do this would be to use REST over HTTP.
249,066
<p>I just want to know how to validate (or clean) user input in ASP.NET MVC so that an HttpRequestValidationException will not be thrown regardless of the values submitted. For example, with a text input, if the user inputs <code>&lt;BR/&gt;</code>, it will cause an exception and the Yellow Screen of Death will be shown. I don't want that. I want to catch the exception and to make visible an user friendly error in the current view, preferably with the controls loaded with the same values submitted. </p> <p>I have found this <a href="http://www.romsteady.net/blog/2007/06/how-to-catch-httprequestvalidationexcep.html" rel="noreferrer">http://www.romsteady.net/blog/2007/06/how-to-catch-httprequestvalidationexcep.html</a>, but it is useless for my purpose. Also, I have found this <a href="http://msdn.microsoft.com/en-us/library/aa973813.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/aa973813.aspx</a> and tried to put inside a model binder but I couldn't make to work.</p>
[ { "answer_id": 253398, "author": "Hrvoje Hudo", "author_id": 1407, "author_profile": "https://Stackoverflow.com/users/1407", "pm_score": 0, "selected": false, "text": "<p>Put put ValidateRequest=\"false\" to your aspx view declaration, but sanitize users input text inside your code, to avoid some xss attacks. </p>\n" }, { "answer_id": 256194, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 1, "selected": false, "text": "<p>Instead of catching the error in the global.asax Application_Error, you could catch it by adding an error handler for the controller that explicitly catches this error and redirects to the view with an error message and appropriate view data.</p>\n\n<p>I found this, somewhat old, <a href=\"http://weblogs.asp.net/fredriknormen/archive/2007/11/22/asp-net-mvc-framework-handling-exception-by-using-an-attribute.aspx\" rel=\"nofollow noreferrer\">post</a> on how to do this with attributes.</p>\n" }, { "answer_id": 552107, "author": "user66787", "author_id": 66787, "author_profile": "https://Stackoverflow.com/users/66787", "pm_score": 6, "selected": true, "text": "<p>With the latest version of ASP.NET MVC (the RC, at the time of writing this) you can just put an attribute on either your controller class or your action method, e.g.:</p>\n\n<pre><code>[ValidateInput(false)]\npublic ActionResult create()\n{\n // ...method body\n}\n</code></pre>\n\n<p>The ValidateInputAttribute is in System.Web.Mvc.</p>\n\n<p>But as others have said, you do then have to perform your own manual input validation or cleaning.</p>\n\n<p>Using MVC 3, you must also ensure this is in your Web.config: <code>&lt;system.web&gt;&lt;httpRuntime requestValidationMode=\"2.0\" /&gt;&lt;/system.web&gt;</code></p>\n" }, { "answer_id": 1023549, "author": "dariol", "author_id": 3644960, "author_profile": "https://Stackoverflow.com/users/3644960", "pm_score": 1, "selected": false, "text": "<p>ValidateInputAttribute is the proper method for disabling request validation. Declarative method within view (aspx) doesn't work because controller is responsible for receiving request (not view/aspx).</p>\n" }, { "answer_id": 2380618, "author": "JoshNaro", "author_id": 7423, "author_profile": "https://Stackoverflow.com/users/7423", "pm_score": 2, "selected": false, "text": "<p>For a very detailed example of how to catch this (and other) exceptions with a filter see: <a href=\"http://code.google.com/p/geochat/source/browse/Source/Web/GeoChat.MvcExtensions/ExceptionHandlerAttribute.cs\" rel=\"nofollow noreferrer\">http://code.google.com/p/geochat/source/browse/Source/Web/GeoChat.MvcExtensions/ExceptionHandlerAttribute.cs</a></p>\n\n<p>This will allow you to keep the validation on, but prevent the user from seeing the \"yellow screen of death\".</p>\n\n<p>This is a simplified (perhaps oversimplified) version:</p>\n\n<pre><code>[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true), AspNetHostingPermission(SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]\npublic class ExceptionHandlerAttribute : FilterAttribute, IExceptionFilter {\n\nprivate HandleErrorAttribute attribute = new HandleErrorAttribute();\n\npublic ExceptionHandlerAttribute() {\n this.ExceptionType = typeof(Exception);\n this.Order = 1;\n}\n\npublic string View {\n get {\n return attribute.View;\n }\n set {\n attribute.View = value;\n }\n}\n\npublic Type ExceptionType {\n get {\n return attribute.ExceptionType;\n }\n set {\n attribute.ExceptionType = value;\n }\n}\n\npublic void OnException(ExceptionContext filterContext) {\n if (this.ExceptionType.IsInstanceOfType(filterContext.Exception)) {\n string controller = (string)filterContext.RouteData.Values[\"controller\"];\n string action = (string)filterContext.RouteData.Values[\"action\"];\n if (controller == null)\n controller = String.Empty;\n\n if (action == null)\n action = String.Empty;\n\n HandleErrorInfo model = new HandleErrorInfo(filterContext.Exception, controller, action);\n ViewResult result = new ViewResult();\n result.ViewName = this.View;\n result.MasterName = String.Empty;\n result.ViewData = new ViewDataDictionary&lt;HandleErrorInfo&gt;(model);\n\n result.TempData = filterContext.Controller.TempData;\n filterContext.Result = result;\n\n filterContext.ExceptionHandled = true;\n filterContext.HttpContext.Response.Clear();\n filterContext.HttpContext.Response.StatusCode = 500;\n }\n}\n</code></pre>\n\n<p>}</p>\n" }, { "answer_id": 4959927, "author": "Kevin Southworth", "author_id": 422176, "author_profile": "https://Stackoverflow.com/users/422176", "pm_score": 4, "selected": false, "text": "<p>In ASP MVC 3 you can use the <code>[AllowHtml]</code> attribute on individual fields/properties in your Model/ViewModel to turn off validation for just that field, which is pretty nice. I will add this attribute to certain fields in my model, and then use the excellent <a href=\"http://wpl.codeplex.com/\">AntiXSS</a> library (also available via NuGet) to sanitize the user input by calling the <code>Sanitizer.GetSafeHtmlFragment(mymodel.Description)</code> (where the \"Description\" property is a string property on my view model, that has the <code>[AllowHtml]</code> attribute applied)</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32173/" ]
I just want to know how to validate (or clean) user input in ASP.NET MVC so that an HttpRequestValidationException will not be thrown regardless of the values submitted. For example, with a text input, if the user inputs `<BR/>`, it will cause an exception and the Yellow Screen of Death will be shown. I don't want that. I want to catch the exception and to make visible an user friendly error in the current view, preferably with the controls loaded with the same values submitted. I have found this <http://www.romsteady.net/blog/2007/06/how-to-catch-httprequestvalidationexcep.html>, but it is useless for my purpose. Also, I have found this <http://msdn.microsoft.com/en-us/library/aa973813.aspx> and tried to put inside a model binder but I couldn't make to work.
With the latest version of ASP.NET MVC (the RC, at the time of writing this) you can just put an attribute on either your controller class or your action method, e.g.: ``` [ValidateInput(false)] public ActionResult create() { // ...method body } ``` The ValidateInputAttribute is in System.Web.Mvc. But as others have said, you do then have to perform your own manual input validation or cleaning. Using MVC 3, you must also ensure this is in your Web.config: `<system.web><httpRuntime requestValidationMode="2.0" /></system.web>`
249,074
<p>I'm sure there are a million posts about this out there, but surprisingly I'm having trouble finding something. </p> <p>I have a simple script where I want to set the onClick handler for an <code>&lt;A&gt;</code> link on initialization of the page.</p> <p>When I run this I <strong>immediately</strong> get a 'foo' alert box where I expected to only get an alert when I click on the link.</p> <p>What stupid thing am I doing wrong? (I've tried click= and onClick=)...</p> <pre><code>&lt;script language="javascript"&gt; function init(){ document.getElementById("foo").click = new function() { alert('foo'); }; } &lt;/script&gt; &lt;body onload="init()"&gt; &lt;a id="foo" href=#&gt;Click to run foo&lt;/a&gt; &lt;/body&gt; </code></pre> <hr> <p><strong>Edit:</strong> I changed my accepted answer to a jQuery answer. The answer by '<a href="https://stackoverflow.com/questions/249074/how-to-change-onclick-handler-dynamically/249093#249093">Már Örlygsson</a>' is technically the correct answer to my original question (<code>click</code> should be <code>onclick</code> and <code>new</code> should be removed) but I <strong>strongly discourage</strong> anyone from using 'document.getElementById(...) directly in their code - and to use <a href="http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery" rel="noreferrer">jQuery</a> instead.</p>
[ { "answer_id": 249084, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 6, "selected": false, "text": "<p>Try:</p>\n\n<pre><code>document.getElementById(\"foo\").onclick = function (){alert('foo');};\n</code></pre>\n" }, { "answer_id": 249091, "author": "Darryl Hein", "author_id": 5441, "author_profile": "https://Stackoverflow.com/users/5441", "pm_score": 6, "selected": true, "text": "<p>jQuery:</p>\n\n<pre><code>$('#foo').click(function() { alert('foo'); });\n</code></pre>\n\n<p>Or if you don't want it to follow the link href:</p>\n\n<pre><code>$('#foo').click(function() { alert('foo'); return false; });\n</code></pre>\n" }, { "answer_id": 249093, "author": "Már Örlygsson", "author_id": 16271, "author_profile": "https://Stackoverflow.com/users/16271", "pm_score": 5, "selected": false, "text": "<p>Use <code>.onclick</code> (all lowercase). Like so:</p>\n\n<pre><code>document.getElementById(\"foo\").onclick = function () {\n alert('foo'); // do your stuff\n return false; // &lt;-- to suppress the default link behaviour\n};\n</code></pre>\n\n<p>Actually, you'll probably find yourself way better off using some good library (I recommend <a href=\"http://www.jquery.com/\" rel=\"noreferrer\">jQuery</a> for several reasons) to get you up and running, and writing clean javascript.</p>\n\n<p>Cross-browser (in)compatibilities are a right hell to deal with for anyone - let alone someone who's just starting.</p>\n" }, { "answer_id": 249504, "author": "kgiannakakis", "author_id": 24054, "author_profile": "https://Stackoverflow.com/users/24054", "pm_score": 2, "selected": false, "text": "<p>I agree that using jQuery is the best option. You should also avoid using body's onload function and use jQuery's ready function instead. As for the event listeners, they should be functions that take one argument:</p>\n\n<pre><code>document.getElementById(\"foo\").onclick = function (event){alert('foo');};\n</code></pre>\n\n<p>or in jQuery:</p>\n\n<pre><code>$('#foo').click(function(event) { alert('foo'); }\n</code></pre>\n" }, { "answer_id": 724160, "author": "blak3r", "author_id": 67268, "author_profile": "https://Stackoverflow.com/users/67268", "pm_score": 1, "selected": false, "text": "<p>Here is the YUI counterpart to the jQuery posts above.</p>\n\n<pre><code>&lt;script&gt;\n YAHOO.util.Event.onDOMReady(function() { \n document.getElementById(\"foo\").onclick = function (){alert('foo');};\n });\n&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 1953270, "author": "Selin Ebeci", "author_id": 237657, "author_profile": "https://Stackoverflow.com/users/237657", "pm_score": 4, "selected": false, "text": "<p>I tried more or less all of the other solutions the other day, but none of them worked for me until I tried this one:</p>\n\n<pre><code>var submitButton = document.getElementById('submitButton');\nsubmitButton.setAttribute('onclick', 'alert(\"hello\");');\n</code></pre>\n\n<p>As far as I can tell, it works perfectly.</p>\n" }, { "answer_id": 2453957, "author": "Web Development Guy", "author_id": 294707, "author_profile": "https://Stackoverflow.com/users/294707", "pm_score": 0, "selected": false, "text": "<p>The YUI example above should really be:</p>\n\n<pre><code>&lt;script&gt;\n YAHOO.util.Event.onDOMReady(function() { \n Dom.get(\"foo\").onclick = function (){alert('foo');};\n });\n&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 5920918, "author": "yuttadhammo", "author_id": 560092, "author_profile": "https://Stackoverflow.com/users/560092", "pm_score": 4, "selected": false, "text": "<p>If you want to pass variables from the current function, another way to do this is, for example:</p>\n\n<pre><code>document.getElementById(\"space1\").onclick = new Function(\"lrgWithInfo('\"+myVar+\"')\");\n</code></pre>\n\n<p>If you don't need to pass information from this function, it's just:</p>\n\n<pre><code>document.getElementById(\"space1\").onclick = new Function(\"lrgWithInfo('13')\");\n</code></pre>\n" }, { "answer_id": 10019638, "author": "lamarant", "author_id": 613536, "author_profile": "https://Stackoverflow.com/users/613536", "pm_score": 0, "selected": false, "text": "<p>I think you want to use jQuery's <a href=\"http://api.jquery.com/bind/\" rel=\"nofollow\">.bind</a> and <a href=\"http://api.jquery.com/unbind/\" rel=\"nofollow\">.unBind</a> methods. In my testing, changing the click event using .click and .onclick actually called the newly assigned event, resulting in a never-ending loop. </p>\n\n<p>For example, if the events you are toggling between are hide() and unHide(), and clicking one switches the click event to the other, you would end up in a continuous loop. A better way would be to do this:</p>\n\n<pre><code>$(element).unbind().bind( 'click' , function(){ alert('!') } ); \n</code></pre>\n" }, { "answer_id": 10744345, "author": "Steven Lu", "author_id": 340947, "author_profile": "https://Stackoverflow.com/users/340947", "pm_score": 0, "selected": false, "text": "<p>Nobody addressed the actual problem which was happening, to explain why the alert was issued. </p>\n\n<p>This code: <code>document.getElementById(\"foo\").click = new function() { alert('foo'); };</code> assigns the click property of the <code>#foo</code> element to an empty object. The anonymous function in here is meant to initialize the object. I like to think of this type of function as a constructor. You put the alert in there, so it gets called because the function gets called immediately. </p>\n\n<p>See <a href=\"https://stackoverflow.com/questions/2274695/new-function-with-lower-case-f-in-javascript\">this question</a>. </p>\n" }, { "answer_id": 14333699, "author": "Eric", "author_id": 1979125, "author_profile": "https://Stackoverflow.com/users/1979125", "pm_score": 3, "selected": false, "text": "<p>OMG... It's not only a problem of \"jQuery Library\" and \"getElementById\".</p>\n\n<p>Sure, jQuery helps us to put cross-browser problems aside, but using the traditional way without libraries can still work well, if you really understand JavaScript ENOUGH!!!</p>\n\n<p>Both @Már Örlygsson and @Darryl Hein gave you good ALTARNATIVES(I'd say, they're just altarnatives, not anwsers), where the former used the traditional way, and the latter jQuery way. But do you really know the answer to your problem? What is wrong with your code?</p>\n\n<p>First, <code>.click</code> is a jQuery way. If you want to use traditional way, use .onclick instead. Or I recommend you concentrating on learning to use jQuery only, in case of confusing. jQuery is a good tool to use without knowing DOM enough.</p>\n\n<p>The second problem, also the critical one, <code>new function(){}</code> is a very bad syntax, or say it is a wrong syntax.</p>\n\n<p>No matter whether you want to go with jQuery or without it, you need to clarify it.</p>\n\n<p>There are 3 basic ways declaring function:</p>\n\n<pre><code>function name () {code}\n\n... = function() {code} // known as anonymous function or function literal\n\n... = new Function(\"code\") // Function Object\n</code></pre>\n\n<p>Note that javascript is <strong>case-sensitive</strong>, so <code>new function()</code> is not a standard syntax of javascript. Browsers may misunderstand the meaning.</p>\n\n<p>Thus your code can be modified using the second way as</p>\n\n<pre><code> = function(){alert();}\n</code></pre>\n\n<p>Or using the third way as</p>\n\n<pre><code> = new Function(\"alert();\");\n</code></pre>\n\n<p>Elaborating on it, the second way works almost the same as the third way, and the second way is very common, while the third is rare. Both of your best answers use the second way.</p>\n\n<p>However, the third way can do something that the second can't do, because of \"runtime\" and \"compile time\". I just hope you know <code>new Function()</code> can be useful sometimes. One day you meet problems using <code>function(){}</code>, don't forget <code>new Function()</code>.</p>\n\n<p>To understand more, you are recommended read &lt;&lt; JavaScript: The Definitive Guide, 6th Edition >>, O'Reilly.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249074", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16940/" ]
I'm sure there are a million posts about this out there, but surprisingly I'm having trouble finding something. I have a simple script where I want to set the onClick handler for an `<A>` link on initialization of the page. When I run this I **immediately** get a 'foo' alert box where I expected to only get an alert when I click on the link. What stupid thing am I doing wrong? (I've tried click= and onClick=)... ``` <script language="javascript"> function init(){ document.getElementById("foo").click = new function() { alert('foo'); }; } </script> <body onload="init()"> <a id="foo" href=#>Click to run foo</a> </body> ``` --- **Edit:** I changed my accepted answer to a jQuery answer. The answer by '[Már Örlygsson](https://stackoverflow.com/questions/249074/how-to-change-onclick-handler-dynamically/249093#249093)' is technically the correct answer to my original question (`click` should be `onclick` and `new` should be removed) but I **strongly discourage** anyone from using 'document.getElementById(...) directly in their code - and to use [jQuery](http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery) instead.
jQuery: ``` $('#foo').click(function() { alert('foo'); }); ``` Or if you don't want it to follow the link href: ``` $('#foo').click(function() { alert('foo'); return false; }); ```
249,087
<p>I'm trying to convert some strings that are in French Canadian and basically, I'd like to be able to take out the French accent marks in the letters while keeping the letter. (E.g. convert <code>é</code> to <code>e</code>, so <code>crème brûlée</code> would become <code>creme brulee</code>)</p> <p>What is the best method for achieving this?</p>
[ { "answer_id": 249126, "author": "Blair Conrad", "author_id": 1199, "author_profile": "https://Stackoverflow.com/users/1199", "pm_score": 10, "selected": true, "text": "<p>I've not used this method, but Michael Kaplan describes a method for doing so in his blog post (with a confusing title) that talks about stripping diacritics: <a href=\"http://archives.miloush.net/michkap/archive/2007/05/14/2629747.html\" rel=\"noreferrer\">Stripping is an interesting job (aka\nOn the meaning of meaningless, aka All\nMn characters are non-spacing, but\nsome are more non-spacing than\nothers)</a></p>\n<pre><code>static string RemoveDiacritics(string text) \n{\n var normalizedString = text.Normalize(NormalizationForm.FormD);\n var stringBuilder = new StringBuilder(capacity: normalizedString.Length);\n\n for (int i = 0; i &lt; normalizedString.Length; i++)\n {\n char c = normalizedString[i];\n var unicodeCategory = CharUnicodeInfo.GetUnicodeCategory(c);\n if (unicodeCategory != UnicodeCategory.NonSpacingMark)\n {\n stringBuilder.Append(c);\n }\n }\n\n return stringBuilder\n .ToString()\n .Normalize(NormalizationForm.FormC);\n}\n</code></pre>\n<p>Note that this is a followup to his earlier post: <a href=\"http://archives.miloush.net/michkap/archive/2005/02/19/376617.html\" rel=\"noreferrer\">Stripping diacritics....</a></p>\n<p>The approach uses <a href=\"https://msdn.microsoft.com/en-us/library/system.string.normalize.aspx\" rel=\"noreferrer\">String.Normalize</a> to split the input string into constituent glyphs (basically separating the &quot;base&quot; characters from the diacritics) and then scans the result and retains only the base characters. It's just a little complicated, but really you're looking at a complicated problem.</p>\n<p>Of course, if you're limiting yourself to French, you could probably get away with the simple table-based approach in <a href=\"https://stackoverflow.com/questions/144761/how-to-remove-accents-and-tilde-in-a-c-stdstring\">How to remove accents and tilde in a C++ std::string</a>, as recommended by @David Dibben.</p>\n" }, { "answer_id": 780800, "author": "Luk", "author_id": 5789, "author_profile": "https://Stackoverflow.com/users/5789", "pm_score": 5, "selected": false, "text": "<p>In case someone is interested, I was looking for something similar and ended writing the following:</p>\n\n<pre><code>public static string NormalizeStringForUrl(string name)\n{\n String normalizedString = name.Normalize(NormalizationForm.FormD);\n StringBuilder stringBuilder = new StringBuilder();\n\n foreach (char c in normalizedString)\n {\n switch (CharUnicodeInfo.GetUnicodeCategory(c))\n {\n case UnicodeCategory.LowercaseLetter:\n case UnicodeCategory.UppercaseLetter:\n case UnicodeCategory.DecimalDigitNumber:\n stringBuilder.Append(c);\n break;\n case UnicodeCategory.SpaceSeparator:\n case UnicodeCategory.ConnectorPunctuation:\n case UnicodeCategory.DashPunctuation:\n stringBuilder.Append('_');\n break;\n }\n }\n string result = stringBuilder.ToString();\n return String.Join(\"_\", result.Split(new char[] { '_' }\n , StringSplitOptions.RemoveEmptyEntries)); // remove duplicate underscores\n}\n</code></pre>\n" }, { "answer_id": 2086575, "author": "azrafe7", "author_id": 1158913, "author_profile": "https://Stackoverflow.com/users/1158913", "pm_score": 8, "selected": false, "text": "<p>this did the trick for me...</p>\n<pre class=\"lang-cs prettyprint-override\"><code>string accentedStr;\nbyte[] tempBytes;\ntempBytes = System.Text.Encoding.GetEncoding(&quot;ISO-8859-8&quot;).GetBytes(accentedStr);\nstring asciiStr = System.Text.Encoding.UTF8.GetString(tempBytes);\n</code></pre>\n<p>quick&amp;short!</p>\n" }, { "answer_id": 3353225, "author": "Stefanos Michanetzis", "author_id": 404544, "author_profile": "https://Stackoverflow.com/users/404544", "pm_score": 2, "selected": false, "text": "<p>THIS IS THE VB VERSION (Works with GREEK) :</p>\n\n<p>Imports System.Text</p>\n\n<p>Imports System.Globalization</p>\n\n<pre><code>Public Function RemoveDiacritics(ByVal s As String)\n Dim normalizedString As String\n Dim stringBuilder As New StringBuilder\n normalizedString = s.Normalize(NormalizationForm.FormD)\n Dim i As Integer\n Dim c As Char\n For i = 0 To normalizedString.Length - 1\n c = normalizedString(i)\n If CharUnicodeInfo.GetUnicodeCategory(c) &lt;&gt; UnicodeCategory.NonSpacingMark Then\n stringBuilder.Append(c)\n End If\n Next\n Return stringBuilder.ToString()\nEnd Function\n</code></pre>\n" }, { "answer_id": 13155469, "author": "realbart", "author_id": 1677285, "author_profile": "https://Stackoverflow.com/users/1677285", "pm_score": 4, "selected": false, "text": "<p>I often use an extenstion method based on another version I found here\n(see <a href=\"https://stackoverflow.com/questions/5459641/replacing-characters-in-c-sharp-ascii/13154805#13154805\">Replacing characters in C# (ascii)</a>)\nA quick explanation:</p>\n\n<ul>\n<li>Normalizing to form D splits charactes like <strong>è</strong> to an <strong>e</strong> and a nonspacing <strong>`</strong></li>\n<li>From this, the nospacing characters are removed</li>\n<li>The result is normalized back to form C (I'm not sure if this is neccesary)</li>\n</ul>\n\n<p>Code:</p>\n\n<pre><code>using System.Linq;\nusing System.Text;\nusing System.Globalization;\n\n// namespace here\npublic static class Utility\n{\n public static string RemoveDiacritics(this string str)\n {\n if (null == str) return null;\n var chars =\n from c in str.Normalize(NormalizationForm.FormD).ToCharArray()\n let uc = CharUnicodeInfo.GetUnicodeCategory(c)\n where uc != UnicodeCategory.NonSpacingMark\n select c;\n\n var cleanStr = new string(chars.ToArray()).Normalize(NormalizationForm.FormC);\n\n return cleanStr;\n }\n\n // or, alternatively\n public static string RemoveDiacritics2(this string str)\n {\n if (null == str) return null;\n var chars = str\n .Normalize(NormalizationForm.FormD)\n .ToCharArray()\n .Where(c=&gt; CharUnicodeInfo.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark)\n .ToArray();\n\n return new string(chars).Normalize(NormalizationForm.FormC);\n }\n}\n</code></pre>\n" }, { "answer_id": 16350657, "author": "giacomelli", "author_id": 956886, "author_profile": "https://Stackoverflow.com/users/956886", "pm_score": 1, "selected": false, "text": "<p>Try <a href=\"https://github.com/giacomelli/HelperSharp\" rel=\"nofollow\">HelperSharp package</a>.</p>\n\n<p>There is a method RemoveAccents:</p>\n\n<pre><code> public static string RemoveAccents(this string source)\n {\n //8 bit characters \n byte[] b = Encoding.GetEncoding(1251).GetBytes(source);\n\n // 7 bit characters\n string t = Encoding.ASCII.GetString(b);\n Regex re = new Regex(\"[^a-zA-Z0-9]=-_/\");\n string c = re.Replace(t, \" \");\n return c;\n }\n</code></pre>\n" }, { "answer_id": 18002273, "author": "Heyjee", "author_id": 1978167, "author_profile": "https://Stackoverflow.com/users/1978167", "pm_score": 2, "selected": false, "text": "<p>This is how i replace diacritic characters to non-diacritic ones in all my .NET program</p>\n\n<p>C#:</p>\n\n<pre><code>//Transforms the culture of a letter to its equivalent representation in the 0-127 ascii table, such as the letter 'é' is substituted by an 'e'\npublic string RemoveDiacritics(string s)\n{\n string normalizedString = null;\n StringBuilder stringBuilder = new StringBuilder();\n normalizedString = s.Normalize(NormalizationForm.FormD);\n int i = 0;\n char c = '\\0';\n\n for (i = 0; i &lt;= normalizedString.Length - 1; i++)\n {\n c = normalizedString[i];\n if (CharUnicodeInfo.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark)\n {\n stringBuilder.Append(c);\n }\n }\n\n return stringBuilder.ToString().ToLower();\n}\n</code></pre>\n\n<p>VB .NET:</p>\n\n<pre><code>'Transforms the culture of a letter to its equivalent representation in the 0-127 ascii table, such as the letter \"é\" is substituted by an \"e\"'\nPublic Function RemoveDiacritics(ByVal s As String) As String\n Dim normalizedString As String\n Dim stringBuilder As New StringBuilder\n normalizedString = s.Normalize(NormalizationForm.FormD)\n Dim i As Integer\n Dim c As Char\n\n For i = 0 To normalizedString.Length - 1\n c = normalizedString(i)\n If CharUnicodeInfo.GetUnicodeCategory(c) &lt;&gt; UnicodeCategory.NonSpacingMark Then\n stringBuilder.Append(c)\n End If\n Next\n Return stringBuilder.ToString().ToLower()\nEnd Function\n</code></pre>\n" }, { "answer_id": 20837592, "author": "Mino", "author_id": 2470786, "author_profile": "https://Stackoverflow.com/users/2470786", "pm_score": 1, "selected": false, "text": "<p>you can use string extension from MMLib.Extensions nuget package:</p>\n\n<pre><code>using MMLib.RapidPrototyping.Generators;\npublic void ExtensionsExample()\n{\n string target = \"aácčeéií\";\n Assert.AreEqual(\"aacceeii\", target.RemoveDiacritics());\n} \n</code></pre>\n\n<hr>\n\n<p>Nuget page: <a href=\"https://www.nuget.org/packages/MMLib.Extensions/\" rel=\"nofollow\">https://www.nuget.org/packages/MMLib.Extensions/</a>\nCodeplex project site <a href=\"https://mmlib.codeplex.com/\" rel=\"nofollow\">https://mmlib.codeplex.com/</a></p>\n" }, { "answer_id": 30981339, "author": "Tratak", "author_id": 2062118, "author_profile": "https://Stackoverflow.com/users/2062118", "pm_score": 1, "selected": false, "text": "<pre><code>Imports System.Text\nImports System.Globalization\n\n Public Function DECODE(ByVal x As String) As String\n Dim sb As New StringBuilder\n For Each c As Char In x.Normalize(NormalizationForm.FormD).Where(Function(a) CharUnicodeInfo.GetUnicodeCategory(a) &lt;&gt; UnicodeCategory.NonSpacingMark) \n sb.Append(c)\n Next\n Return sb.ToString()\n End Function\n</code></pre>\n" }, { "answer_id": 34228877, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/a/148137/3638471\">What this person said:</a></p>\n\n<p><code>Encoding.ASCII.GetString(Encoding.GetEncoding(1251).GetBytes(text));</code></p>\n\n<p>It actually splits the likes of <code>å</code> which is one character (which is character code <code>00E5</code>, <em>not</em> <code>0061</code> plus the modifier <code>030A</code> which would look the same) into <code>a</code> plus some kind of modifier, and then the ASCII conversion removes the modifier, leaving the only <code>a</code>.</p>\n" }, { "answer_id": 34272324, "author": "CIRCLE", "author_id": 2011284, "author_profile": "https://Stackoverflow.com/users/2011284", "pm_score": 5, "selected": false, "text": "<p>I needed something that converts all major unicode characters and the voted answer leaved a few out so I've created a version of CodeIgniter's <code>convert_accented_characters($str)</code> into C# that is easily customisable:</p>\n\n<pre><code>using System;\nusing System.Text;\nusing System.Collections.Generic;\n\npublic static class Strings\n{\n static Dictionary&lt;string, string&gt; foreign_characters = new Dictionary&lt;string, string&gt;\n {\n { \"äæǽ\", \"ae\" },\n { \"öœ\", \"oe\" },\n { \"ü\", \"ue\" },\n { \"Ä\", \"Ae\" },\n { \"Ü\", \"Ue\" },\n { \"Ö\", \"Oe\" },\n { \"ÀÁÂÃÄÅǺĀĂĄǍΑΆẢẠẦẪẨẬẰẮẴẲẶА\", \"A\" },\n { \"àáâãåǻāăąǎªαάảạầấẫẩậằắẵẳặа\", \"a\" },\n { \"Б\", \"B\" },\n { \"б\", \"b\" },\n { \"ÇĆĈĊČ\", \"C\" },\n { \"çćĉċč\", \"c\" },\n { \"Д\", \"D\" },\n { \"д\", \"d\" },\n { \"ÐĎĐΔ\", \"Dj\" },\n { \"ðďđδ\", \"dj\" },\n { \"ÈÉÊËĒĔĖĘĚΕΈẼẺẸỀẾỄỂỆЕЭ\", \"E\" },\n { \"èéêëēĕėęěέεẽẻẹềếễểệеэ\", \"e\" },\n { \"Ф\", \"F\" },\n { \"ф\", \"f\" },\n { \"ĜĞĠĢΓГҐ\", \"G\" },\n { \"ĝğġģγгґ\", \"g\" },\n { \"ĤĦ\", \"H\" },\n { \"ĥħ\", \"h\" },\n { \"ÌÍÎÏĨĪĬǏĮİΗΉΊΙΪỈỊИЫ\", \"I\" },\n { \"ìíîïĩīĭǐįıηήίιϊỉịиыї\", \"i\" },\n { \"Ĵ\", \"J\" },\n { \"ĵ\", \"j\" },\n { \"ĶΚК\", \"K\" },\n { \"ķκк\", \"k\" },\n { \"ĹĻĽĿŁΛЛ\", \"L\" },\n { \"ĺļľŀłλл\", \"l\" },\n { \"М\", \"M\" },\n { \"м\", \"m\" },\n { \"ÑŃŅŇΝН\", \"N\" },\n { \"ñńņňʼnνн\", \"n\" },\n { \"ÒÓÔÕŌŎǑŐƠØǾΟΌΩΏỎỌỒỐỖỔỘỜỚỠỞỢО\", \"O\" },\n { \"òóôõōŏǒőơøǿºοόωώỏọồốỗổộờớỡởợо\", \"o\" },\n { \"П\", \"P\" },\n { \"п\", \"p\" },\n { \"ŔŖŘΡР\", \"R\" },\n { \"ŕŗřρр\", \"r\" },\n { \"ŚŜŞȘŠΣС\", \"S\" },\n { \"śŝşșšſσςс\", \"s\" },\n { \"ȚŢŤŦτТ\", \"T\" },\n { \"țţťŧт\", \"t\" },\n { \"ÙÚÛŨŪŬŮŰŲƯǓǕǗǙǛŨỦỤỪỨỮỬỰУ\", \"U\" },\n { \"ùúûũūŭůűųưǔǖǘǚǜυύϋủụừứữửựу\", \"u\" },\n { \"ÝŸŶΥΎΫỲỸỶỴЙ\", \"Y\" },\n { \"ýÿŷỳỹỷỵй\", \"y\" },\n { \"В\", \"V\" },\n { \"в\", \"v\" },\n { \"Ŵ\", \"W\" },\n { \"ŵ\", \"w\" },\n { \"ŹŻŽΖЗ\", \"Z\" },\n { \"źżžζз\", \"z\" },\n { \"ÆǼ\", \"AE\" },\n { \"ß\", \"ss\" },\n { \"IJ\", \"IJ\" },\n { \"ij\", \"ij\" },\n { \"Œ\", \"OE\" },\n { \"ƒ\", \"f\" },\n { \"ξ\", \"ks\" },\n { \"π\", \"p\" },\n { \"β\", \"v\" },\n { \"μ\", \"m\" },\n { \"ψ\", \"ps\" },\n { \"Ё\", \"Yo\" },\n { \"ё\", \"yo\" },\n { \"Є\", \"Ye\" },\n { \"є\", \"ye\" },\n { \"Ї\", \"Yi\" },\n { \"Ж\", \"Zh\" },\n { \"ж\", \"zh\" },\n { \"Х\", \"Kh\" },\n { \"х\", \"kh\" },\n { \"Ц\", \"Ts\" },\n { \"ц\", \"ts\" },\n { \"Ч\", \"Ch\" },\n { \"ч\", \"ch\" },\n { \"Ш\", \"Sh\" },\n { \"ш\", \"sh\" },\n { \"Щ\", \"Shch\" },\n { \"щ\", \"shch\" },\n { \"ЪъЬь\", \"\" },\n { \"Ю\", \"Yu\" },\n { \"ю\", \"yu\" },\n { \"Я\", \"Ya\" },\n { \"я\", \"ya\" },\n };\n\n public static char RemoveDiacritics(this char c){\n foreach(KeyValuePair&lt;string, string&gt; entry in foreign_characters)\n {\n if(entry.Key.IndexOf (c) != -1)\n {\n return entry.Value[0];\n }\n }\n return c;\n }\n\n public static string RemoveDiacritics(this string s) \n {\n //StringBuilder sb = new StringBuilder ();\n string text = \"\";\n\n\n foreach (char c in s)\n {\n int len = text.Length;\n\n foreach(KeyValuePair&lt;string, string&gt; entry in foreign_characters)\n {\n if(entry.Key.IndexOf (c) != -1)\n {\n text += entry.Value;\n break;\n }\n }\n\n if (len == text.Length) {\n text += c; \n }\n }\n return text;\n }\n}\n</code></pre>\n\n<p><strong>Usage</strong></p>\n\n<pre><code>// for strings\n\"crème brûlée\".RemoveDiacritics (); // creme brulee\n\n// for chars\n\"Ã\"[0].RemoveDiacritics (); // A\n</code></pre>\n" }, { "answer_id": 38779892, "author": "Sergio Cabral", "author_id": 1396511, "author_profile": "https://Stackoverflow.com/users/1396511", "pm_score": 4, "selected": false, "text": "<p>The CodePage of <strong>Greek (ISO)</strong> can do it</p>\n\n<p>The information about this codepage is into <code>System.Text.Encoding.GetEncodings()</code>. Learn about in: <a href=\"https://msdn.microsoft.com/pt-br/library/system.text.encodinginfo.getencoding(v=vs.110).aspx\" rel=\"noreferrer\">https://msdn.microsoft.com/pt-br/library/system.text.encodinginfo.getencoding(v=vs.110).aspx</a></p>\n\n<p>Greek (ISO) has codepage <strong>28597</strong> and name <strong>iso-8859-7</strong>.</p>\n\n<p>Go to the code... \\o/</p>\n\n<pre><code>string text = \"Você está numa situação lamentável\";\n\nstring textEncode = System.Web.HttpUtility.UrlEncode(text, Encoding.GetEncoding(\"iso-8859-7\"));\n//result: \"Voce+esta+numa+situacao+lamentavel\"\n\nstring textDecode = System.Web.HttpUtility.UrlDecode(textEncode);\n//result: \"Voce esta numa situacao lamentavel\"\n</code></pre>\n\n<p>So, write this function...</p>\n\n<pre><code>public string RemoveAcentuation(string text)\n{\n return\n System.Web.HttpUtility.UrlDecode(\n System.Web.HttpUtility.UrlEncode(\n text, Encoding.GetEncoding(\"iso-8859-7\")));\n}\n</code></pre>\n\n<p>Note that... <code>Encoding.GetEncoding(\"iso-8859-7\")</code> is equivalent to <code>Encoding.GetEncoding(28597)</code> because first is the name, and second the codepage of Encoding.</p>\n" }, { "answer_id": 42068811, "author": "EricBDev", "author_id": 6579566, "author_profile": "https://Stackoverflow.com/users/6579566", "pm_score": 3, "selected": false, "text": "<p>It's funny such a question can get so many answers, and yet none fit my requirements :) There are so many languages around, a full language agnostic solution is AFAIK not really possible, as others has mentionned that the FormC or FormD are giving issues.</p>\n\n<p>Since the original question was related to French, the simplest working answer is indeed </p>\n\n<pre><code> public static string ConvertWesternEuropeanToASCII(this string str)\n {\n return Encoding.ASCII.GetString(Encoding.GetEncoding(1251).GetBytes(str));\n }\n</code></pre>\n\n<p>1251 should be replaced by the encoding code of the input language.</p>\n\n<p>This however replace only one character by one character. Since I am also working with German as input, I did a manual convert</p>\n\n<pre><code> public static string LatinizeGermanCharacters(this string str)\n {\n StringBuilder sb = new StringBuilder(str.Length);\n foreach (char c in str)\n {\n switch (c)\n {\n case 'ä':\n sb.Append(\"ae\");\n break;\n case 'ö':\n sb.Append(\"oe\");\n break;\n case 'ü':\n sb.Append(\"ue\");\n break;\n case 'Ä':\n sb.Append(\"Ae\");\n break;\n case 'Ö':\n sb.Append(\"Oe\");\n break;\n case 'Ü':\n sb.Append(\"Ue\");\n break;\n case 'ß':\n sb.Append(\"ss\");\n break;\n default:\n sb.Append(c);\n break;\n }\n }\n return sb.ToString();\n }\n</code></pre>\n\n<p>It might not deliver the best performance, but at least it is very easy to read and extend.\nRegex is a NO GO, much slower than any char/string stuff.</p>\n\n<p>I also have a very simple method to remove space:</p>\n\n<pre><code> public static string RemoveSpace(this string str)\n {\n return str.Replace(\" \", string.Empty);\n }\n</code></pre>\n\n<p>Eventually, I am using a combination of all 3 above extensions:</p>\n\n<pre><code> public static string LatinizeAndConvertToASCII(this string str, bool keepSpace = false)\n {\n str = str.LatinizeGermanCharacters().ConvertWesternEuropeanToASCII(); \n return keepSpace ? str : str.RemoveSpace();\n }\n</code></pre>\n\n<p>And a small unit test to that (not exhaustive) which pass successfully.</p>\n\n<pre><code> [TestMethod()]\n public void LatinizeAndConvertToASCIITest()\n {\n string europeanStr = \"Bonjour ça va? C'est l'été! Ich möchte ä Ä á à â ê é è ë Ë É ï Ï î í ì ó ò ô ö Ö Ü ü ù ú û Û ý Ý ç Ç ñ Ñ\";\n string expected = \"Bonjourcava?C'estl'ete!IchmoechteaeAeaaaeeeeEEiIiiiooooeOeUeueuuuUyYcCnN\";\n string actual = europeanStr.LatinizeAndConvertToASCII();\n Assert.AreEqual(expected, actual);\n }\n</code></pre>\n" }, { "answer_id": 42234063, "author": "Siavash Mortazavi", "author_id": 1854557, "author_profile": "https://Stackoverflow.com/users/1854557", "pm_score": 1, "selected": false, "text": "<p>I really like the concise and functional code provided by <a href=\"https://stackoverflow.com/users/253243/azrafe7\">azrafe7</a>.\nSo, I have changed it a little bit to convert it to an extension method:</p>\n\n<pre><code>public static class StringExtensions\n{\n public static string RemoveDiacritics(this string text)\n {\n const string SINGLEBYTE_LATIN_ASCII_ENCODING = \"ISO-8859-8\";\n\n if (string.IsNullOrEmpty(text))\n {\n return string.Empty;\n }\n\n return Encoding.ASCII.GetString(\n Encoding.GetEncoding(SINGLEBYTE_LATIN_ASCII_ENCODING).GetBytes(text));\n }\n}\n</code></pre>\n" }, { "answer_id": 44101827, "author": "Squiggs.", "author_id": 42446, "author_profile": "https://Stackoverflow.com/users/42446", "pm_score": 2, "selected": false, "text": "<p>Popping this Library here if you haven't already considered it. Looks like there are a full range of unit tests with it. </p>\n\n<p><a href=\"https://github.com/thomasgalliker/Diacritics.NET\" rel=\"nofollow noreferrer\">https://github.com/thomasgalliker/Diacritics.NET</a></p>\n" }, { "answer_id": 55669972, "author": "Adrian", "author_id": 5958655, "author_profile": "https://Stackoverflow.com/users/5958655", "pm_score": -1, "selected": false, "text": "<p>Not having enough reputations, apparently I can not comment on Alexander's excellent link. - Lucene appears to be the only solution working in reasonably generic cases. </p>\n\n<p>For those wanting a simple copy-paste solution, here it is, leveraging code in Lucene:</p>\n\n<p>string testbed = \"ÁÂÄÅÇÉÍÎÓÖØÚÜÞàáâãäåæçèéêëìíîïðñóôöøúüāăčĐęğıŁłńŌōřŞşšźžșțệủ\";</p>\n\n<p>Console.WriteLine(Lucene.latinizeLucene(testbed));</p>\n\n<blockquote>\n <blockquote>\n <p>AAAACEIIOOOUUTHaaaaaaaeceeeeiiiidnoooouuaacDegiLlnOorSsszzsteu</p>\n </blockquote>\n</blockquote>\n\n<p>//////////</p>\n\n<pre><code>public static class Lucene\n{\n // source: https://raw.githubusercontent.com/apache/lucenenet/master/src/Lucene.Net.Analysis.Common/Analysis/Miscellaneous/ASCIIFoldingFilter.cs\n // idea: https://stackoverflow.com/questions/249087/how-do-i-remove-diacritics-accents-from-a-string-in-net (scroll down, search for lucene by Alexander)\n public static string latinizeLucene(string arg)\n {\n char[] argChar = arg.ToCharArray();\n\n // latinizeLuceneImpl can expand one char up to four chars - e.g. Þ to TH, or æ to ae, or in fact ⑽ to (10)\n char[] resultChar = new String(' ', arg.Length * 4).ToCharArray();\n\n int outputPos = Lucene.latinizeLuceneImpl(argChar, 0, ref resultChar, 0, arg.Length);\n\n string ret = new string(resultChar);\n ret = ret.Substring(0, outputPos);\n\n return ret;\n }\n\n /// &lt;summary&gt;\n /// Converts characters above ASCII to their ASCII equivalents. For example,\n /// accents are removed from accented characters. \n /// &lt;para/&gt;\n /// @lucene.internal\n /// &lt;/summary&gt;\n /// &lt;param name=\"input\"&gt; The characters to fold &lt;/param&gt;\n /// &lt;param name=\"inputPos\"&gt; Index of the first character to fold &lt;/param&gt;\n /// &lt;param name=\"output\"&gt; The result of the folding. Should be of size &gt;= &lt;c&gt;length * 4&lt;/c&gt;. &lt;/param&gt;\n /// &lt;param name=\"outputPos\"&gt; Index of output where to put the result of the folding &lt;/param&gt;\n /// &lt;param name=\"length\"&gt; The number of characters to fold &lt;/param&gt;\n /// &lt;returns&gt; length of output &lt;/returns&gt;\n private static int latinizeLuceneImpl(char[] input, int inputPos, ref char[] output, int outputPos, int length)\n {\n int end = inputPos + length;\n for (int pos = inputPos; pos &lt; end; ++pos)\n {\n char c = input[pos];\n\n // Quick test: if it's not in range then just keep current character\n if (c &lt; '\\u0080')\n {\n output[outputPos++] = c;\n }\n else\n {\n switch (c)\n {\n case '\\u00C0': // À [LATIN CAPITAL LETTER A WITH GRAVE]\n case '\\u00C1': // Á [LATIN CAPITAL LETTER A WITH ACUTE]\n case '\\u00C2': //  [LATIN CAPITAL LETTER A WITH CIRCUMFLEX]\n case '\\u00C3': // à [LATIN CAPITAL LETTER A WITH TILDE]\n case '\\u00C4': // Ä [LATIN CAPITAL LETTER A WITH DIAERESIS]\n case '\\u00C5': // Å [LATIN CAPITAL LETTER A WITH RING ABOVE]\n case '\\u0100': // Ā [LATIN CAPITAL LETTER A WITH MACRON]\n case '\\u0102': // Ă [LATIN CAPITAL LETTER A WITH BREVE]\n case '\\u0104': // Ą [LATIN CAPITAL LETTER A WITH OGONEK]\n case '\\u018F': // Ə http://en.wikipedia.org/wiki/Schwa [LATIN CAPITAL LETTER SCHWA]\n case '\\u01CD': // Ǎ [LATIN CAPITAL LETTER A WITH CARON]\n case '\\u01DE': // Ǟ [LATIN CAPITAL LETTER A WITH DIAERESIS AND MACRON]\n case '\\u01E0': // Ǡ [LATIN CAPITAL LETTER A WITH DOT ABOVE AND MACRON]\n case '\\u01FA': // Ǻ [LATIN CAPITAL LETTER A WITH RING ABOVE AND ACUTE]\n case '\\u0200': // Ȁ [LATIN CAPITAL LETTER A WITH DOUBLE GRAVE]\n case '\\u0202': // Ȃ [LATIN CAPITAL LETTER A WITH INVERTED BREVE]\n case '\\u0226': // Ȧ [LATIN CAPITAL LETTER A WITH DOT ABOVE]\n case '\\u023A': // Ⱥ [LATIN CAPITAL LETTER A WITH STROKE]\n case '\\u1D00': // ᴀ [LATIN LETTER SMALL CAPITAL A]\n case '\\u1E00': // Ḁ [LATIN CAPITAL LETTER A WITH RING BELOW]\n case '\\u1EA0': // Ạ [LATIN CAPITAL LETTER A WITH DOT BELOW]\n case '\\u1EA2': // Ả [LATIN CAPITAL LETTER A WITH HOOK ABOVE]\n case '\\u1EA4': // Ấ [LATIN CAPITAL LETTER A WITH CIRCUMFLEX AND ACUTE]\n case '\\u1EA6': // Ầ [LATIN CAPITAL LETTER A WITH CIRCUMFLEX AND GRAVE]\n case '\\u1EA8': // Ẩ [LATIN CAPITAL LETTER A WITH CIRCUMFLEX AND HOOK ABOVE]\n case '\\u1EAA': // Ẫ [LATIN CAPITAL LETTER A WITH CIRCUMFLEX AND TILDE]\n case '\\u1EAC': // Ậ [LATIN CAPITAL LETTER A WITH CIRCUMFLEX AND DOT BELOW]\n case '\\u1EAE': // Ắ [LATIN CAPITAL LETTER A WITH BREVE AND ACUTE]\n case '\\u1EB0': // Ằ [LATIN CAPITAL LETTER A WITH BREVE AND GRAVE]\n case '\\u1EB2': // Ẳ [LATIN CAPITAL LETTER A WITH BREVE AND HOOK ABOVE]\n case '\\u1EB4': // Ẵ [LATIN CAPITAL LETTER A WITH BREVE AND TILDE]\n case '\\u1EB6': // Ặ [LATIN CAPITAL LETTER A WITH BREVE AND DOT BELOW]\n case '\\u24B6': // Ⓐ [CIRCLED LATIN CAPITAL LETTER A]\n case '\\uFF21': // A [FULLWIDTH LATIN CAPITAL LETTER A]\n output[outputPos++] = 'A';\n break;\n case '\\u00E0': // à [LATIN SMALL LETTER A WITH GRAVE]\n case '\\u00E1': // á [LATIN SMALL LETTER A WITH ACUTE]\n case '\\u00E2': // â [LATIN SMALL LETTER A WITH CIRCUMFLEX]\n case '\\u00E3': // ã [LATIN SMALL LETTER A WITH TILDE]\n case '\\u00E4': // ä [LATIN SMALL LETTER A WITH DIAERESIS]\n case '\\u00E5': // å [LATIN SMALL LETTER A WITH RING ABOVE]\n case '\\u0101': // ā [LATIN SMALL LETTER A WITH MACRON]\n case '\\u0103': // ă [LATIN SMALL LETTER A WITH BREVE]\n case '\\u0105': // ą [LATIN SMALL LETTER A WITH OGONEK]\n case '\\u01CE': // ǎ [LATIN SMALL LETTER A WITH CARON]\n case '\\u01DF': // ǟ [LATIN SMALL LETTER A WITH DIAERESIS AND MACRON]\n case '\\u01E1': // ǡ [LATIN SMALL LETTER A WITH DOT ABOVE AND MACRON]\n case '\\u01FB': // ǻ [LATIN SMALL LETTER A WITH RING ABOVE AND ACUTE]\n case '\\u0201': // ȁ [LATIN SMALL LETTER A WITH DOUBLE GRAVE]\n case '\\u0203': // ȃ [LATIN SMALL LETTER A WITH INVERTED BREVE]\n case '\\u0227': // ȧ [LATIN SMALL LETTER A WITH DOT ABOVE]\n case '\\u0250': // ɐ [LATIN SMALL LETTER TURNED A]\n case '\\u0259': // ə [LATIN SMALL LETTER SCHWA]\n case '\\u025A': // ɚ [LATIN SMALL LETTER SCHWA WITH HOOK]\n case '\\u1D8F': // ᶏ [LATIN SMALL LETTER A WITH RETROFLEX HOOK]\n case '\\u1D95': // ᶕ [LATIN SMALL LETTER SCHWA WITH RETROFLEX HOOK]\n case '\\u1E01': // ạ [LATIN SMALL LETTER A WITH RING BELOW]\n case '\\u1E9A': // ả [LATIN SMALL LETTER A WITH RIGHT HALF RING]\n case '\\u1EA1': // ạ [LATIN SMALL LETTER A WITH DOT BELOW]\n case '\\u1EA3': // ả [LATIN SMALL LETTER A WITH HOOK ABOVE]\n case '\\u1EA5': // ấ [LATIN SMALL LETTER A WITH CIRCUMFLEX AND ACUTE]\n case '\\u1EA7': // ầ [LATIN SMALL LETTER A WITH CIRCUMFLEX AND GRAVE]\n case '\\u1EA9': // ẩ [LATIN SMALL LETTER A WITH CIRCUMFLEX AND HOOK ABOVE]\n case '\\u1EAB': // ẫ [LATIN SMALL LETTER A WITH CIRCUMFLEX AND TILDE]\n case '\\u1EAD': // ậ [LATIN SMALL LETTER A WITH CIRCUMFLEX AND DOT BELOW]\n case '\\u1EAF': // ắ [LATIN SMALL LETTER A WITH BREVE AND ACUTE]\n case '\\u1EB1': // ằ [LATIN SMALL LETTER A WITH BREVE AND GRAVE]\n case '\\u1EB3': // ẳ [LATIN SMALL LETTER A WITH BREVE AND HOOK ABOVE]\n case '\\u1EB5': // ẵ [LATIN SMALL LETTER A WITH BREVE AND TILDE]\n case '\\u1EB7': // ặ [LATIN SMALL LETTER A WITH BREVE AND DOT BELOW]\n case '\\u2090': // ₐ [LATIN SUBSCRIPT SMALL LETTER A]\n case '\\u2094': // ₔ [LATIN SUBSCRIPT SMALL LETTER SCHWA]\n case '\\u24D0': // ⓐ [CIRCLED LATIN SMALL LETTER A]\n case '\\u2C65': // ⱥ [LATIN SMALL LETTER A WITH STROKE]\n case '\\u2C6F': // Ɐ [LATIN CAPITAL LETTER TURNED A]\n case '\\uFF41': // a [FULLWIDTH LATIN SMALL LETTER A]\n output[outputPos++] = 'a';\n break;\n case '\\uA732': // Ꜳ [LATIN CAPITAL LETTER AA]\n output[outputPos++] = 'A';\n output[outputPos++] = 'A';\n break;\n case '\\u00C6': // Æ [LATIN CAPITAL LETTER AE]\n case '\\u01E2': // Ǣ [LATIN CAPITAL LETTER AE WITH MACRON]\n case '\\u01FC': // Ǽ [LATIN CAPITAL LETTER AE WITH ACUTE]\n case '\\u1D01': // ᴁ [LATIN LETTER SMALL CAPITAL AE]\n output[outputPos++] = 'A';\n output[outputPos++] = 'E';\n break;\n case '\\uA734': // Ꜵ [LATIN CAPITAL LETTER AO]\n output[outputPos++] = 'A';\n output[outputPos++] = 'O';\n break;\n case '\\uA736': // Ꜷ [LATIN CAPITAL LETTER AU]\n output[outputPos++] = 'A';\n output[outputPos++] = 'U';\n break;\n\n // etc. etc. etc.\n // see link above for complete source code\n // \n // unfortunately, postings are limited, as in\n // \"Body is limited to 30000 characters; you entered 136098.\"\n\n [...]\n\n case '\\u2053': // ⁓ [SWUNG DASH]\n case '\\uFF5E': // ~ [FULLWIDTH TILDE]\n output[outputPos++] = '~';\n break;\n default:\n output[outputPos++] = c;\n break;\n }\n }\n }\n return outputPos;\n }\n}\n</code></pre>\n" }, { "answer_id": 56797567, "author": "Andy Raddatz", "author_id": 479701, "author_profile": "https://Stackoverflow.com/users/479701", "pm_score": 4, "selected": false, "text": "<p>TL;DR - <a href=\"https://gist.github.com/andyraddatz/e6a396fb91856174d4e3f1bf2e10951c\" rel=\"noreferrer\">C# string extension method</a></p>\n\n<p>I think the best solution to preserve the meaning of the string is to convert the characters instead of stripping them, which is well illustrated in the example <code>crème brûlée</code> to <code>crme brle</code> vs. <code>creme brulee</code>.</p>\n\n<p>I checked out <a href=\"https://stackoverflow.com/questions/249087/how-do-i-remove-diacritics-accents-from-a-string-in-net#comment86833005_34272324\">Alexander's comment above</a> and saw the Lucene.Net code is Apache 2.0 licensed, so I've modified the class into a simple string extension method. You can use it like this:</p>\n\n<pre><code>var originalString = \"crème brûlée\";\nvar maxLength = originalString.Length; // limit output length as necessary\nvar foldedString = originalString.FoldToASCII(maxLength); \n// \"creme brulee\"\n</code></pre>\n\n<p>The function is too long to post in a StackOverflow answer (~139k characters of 30k allowed lol) so <a href=\"https://gist.github.com/andyraddatz/e6a396fb91856174d4e3f1bf2e10951c\" rel=\"noreferrer\">I made a gist and attributed the authors</a>: </p>\n\n<pre><code>/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/// &lt;summary&gt;\n/// This class converts alphabetic, numeric, and symbolic Unicode characters\n/// which are not in the first 127 ASCII characters (the \"Basic Latin\" Unicode\n/// block) into their ASCII equivalents, if one exists.\n/// &lt;para/&gt;\n/// Characters from the following Unicode blocks are converted; however, only\n/// those characters with reasonable ASCII alternatives are converted:\n/// \n/// &lt;ul&gt;\n/// &lt;item&gt;&lt;description&gt;C1 Controls and Latin-1 Supplement: &lt;a href=\"http://www.unicode.org/charts/PDF/U0080.pdf\"&gt;http://www.unicode.org/charts/PDF/U0080.pdf&lt;/a&gt;&lt;/description&gt;&lt;/item&gt;\n/// &lt;item&gt;&lt;description&gt;Latin Extended-A: &lt;a href=\"http://www.unicode.org/charts/PDF/U0100.pdf\"&gt;http://www.unicode.org/charts/PDF/U0100.pdf&lt;/a&gt;&lt;/description&gt;&lt;/item&gt;\n/// &lt;item&gt;&lt;description&gt;Latin Extended-B: &lt;a href=\"http://www.unicode.org/charts/PDF/U0180.pdf\"&gt;http://www.unicode.org/charts/PDF/U0180.pdf&lt;/a&gt;&lt;/description&gt;&lt;/item&gt;\n/// &lt;item&gt;&lt;description&gt;Latin Extended Additional: &lt;a href=\"http://www.unicode.org/charts/PDF/U1E00.pdf\"&gt;http://www.unicode.org/charts/PDF/U1E00.pdf&lt;/a&gt;&lt;/description&gt;&lt;/item&gt;\n/// &lt;item&gt;&lt;description&gt;Latin Extended-C: &lt;a href=\"http://www.unicode.org/charts/PDF/U2C60.pdf\"&gt;http://www.unicode.org/charts/PDF/U2C60.pdf&lt;/a&gt;&lt;/description&gt;&lt;/item&gt;\n/// &lt;item&gt;&lt;description&gt;Latin Extended-D: &lt;a href=\"http://www.unicode.org/charts/PDF/UA720.pdf\"&gt;http://www.unicode.org/charts/PDF/UA720.pdf&lt;/a&gt;&lt;/description&gt;&lt;/item&gt;\n/// &lt;item&gt;&lt;description&gt;IPA Extensions: &lt;a href=\"http://www.unicode.org/charts/PDF/U0250.pdf\"&gt;http://www.unicode.org/charts/PDF/U0250.pdf&lt;/a&gt;&lt;/description&gt;&lt;/item&gt;\n/// &lt;item&gt;&lt;description&gt;Phonetic Extensions: &lt;a href=\"http://www.unicode.org/charts/PDF/U1D00.pdf\"&gt;http://www.unicode.org/charts/PDF/U1D00.pdf&lt;/a&gt;&lt;/description&gt;&lt;/item&gt;\n/// &lt;item&gt;&lt;description&gt;Phonetic Extensions Supplement: &lt;a href=\"http://www.unicode.org/charts/PDF/U1D80.pdf\"&gt;http://www.unicode.org/charts/PDF/U1D80.pdf&lt;/a&gt;&lt;/description&gt;&lt;/item&gt;\n/// &lt;item&gt;&lt;description&gt;General Punctuation: &lt;a href=\"http://www.unicode.org/charts/PDF/U2000.pdf\"&gt;http://www.unicode.org/charts/PDF/U2000.pdf&lt;/a&gt;&lt;/description&gt;&lt;/item&gt;\n/// &lt;item&gt;&lt;description&gt;Superscripts and Subscripts: &lt;a href=\"http://www.unicode.org/charts/PDF/U2070.pdf\"&gt;http://www.unicode.org/charts/PDF/U2070.pdf&lt;/a&gt;&lt;/description&gt;&lt;/item&gt;\n/// &lt;item&gt;&lt;description&gt;Enclosed Alphanumerics: &lt;a href=\"http://www.unicode.org/charts/PDF/U2460.pdf\"&gt;http://www.unicode.org/charts/PDF/U2460.pdf&lt;/a&gt;&lt;/description&gt;&lt;/item&gt;\n/// &lt;item&gt;&lt;description&gt;Dingbats: &lt;a href=\"http://www.unicode.org/charts/PDF/U2700.pdf\"&gt;http://www.unicode.org/charts/PDF/U2700.pdf&lt;/a&gt;&lt;/description&gt;&lt;/item&gt;\n/// &lt;item&gt;&lt;description&gt;Supplemental Punctuation: &lt;a href=\"http://www.unicode.org/charts/PDF/U2E00.pdf\"&gt;http://www.unicode.org/charts/PDF/U2E00.pdf&lt;/a&gt;&lt;/description&gt;&lt;/item&gt;\n/// &lt;item&gt;&lt;description&gt;Alphabetic Presentation Forms: &lt;a href=\"http://www.unicode.org/charts/PDF/UFB00.pdf\"&gt;http://www.unicode.org/charts/PDF/UFB00.pdf&lt;/a&gt;&lt;/description&gt;&lt;/item&gt;\n/// &lt;item&gt;&lt;description&gt;Halfwidth and Fullwidth Forms: &lt;a href=\"http://www.unicode.org/charts/PDF/UFF00.pdf\"&gt;http://www.unicode.org/charts/PDF/UFF00.pdf&lt;/a&gt;&lt;/description&gt;&lt;/item&gt;\n/// &lt;/ul&gt;\n/// &lt;para/&gt;\n/// See: &lt;a href=\"http://en.wikipedia.org/wiki/Latin_characters_in_Unicode\"&gt;http://en.wikipedia.org/wiki/Latin_characters_in_Unicode&lt;/a&gt;\n/// &lt;para/&gt;\n/// For example, '&amp;amp;agrave;' will be replaced by 'a'.\n/// &lt;/summary&gt;\npublic static partial class StringExtensions\n{\n /// &lt;summary&gt;\n /// Converts characters above ASCII to their ASCII equivalents. For example,\n /// accents are removed from accented characters. \n /// &lt;/summary&gt;\n /// &lt;param name=\"input\"&gt; The string of characters to fold &lt;/param&gt;\n /// &lt;param name=\"length\"&gt; The length of the folded return string &lt;/param&gt;\n /// &lt;returns&gt; length of output &lt;/returns&gt;\n public static string FoldToASCII(this string input, int? length = null)\n {\n // See https://gist.github.com/andyraddatz/e6a396fb91856174d4e3f1bf2e10951c\n }\n}\n</code></pre>\n\n<p>Hope that helps someone else, this is the most robust solution I've found!</p>\n" }, { "answer_id": 63729084, "author": "Thomas", "author_id": 42659, "author_profile": "https://Stackoverflow.com/users/42659", "pm_score": 0, "selected": false, "text": "<p>This code worked for me:</p>\n<pre><code>var updatedText = text.Normalize(NormalizationForm.FormD)\n .Where(c =&gt; CharUnicodeInfo.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark)\n .ToArray();\n</code></pre>\n<p><strong>However, please don't do this with names.</strong> It's not only an insult to people with umlauts/accents in their name, it can also be dangerously wrong in certain situations (see below). There are alternative writings instead of just removing the accent.</p>\n<p><strong>Furthermore, it's simply wrong and dangerous</strong>, e.g. if the user has to provide his name exactly how it occurs on the passport.</p>\n<p>For example my name is written <code>Zuberbühler</code> and in the machine readable part of my passport you will find <code>Zuberbuehler</code>. By removing the umlaut, the name will not match with either part. This can lead to issues for the users.</p>\n<p><strong>You should rather disallow umlauts/accent</strong> in an input form <strong>for names</strong> so the user can write his name correctly without its umlaut or accent.</p>\n<p>Practical example, if the web service to apply for ESTA (<a href=\"https://www.application-esta.co.uk/special-characters-and\" rel=\"nofollow noreferrer\">https://www.application-esta.co.uk/special-characters-and</a>) would use above code instead of transforming umlauts correctly, the ESTA application would either be refused or the traveller will have problems with the American Border Control when entering the States.</p>\n<p>Another example would be flight tickets. Assuming you have a flight ticket booking web application, the user provides his name with an accent and your implementation is just removing the accents and then using the airline's web service to book the ticket! Your customer may not be allowed to board since the name does not match to any part of his/her passport.</p>\n" }, { "answer_id": 67190157, "author": "aepot", "author_id": 12888024, "author_profile": "https://Stackoverflow.com/users/12888024", "pm_score": 2, "selected": false, "text": "<p>Same as accepted answer but faster, using <code>Span</code> instead of <code>StringBuilder</code>.<br />\nRequires .NET Core 3.1 or newer .NET.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>static string RemoveDiacritics(string text) \n{\n ReadOnlySpan&lt;char&gt; normalizedString = text.Normalize(NormalizationForm.FormD);\n int i = 0;\n Span&lt;char&gt; span = text.Length &lt; 1000\n ? stackalloc char[text.Length]\n : new char[text.Length];\n\n foreach (char c in normalizedString)\n {\n if (CharUnicodeInfo.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark)\n span[i++] = c;\n }\n\n return new string(span).Normalize(NormalizationForm.FormC);\n}\n</code></pre>\n<p>Also this is extensible for additional character replacements e.g. for polish Ł.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>span[i++] = c switch\n{\n 'Ł' =&gt; 'L',\n 'ł' =&gt; 'l',\n _ =&gt; c\n};\n</code></pre>\n<p>A small note: Stack allocation <code>stackalloc</code> is rather faster than Heap allocation <code>new</code>, and it makes less work for Garbage Collector. <code>1000</code> is a threshold to avoid allocating large structures on Stack which may cause <code>StackOverflowException</code>. While 1000 is a pretty safe value, in most cases 10000 or even 100000 would also work (100k allocates on Stack up to 200kB while default stack size is 1 MB). However 100k looks for me a bit dangerous.</p>\n" }, { "answer_id": 67569854, "author": "cdie", "author_id": 2743315, "author_profile": "https://Stackoverflow.com/users/2743315", "pm_score": 4, "selected": false, "text": "<p>The accepted answer is totally correct, but nowadays, it should be updated to use <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.text.rune?view=net-5.0\" rel=\"noreferrer\">Rune</a> class instead of <code>CharUnicodeInfo</code>, as C# &amp; .NET updated the way to analyse strings in latest versions (Rune class has been added in .NET Core 3.0).</p>\n<p>The following code for .NET 5+ is now recommended, as it go further for non-latin chars :</p>\n<pre><code>static string RemoveDiacritics(string text) \n{\n var normalizedString = text.Normalize(NormalizationForm.FormD);\n var stringBuilder = new StringBuilder();\n\n foreach (var c in normalizedString.EnumerateRunes())\n {\n var unicodeCategory = Rune.GetUnicodeCategory(c);\n if (unicodeCategory != UnicodeCategory.NonSpacingMark)\n {\n stringBuilder.Append(c);\n }\n }\n\n return stringBuilder.ToString().Normalize(NormalizationForm.FormC);\n}\n</code></pre>\n" }, { "answer_id": 72705782, "author": "Joshua Barker", "author_id": 3617346, "author_profile": "https://Stackoverflow.com/users/3617346", "pm_score": 2, "selected": false, "text": "<p>For simply removing French Canadian accent marks as the original question asked, here's an alternate method that uses a regular expression instead of hardcoded conversions and For/Next loops. Depending on your needs, it could be condensed into a single line of code; however, I added it to an extensions class for easier reusability.</p>\n<p><strong>Visual Basic</strong></p>\n<pre><code>Imports System.Text\nImports System.Text.RegularExpressions\n\nPublic MustInherit Class StringExtension\n Public Shared Function RemoveDiacritics(Text As String) As String\n Return New Regex(&quot;\\p{Mn}&quot;, RegexOptions.Compiled).Replace(Text.Normalize(NormalizationForm.FormD), String.Empty)\n End Function\nEnd Class\n</code></pre>\n<p>Implementation</p>\n<pre><code> Private Shared Sub DoStuff()\n MsgBox(StringExtension.RemoveDiacritics(inputString))\n End Sub\n</code></pre>\n<p><strong>c#</strong></p>\n<pre><code>using System.Text;\nusing System.Text.RegularExpressions;\n\nnamespace YourApplication\n{\n public abstract class StringExtension\n {\n public static string RemoveDiacritics(string Text)\n {\n return new Regex(@&quot;\\p{Mn}&quot;, RegexOptions.Compiled).Replace(Text.Normalize(NormalizationForm.FormD), string.Empty);\n }\n }\n}\n</code></pre>\n<p>Implementation</p>\n<pre><code> private static void DoStuff()\n {\n MessageBox.Show(StringExtension.RemoveDiacritics(inputString));\n }\n</code></pre>\n<p><strong>Input</strong>:    <code>äáčďěéíľľňôóřŕšťúůýž ÄÁČĎĚÉÍĽĽŇÔÓŘŔŠŤÚŮÝŽ ÖÜË łŁđĐ ţŢşŞçÇ øı</code></p>\n<p><strong>Output</strong>: <code>aacdeeillnoorrstuuyz AACDEEILLNOORRSTUUYZ OUE łŁđĐ tTsScC øı</code></p>\n<p>I included characters that wouldn't be converted to help visualize what happens when unexpected input is received.</p>\n<p>If you need it to also convert other types of characters such as the Polish ł and Ł, then depending on your needs, consider incorporating <a href=\"https://stackoverflow.com/a/50875725/3617346\">this answer</a> (.NET Core friendly) that uses <code>CodePagesEncodingProvider</code> into your solution.</p>\n" }, { "answer_id": 73414244, "author": "Zoner", "author_id": 5240599, "author_profile": "https://Stackoverflow.com/users/5240599", "pm_score": 0, "selected": false, "text": "<p>For anyone who finds Lucene.Net as an overkill for removing diacritics, I managed to find this small library, that utilize ASCII transliteration for you.</p>\n<p><a href=\"https://github.com/anyascii/anyascii\" rel=\"nofollow noreferrer\">https://github.com/anyascii/anyascii</a></p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249087", "https://Stackoverflow.com", "https://Stackoverflow.com/users/514/" ]
I'm trying to convert some strings that are in French Canadian and basically, I'd like to be able to take out the French accent marks in the letters while keeping the letter. (E.g. convert `é` to `e`, so `crème brûlée` would become `creme brulee`) What is the best method for achieving this?
I've not used this method, but Michael Kaplan describes a method for doing so in his blog post (with a confusing title) that talks about stripping diacritics: [Stripping is an interesting job (aka On the meaning of meaningless, aka All Mn characters are non-spacing, but some are more non-spacing than others)](http://archives.miloush.net/michkap/archive/2007/05/14/2629747.html) ``` static string RemoveDiacritics(string text) { var normalizedString = text.Normalize(NormalizationForm.FormD); var stringBuilder = new StringBuilder(capacity: normalizedString.Length); for (int i = 0; i < normalizedString.Length; i++) { char c = normalizedString[i]; var unicodeCategory = CharUnicodeInfo.GetUnicodeCategory(c); if (unicodeCategory != UnicodeCategory.NonSpacingMark) { stringBuilder.Append(c); } } return stringBuilder .ToString() .Normalize(NormalizationForm.FormC); } ``` Note that this is a followup to his earlier post: [Stripping diacritics....](http://archives.miloush.net/michkap/archive/2005/02/19/376617.html) The approach uses [String.Normalize](https://msdn.microsoft.com/en-us/library/system.string.normalize.aspx) to split the input string into constituent glyphs (basically separating the "base" characters from the diacritics) and then scans the result and retains only the base characters. It's just a little complicated, but really you're looking at a complicated problem. Of course, if you're limiting yourself to French, you could probably get away with the simple table-based approach in [How to remove accents and tilde in a C++ std::string](https://stackoverflow.com/questions/144761/how-to-remove-accents-and-tilde-in-a-c-stdstring), as recommended by @David Dibben.
249,103
<p>So I just love it when my application is working great in Firefox, but then I open it in IE and... Nope, please try again.</p> <p>The issue I'm having is that I'm setting a CSS display property to either <code>none</code> or <code>table-cell</code> with JavaScript.</p> <p>I was initially using <code>display: block</code>, but Firefox was rendering it weird without the <code>table-cell</code> property.</p> <p>I would love to do this without adding a hack in the JavaScript to test for IE. Any suggestions?</p> <p>Thanks.</p>
[ { "answer_id": 249121, "author": "joelhardi", "author_id": 11438, "author_profile": "https://Stackoverflow.com/users/11438", "pm_score": 2, "selected": false, "text": "<p>Well, <a href=\"http://www.quirksmode.org/css/display.html\" rel=\"nofollow noreferrer\">IE7 does not have <code>display: table(-cell/-row)</code></a> so you will have to figure something else out or do browser targeting (which I agree, is bad hack). As a quick fix (I don't know what you're trying to achieve, appearance-wise) you could try <code>display: inline-block</code> and see what it looks like.</p>\n\n<p>Maybe figure out a way to do <code>display: block</code> and solve the problem of \"Firefox rendering it weird\" instead? Can you describe what you mean by the weird rendering exactly?</p>\n" }, { "answer_id": 249232, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 2, "selected": false, "text": "<p>You never need Javascript to test for IE, use <a href=\"http://www.quirksmode.org/css/condcom.html\" rel=\"nofollow noreferrer\">conditional comments</a>.</p>\n\n<p>You might look at the solution <a href=\"http://www.tjkdesign.com/articles/css-layout/no_div_no_float_no_clear_no_hack_no_joke.asp\" rel=\"nofollow noreferrer\">these guys</a> came up with for handling table-like display in IE.</p>\n" }, { "answer_id": 250225, "author": "Herb Caudill", "author_id": 239663, "author_profile": "https://Stackoverflow.com/users/239663", "pm_score": 2, "selected": false, "text": "<p>I've been using CSS for over a decade and I've never had occasion to use display:table-cell, and the only times I ever use conditional comments are to hide advanced effects from IE6. </p>\n\n<p>I suspect that a different approach would solve your problem in an intrinsically cross-browser way. Can you open a separate question that describes the effect you're trying to achieve, and post the HTML and CSS that's currently working in Firefox?</p>\n" }, { "answer_id": 645977, "author": "Jacco", "author_id": 22674, "author_profile": "https://Stackoverflow.com/users/22674", "pm_score": 6, "selected": true, "text": "<p>A good way of solving this setting the <code>display</code> value to <code>''</code>:</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\n&lt;!--\nfunction toggle( elemntId ) {\n if (document.getElementById( elemntId ).style.display != 'none') {\n document.getElementById( elemntId ).style.display = 'none';\n } else {\n document.getElementById( elemntId ).style.display = '';\n }\n return true;\n}\n//--&gt;\n&lt;/script&gt;\n</code></pre>\n\n<p>The empty value causes the style to revert back to it's default value. This solution works across all major browsers.</p>\n" }, { "answer_id": 1235847, "author": "Jonathan Hendler", "author_id": 135043, "author_profile": "https://Stackoverflow.com/users/135043", "pm_score": 3, "selected": false, "text": "<p>I had the same issue and used</p>\n\n<pre><code>*float: left; \n</code></pre>\n\n<p>\"*\" indicates IE only</p>\n" }, { "answer_id": 4963526, "author": "andy magoon", "author_id": 612216, "author_profile": "https://Stackoverflow.com/users/612216", "pm_score": 6, "selected": false, "text": "<p>I've solved this using jQuery:</p>\n\n<pre><code>$(document).ready(function(){\n if ($.browser.msie &amp;&amp; $.browser.version == 7)\n {\n $(\".tablecell\").wrap(\"&lt;td /&gt;\");\n $(\".tablerow\").wrap(\"&lt;tr /&gt;\");\n $(\".table\").wrapInner(\"&lt;table /&gt;\");\n }\n});\n</code></pre>\n\n<p>the above script assumes you have divs using style such as:</p>\n\n<pre><code>&lt;style&gt;\n.table { display: table; }\n.tablerow { display: table-row; }\n.tablecell { display: table-cell; }\n&lt;/style&gt;\n</code></pre>\n" }, { "answer_id": 6988609, "author": "risingfish", "author_id": 884832, "author_profile": "https://Stackoverflow.com/users/884832", "pm_score": 2, "selected": false, "text": "<p>Using inline-block works well for this type of stuff. No, IE 6 and IE 7 technically do not have display: inline-block, but you can replicate the behavior with the following styles:</p>\n\n<pre><code>div.show-ib {\n display: inline-block;\n *zoom: 1;\n *display: inline;\n}\n</code></pre>\n\n<p>The key to this is 'zoom: 1' toggles the 'hasLayout' property on the element which changes the way the browser renders a block level element. The only gotcha with inline block is you cannot have a margin of less than 4px.</p>\n" }, { "answer_id": 12320221, "author": "stack collision with heap", "author_id": 1630242, "author_profile": "https://Stackoverflow.com/users/1630242", "pm_score": 1, "selected": false, "text": "<p>A code example fot the conditional comments that user eyelidlessness, kindly posted</p>\n\n<p>\"[if lt IE 8]\" only works if the browser is IE lower than IE8 because IE8 does it right. With the conditional comments IE7 arranges the DIVs nicely horizontally...\nHTML: </p>\n\n<pre><code> &lt;div class=\"container\"&gt;\n &lt;!--[if lt IE 8 ]&gt;&lt;table&gt;&lt;tr&gt;&lt;![endif]--&gt; \n &lt;!--[if lt IE 8 ]&gt;&lt;td&gt;&lt;![endif]--&gt;\n &lt;div class=\"link\"&gt;&lt;a href=\"en.html\"&gt;English&lt;/a&gt;&lt;/div&gt;\n &lt;!--[if lt IE 8 ]&gt;&lt;/td&gt;&lt;![endif]--&gt;\n &lt;!--[if lt IE 8 ]&gt;&lt;td&gt;&lt;![endif]--&gt;\n &lt;div tabindex=\"0\" class=\"thumb\"&gt;&lt;img src=\"pictures\\pic.jpg\" /&gt;&lt;/div&gt;\n &lt;!--[if lt IE 8 ]&gt;&lt;/td&gt;&lt;![endif]--&gt;\n &lt;!--[if lt IE 8 ]&gt;&lt;td&gt;&lt;![endif]--&gt;\n &lt;div class=\"link\"&gt;&lt;a href=\"de.html\"&gt;Deutsch&lt;/a&gt;&lt;/div&gt;\n &lt;!--[if lt IE 8 ]&gt;&lt;/td&gt;&lt;![endif]--&gt;\n &lt;!--[if lt IE 8 ]&gt;&lt;/tr&gt;&lt;/table&gt;&lt;![endif]--&gt;\n&lt;/div&gt; \n</code></pre>\n\n<p>My CSS </p>\n\n<pre><code>.link {\n display:table-cell;\n vertical-align:middle;\n }\n div.container {\n margin: 0 auto;\n display:table;\n }\n .thumb {\n display:table-cell;\n float: left;\n text-align: center;\n }\n</code></pre>\n\n<p>IE 8 and 9 Work with the CSS as does FireFox. IE7 looks now the same using the Table and TD &amp; TR tags. On some pages IE 8 worked only 20% of the time, so I used [if lt IE 9 ]</p>\n\n<p>This also helps smoothing out vertical-align issues that IE7 can't handle.</p>\n" }, { "answer_id": 14485739, "author": "Mike6679", "author_id": 517733, "author_profile": "https://Stackoverflow.com/users/517733", "pm_score": 0, "selected": false, "text": "<p>I tried everything and the only way I found that was all cross browser was to use Javascript / Jquery. This is a clean lightweight solution: <a href=\"http://www.ddrewdesign.com/blog/jquery-vertical-align-function\" rel=\"nofollow\">click here</a></p>\n" }, { "answer_id": 23745735, "author": "Phill Healey", "author_id": 619792, "author_profile": "https://Stackoverflow.com/users/619792", "pm_score": 0, "selected": false, "text": "<p>IE7 doesn't support <code>display:inline-block;</code> either. An apparent hack is <code>zoom: 1; *display: inline;</code> after your css for <code>display:table-cell;</code></p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249103", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10420/" ]
So I just love it when my application is working great in Firefox, but then I open it in IE and... Nope, please try again. The issue I'm having is that I'm setting a CSS display property to either `none` or `table-cell` with JavaScript. I was initially using `display: block`, but Firefox was rendering it weird without the `table-cell` property. I would love to do this without adding a hack in the JavaScript to test for IE. Any suggestions? Thanks.
A good way of solving this setting the `display` value to `''`: ``` <script type="text/javascript"> <!-- function toggle( elemntId ) { if (document.getElementById( elemntId ).style.display != 'none') { document.getElementById( elemntId ).style.display = 'none'; } else { document.getElementById( elemntId ).style.display = ''; } return true; } //--> </script> ``` The empty value causes the style to revert back to it's default value. This solution works across all major browsers.
249,110
<p>I have a Django model with a large number of fields and 20000+ table rows. To facilitate human readable URLs and the ability to break down the large list into arbitrary sublists, I would like to have a URL that looks like this:</p> <pre><code>/browse/&lt;name1&gt;/&lt;value1&gt;/&lt;name2&gt;/&lt;value2&gt;/ .... etc .... </code></pre> <p>where 'name' maps to a model attribute and 'value' is the search criteria for that attribute. Each "name" will be treated like a category to return subsets of the model instances where the categories match.</p> <p>Now, this could be handled with GET parameters, but I prefer more readable URLs for both the user's sake and the search engines. These URLs subsets will be embedded on each page that displays this model, so it seems worth the effort to make pretty URLs.</p> <p>Ideally each name/value pair will be passed to the view function as a parameter named <code>name1</code>, <code>name2</code>, etc. However, I don't believe it's possible to defined named patterns via a regex's matched text. Am I wrong there?</p> <p>So, it seems I need to do something like this:</p> <pre><code>urlpatterns = patterns('', url(r'^browse/(?:([\w]+)/([\w]+)/)+$', 'app.views.view', name="model_browse"), ) </code></pre> <p>It seems this should match any sets of two name/value pairs. While it matches it successfully, it only passes the last name/value pair as parameters to the view function. My guess is that each match is overwriting the previous match. Under the guess that the containing (?:...)+ is causing it, I tried a simple repeating pattern instead:</p> <pre><code>urlpatterns = patterns('', url(r'^browse/([\w]+/)+$', 'app.views.view', name="model_browse"), ) </code></pre> <p>... and got the same problem, but this time <code>*args</code> only includes the last matched pattern.</p> <p>Is this a limitation of Django's url dispatcher, and/or Python's regex support? It seems either of these methods should work. Is there a way to achieve this without hardcoding each possible model attribute in the URL as an optional (.*) pattern?</p>
[ { "answer_id": 249524, "author": "Adam", "author_id": 30084, "author_profile": "https://Stackoverflow.com/users/30084", "pm_score": 5, "selected": true, "text": "<p>A possibility that you might consider is matching the entire string of possible values within the url pattern portion and pull out the specific pieces within your view. As an example:</p>\n\n<pre><code>urlpatterns = patterns('',\n url(r'^browse/(?P&lt;match&gt;.+)/$', 'app.views.view', name='model_browse'),\n)\n\ndef view(request, match):\n pieces = match.split('/')\n # even indexed pieces are the names, odd are values\n ...\n</code></pre>\n\n<p>No promises about the regexp I used, but I think you understand what I mean.</p>\n\n<p>(Edited to try and fix the regexp.)</p>\n" }, { "answer_id": 251253, "author": "Peter Rowell", "author_id": 17017, "author_profile": "https://Stackoverflow.com/users/17017", "pm_score": 2, "selected": false, "text": "<p>I agree with Adam, but I think the pattern in urls.py should be:</p>\n\n<pre><code>... r'^browse/(?P&lt;match&gt;.+)/$' ...\n</code></pre>\n\n<p>The '\\w' will only match 'word' characters, but the '.' will match anything.</p>\n" }, { "answer_id": 255251, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Same answer came to me while reading the question.</p>\n\n<p>I believe model_browse view is the best way to sort the query parameters and use it as a generic router.</p>\n" }, { "answer_id": 19378600, "author": "Michael", "author_id": 1694500, "author_profile": "https://Stackoverflow.com/users/1694500", "pm_score": 0, "selected": false, "text": "<p>I think the answer of Adam is more generic than my solution, but if you like to use a fixed number of arguments in the url, you could also do something like this:</p>\n\n<p>The following example shows how to get all sales of a day for a location by entering the name of the <code>store</code> and the <code>year</code>, <code>month</code> and <code>day</code>.</p>\n\n<p><strong>urls.py</strong>:</p>\n\n<pre><code>urlpatterns = patterns('',\n url(r'^baseurl/location/(?P&lt;store&gt;.+)/sales/(?P&lt;year&gt;[0-9][0-9][0-9][0-9])-(?P&lt;month&gt;[0-9][0-9])-(?P&lt;day&gt;[0-9][0-9])/$', views.DailySalesAtLocationListAPIView.as_view(), name='daily-sales-at-location'),\n)\n</code></pre>\n\n<p>Alternativly, you could also use the id of the store by changing <code>(?P&lt;store&gt;.+)</code> to <code>(?P&lt;store&gt;[0-9]+)</code>. Note that <code>location</code> and <code>sales</code> are no keywords, they just improve readability of the url.</p>\n\n<p><strong>views.py</strong></p>\n\n<pre><code>class DailySalesAtLocationListAPIView(generics.ListAPIView):\n def get(self, request, store, year, month, day):\n # here you can start using the values from the url\n print store\n print year\n print month\n print date\n\n # now start filtering your model\n</code></pre>\n\n<p>Hope it helps anybody!</p>\n\n<p>Best regards,</p>\n\n<p>Michael</p>\n" }, { "answer_id": 35575143, "author": "softwareplay", "author_id": 2595727, "author_profile": "https://Stackoverflow.com/users/2595727", "pm_score": 1, "selected": false, "text": "<p>I've an alternative solution, which isn't quite different from the previous but it's more refined:</p>\n\n<p><code>url(r'^my_app/(((list\\/)((\\w{1,})\\/(\\w{1,})\\/(\\w{1,3})\\/){1,10})+)$'</code></p>\n\n<p>I've used <a href=\"https://docs.djangoproject.com/en/1.9/topics/http/urls/#example\" rel=\"nofollow\">unnamed url parameters</a> and a repetitive regexp. Not to get the \"is not a valid regular expression: multiple repeat\" i place a word at the beginning of the list.</p>\n\n<p>I'm still working at the view receiving the list. But i think ill' go through the args or kwargs.. Cannot still say it exactly.</p>\n\n<p>My 2 cents</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249110", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32638/" ]
I have a Django model with a large number of fields and 20000+ table rows. To facilitate human readable URLs and the ability to break down the large list into arbitrary sublists, I would like to have a URL that looks like this: ``` /browse/<name1>/<value1>/<name2>/<value2>/ .... etc .... ``` where 'name' maps to a model attribute and 'value' is the search criteria for that attribute. Each "name" will be treated like a category to return subsets of the model instances where the categories match. Now, this could be handled with GET parameters, but I prefer more readable URLs for both the user's sake and the search engines. These URLs subsets will be embedded on each page that displays this model, so it seems worth the effort to make pretty URLs. Ideally each name/value pair will be passed to the view function as a parameter named `name1`, `name2`, etc. However, I don't believe it's possible to defined named patterns via a regex's matched text. Am I wrong there? So, it seems I need to do something like this: ``` urlpatterns = patterns('', url(r'^browse/(?:([\w]+)/([\w]+)/)+$', 'app.views.view', name="model_browse"), ) ``` It seems this should match any sets of two name/value pairs. While it matches it successfully, it only passes the last name/value pair as parameters to the view function. My guess is that each match is overwriting the previous match. Under the guess that the containing (?:...)+ is causing it, I tried a simple repeating pattern instead: ``` urlpatterns = patterns('', url(r'^browse/([\w]+/)+$', 'app.views.view', name="model_browse"), ) ``` ... and got the same problem, but this time `*args` only includes the last matched pattern. Is this a limitation of Django's url dispatcher, and/or Python's regex support? It seems either of these methods should work. Is there a way to achieve this without hardcoding each possible model attribute in the URL as an optional (.\*) pattern?
A possibility that you might consider is matching the entire string of possible values within the url pattern portion and pull out the specific pieces within your view. As an example: ``` urlpatterns = patterns('', url(r'^browse/(?P<match>.+)/$', 'app.views.view', name='model_browse'), ) def view(request, match): pieces = match.split('/') # even indexed pieces are the names, odd are values ... ``` No promises about the regexp I used, but I think you understand what I mean. (Edited to try and fix the regexp.)
249,158
<p>First, a couple operating parameters:</p> <ul> <li>.NET development using Visual Studio 2005/2008</li> <li>TortoiseSVN client</li> </ul> <p>I've only primarily worked with Visual Source Safe and SourceGear Vault source control systems. In each, I map the root of the repository to a local working directory. For example:</p> <pre><code>$/ --&gt; C:\source </code></pre> <p>As long as the local directory exists, I've got my "working copy" (svn) or "working folder" (VSS) set up.</p> <p>To work on a new project that is already in the source code repository I need to "get the latest" (VSS) version of that project's directory.</p> <p>When I go into any child directory in the repository and "Get Latest" (i.e. svn checkout) the client will automatically create the complete directory hierarchy for me, mirroring the structure on my local disk. Thus when I get latest of</p> <pre><code>$/foo/bar/project1 </code></pre> <p>it is created on the drive at</p> <pre><code>C:\source\foo\bar\project1 </code></pre> <p>In subversion, when I check out a directory, I must specify the working copy directory location. If I want to properly mirror my working copy directory structure to match the repository I have to either manually construct every child directory in the path or do a checkout of the repository root to the working copy root, getting everything in the repository.</p> <p><strong>Is there a way to get a repository directory down in the hierarchy such that it will be created in a matching local working copy directory structure without all the manual intervention?</strong></p> <p>This isn't a problem with a small repository, but in most cases, I don't need a large percentage of the source repository. It's imperative that the physical structure is maintained in order for file references to projects and resources not to break. Plus the disk cost of SVN is twice the actual source size given all the working base copies of the files.</p> <p>I'm currently using Tortoise. Is it possible there are other SVN clients that will do what I'm looking for?</p>
[ { "answer_id": 249164, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 2, "selected": false, "text": "<p>The Subversion \"check out\" operation creates a <em>new</em> working copy. What you probably want to do is check out your whole project (which automatically creates the proper directory structure as it is in the repository), then use the Subversion \"update\" operation. The update will update everything in the specified directory and in subdirectories.</p>\n\n<p>This is perhaps due to a difference in terminology between VSS and Subversion. The <a href=\"http://svnbook.red-bean.com\" rel=\"nofollow noreferrer\">Subversion Book</a> is a worthwhile read, particularly the chapter on <a href=\"http://svnbook.red-bean.com/en/1.5/svn.tour.html\" rel=\"nofollow noreferrer\">Basic Usage</a>.</p>\n\n<p>Update: I suppose I'm not quite understanding what your expected use-case is. It sounds like one of the new Subversion 1.5 features you might need is <a href=\"http://subversion.tigris.org/svn_1.5_releasenotes.html#sparse-checkouts\" rel=\"nofollow noreferrer\">sparse checkouts</a>. This lets you selectively fetch a portion of a repository without necessarily getting the whole thing. It's quite flexible in the options it gives you for managing how much you need to get.</p>\n\n<p><strike>Since sparse checkouts are relatively new, I don't think the SVN book has been updated to include information on this feature.</strike> It has been updated, see comments.</p>\n\n<p>Update 2: It sounds like you can construct what you want by checking out the top level of your repository into c:\\source with the --depth=empty option. Then, for each subdirectory that you want, update that subdirectory with --depth=empty or --depth=infinity as appropriate.</p>\n\n<p>I believe that all this is rooted in the Subversion design goal of being able to have multiple independent source trees on your system at the same time. With VSS, $/ is configured globally to refer to a specific directory (c:\\source) so you can only have one checkout (without a bunch of messing around with the global configuration every time you want to switch).</p>\n" }, { "answer_id": 249170, "author": "Peter", "author_id": 5496, "author_profile": "https://Stackoverflow.com/users/5496", "pm_score": 0, "selected": false, "text": "<p>But the whole point of the question is that I would prefer not to get the whole entire repository just to create the directory structure on the initial checkout.</p>\n\n<p>Sorry if I wasn't clear that I am starting from a clean, empty working copy location.</p>\n\n<p>And I have read a good portion of the SVN book. However, it doesn't cover these kinds of questions.</p>\n" }, { "answer_id": 249186, "author": "Hector Sosa Jr", "author_id": 12829, "author_profile": "https://Stackoverflow.com/users/12829", "pm_score": -1, "selected": false, "text": "<p>Not sure why you want to do what you are asking. Most people just create a working local copy, and work on whatever directory they want. That's because of the way Subversion works. It doesn't lock the source code. I started source control by using SourceSafe, so I have a little bit of an idea of what you are going through. </p>\n\n<p>What you probably want is to use the svn:externals property. There are several posts here that talk about this. Here is one of them:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/125468/how-to-make-svn-only-update-files-but-not-add-new-ones\">How to make SVN only update files but not add new ones</a></p>\n" }, { "answer_id": 249190, "author": "Ken Gentle", "author_id": 8709, "author_profile": "https://Stackoverflow.com/users/8709", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://ankhsvn.open.collab.net/\" rel=\"nofollow noreferrer\">ankhsvn</a> (open source) and <a href=\"http://www.visualsvn.com/\" rel=\"nofollow noreferrer\">VisualSVN</a> (commercial) are products integrated with Visual Studio that may better fit your development model.</p>\n" }, { "answer_id": 249208, "author": "icelava", "author_id": 2663, "author_profile": "https://Stackoverflow.com/users/2663", "pm_score": 1, "selected": false, "text": "<ol>\n<li>First browse your Subversion repository using Repo Browser.</li>\n<li>Navigate down the hierarchy to your desired directory; you should end up with a URL showing something like <a href=\"https://subversion:8443/svn/BranchMerge/Branches/TestWeb\" rel=\"nofollow noreferrer\">https://subversion:8443/svn/BranchMerge/Branches/TestWeb</a></li>\n<li>Right click on that directory in the left navigation pane, and choose Checkout...</li>\n<li>Copy (into clipboard) that directory path \"BranchMerge/Branches/TestWeb\" from the URL of repository textbox.</li>\n<li>Paste that into the Checkout directory textbox to mix and match with the existing path it has, so that it shows your desired hierarchy for your local drive. \"C:\\source\\BranchMerge/Branches/TestWeb\"</li>\n<li>When you hit OK, a dialog box should appear to ask to auto-create those missing directories.</li>\n<li>Agree with it, of course.</li>\n</ol>\n" }, { "answer_id": 249651, "author": "Peter Parker", "author_id": 23264, "author_profile": "https://Stackoverflow.com/users/23264", "pm_score": 2, "selected": false, "text": "<p>To answer your bold printed question in short: <strong>NO</strong> there is no way to create all folders above your project location</p>\n\n<p>The reason for this is slightly longer:</p>\n\n<p>You are thinking in a VSS workflow, where you have 1 workingfolder which has a fixed path on your local directory. So all you can do is check out another project which will create the whole directory structure on your local HD inside your workingfolder.</p>\n\n<p>In SVN you have <em>floating</em> workingcopys you can check out a specific location in your repository to any place you want. You even can move your workingcopy to a different place! Your working copy do not need a fixed location on your HD.</p>\n\n<p>So you do not <em>need</em> to recreate the folderstructure above your project. For your project it also should not make any difference. You are much more flexible by using the SVN workflow of <em>floating</em> workingcopys where the absolute path is unimportant. </p>\n\n<p>However, if you feel more comfortable in using your old VSS-based workflow you can checkout using the <code>--sparse-checkout</code> parameter and recreate the structure manually or write a simple batch file doing this. I cannot see any advantage of this and you will surely forget to do so, if you continue to work with SVN and forgot the old rusty VSS-workflow</p>\n" }, { "answer_id": 250669, "author": "Peter", "author_id": 5496, "author_profile": "https://Stackoverflow.com/users/5496", "pm_score": 0, "selected": false, "text": "<p>I'm generally understanding what you all are saying about \"how SVN works\". Perhaps the problem is not that I'm unclear on that, but I'm falling victim to a higher code organizational problem.</p>\n\n<p>The root of the problem comes from project dependencies. I have many applications that have many dependencies. Because of the hierarchical structure of the .NET projects, the dependencies are expected to be in certain physical locations. So if I am going to start to work on this project:</p>\n\n<pre><code>http://mysvn/svn/foo/bar/project1\n</code></pre>\n\n<p>that project would go into </p>\n\n<pre><code>C:\\source\\foo\\bar\\project1\n</code></pre>\n\n<p>Now that project depends on another project. In the .NET project file, the project reference is relatively \"back referenced\":</p>\n\n<pre><code>..\\..\\..\\bar\\foo\\project2\n</code></pre>\n\n<p>so the dependency is expect to be in the local working copy at</p>\n\n<pre><code>C:\\source\\bar\\foo\\project2\n</code></pre>\n\n<p>Thus, the parent directory structure is critical. </p>\n\n<p>I can't store dependent project as children of any one specific application/project because they are shared among many projects. So they live in their own locations outside of one particular project tree. Thus, I do need to ensure that any given project (and its dependencies) are checked out to a specific tree location relative to the root of the source tree in order to ensure that the references to the projects don't break or that they don't differ between developers. Otherwise, each of us continually updates references to make them work creating a lot of noise in the source history and constant breaks between developers. Also, then the build server won't have them in the right place either.</p>\n\n<p>I have yet to find any good information about doing .NET development with SVN. There are plenty of open source projects in .NET that use SVN or CVS. However, those that I have looked at always seem to be in a fairly isolated structure such that all the different projects fall under a single source tree location. This makes it trivial to get everything that is needed because you can simply check out one path recursively and get everything you need.</p>\n\n<p>I'd be very interested to hear from anyone who does enterprise development in .NET using SVN with many shared projects that cross project storage location boundaries.</p>\n\n<p>It is beginning to feel like the only solution that would work in a team is to simply check out the entire repository to ensure the structure is correct and consistent. That is unfortunate for a repository that has many gig of source.</p>\n" }, { "answer_id": 341123, "author": "Jim T", "author_id": 7298, "author_profile": "https://Stackoverflow.com/users/7298", "pm_score": 0, "selected": false, "text": "<p>Ok, first and foremost, the way you're working is like to cause problems, ultimately.</p>\n\n<p>The principle your looking for is that each project should have a trunk/branches/tags structure which is independant of any other project. And that checking out trunk automatically gets all the code, including dependencies, which will be enough to build your project.</p>\n\n<p>You're clearly not in that kind of position, and moving to it will take some effort. However, there is a workaround that you can use to get you going as you want, using externals.</p>\n\n<ol>\n<li>In Repo-browser, create a new tree folder in the root, perhaps \"Projects\".</li>\n<li>In this Projects folder, create a folder for your project \"MyProject\".</li>\n<li>On this folder, right click it and edit the properties, add a new property called \"svn:externals\" - it'll be in the list.</li>\n<li>Use this property to define the tree required for your project.</li>\n<li>Checkout <a href=\"http://svnserver/svn/Projects/MyProject\" rel=\"nofollow noreferrer\">http://svnserver/svn/Projects/MyProject</a> and the whole tree will be retrieved.</li>\n<li>Work as normal.</li>\n</ol>\n\n<p>An example of the svn:externals property might be:</p>\n\n<pre><code>http://mysvn/svn/foo/bar/project1 foo/bar/project1\nhttp://mysvn/svn/bar/foo/project2 bar/foo/project2\n</code></pre>\n\n<p>Although it would be better to use relative references as detailed in the redbook.</p>\n" }, { "answer_id": 1098302, "author": "Peter", "author_id": 5496, "author_profile": "https://Stackoverflow.com/users/5496", "pm_score": 2, "selected": true, "text": "<p>I seemed to have found a suitable solution to my problem.</p>\n\n<p><strong>Using TortoiseSVN, the \"Update item to revision\" action within the repo browser can be used to locally reconstruct the repository's folder structure for an arbitrary repo path.</strong></p>\n\n<p>Detailed steps are:</p>\n\n<ol>\n<li>Create a local folder to be the working copy root of the highest repository folder for which you need to maintain physical folder structure</li>\n<li>Do a shallow checkout of the repository root (checkout, select \"Checkout Depth\" of anything <strong><em>except</em></strong> \"Fully recursive\")</li>\n<li>Launch repo browser from the working copy folder</li>\n<li>Find repo path you want to get</li>\n<li>Right-click on desired folder, choose \"Update item to revision\"</li>\n<li>Leave defaults of HEAD revision and \"Working copy\" update depth, click OK</li>\n</ol>\n\n<p>This will update your working copy with the contents of the chosen repo path including all the parent directories up to the start of the checkout working copy thus mirroring the folder hierarchy of the repository in your working copy.</p>\n\n<p>Notes on the \"Update item to revision\" context menu option:</p>\n\n<ul>\n<li>This option only appears on repository paths that don't already exist in the local working copy</li>\n<li>It looks like leaving the \"Update Depth\" to the default of \"Working Copy\" is fine for getting all contents of the chosen path. (Rather than having to explicitly select \"Fully recursive\".)</li>\n</ul>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249158", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5496/" ]
First, a couple operating parameters: * .NET development using Visual Studio 2005/2008 * TortoiseSVN client I've only primarily worked with Visual Source Safe and SourceGear Vault source control systems. In each, I map the root of the repository to a local working directory. For example: ``` $/ --> C:\source ``` As long as the local directory exists, I've got my "working copy" (svn) or "working folder" (VSS) set up. To work on a new project that is already in the source code repository I need to "get the latest" (VSS) version of that project's directory. When I go into any child directory in the repository and "Get Latest" (i.e. svn checkout) the client will automatically create the complete directory hierarchy for me, mirroring the structure on my local disk. Thus when I get latest of ``` $/foo/bar/project1 ``` it is created on the drive at ``` C:\source\foo\bar\project1 ``` In subversion, when I check out a directory, I must specify the working copy directory location. If I want to properly mirror my working copy directory structure to match the repository I have to either manually construct every child directory in the path or do a checkout of the repository root to the working copy root, getting everything in the repository. **Is there a way to get a repository directory down in the hierarchy such that it will be created in a matching local working copy directory structure without all the manual intervention?** This isn't a problem with a small repository, but in most cases, I don't need a large percentage of the source repository. It's imperative that the physical structure is maintained in order for file references to projects and resources not to break. Plus the disk cost of SVN is twice the actual source size given all the working base copies of the files. I'm currently using Tortoise. Is it possible there are other SVN clients that will do what I'm looking for?
I seemed to have found a suitable solution to my problem. **Using TortoiseSVN, the "Update item to revision" action within the repo browser can be used to locally reconstruct the repository's folder structure for an arbitrary repo path.** Detailed steps are: 1. Create a local folder to be the working copy root of the highest repository folder for which you need to maintain physical folder structure 2. Do a shallow checkout of the repository root (checkout, select "Checkout Depth" of anything ***except*** "Fully recursive") 3. Launch repo browser from the working copy folder 4. Find repo path you want to get 5. Right-click on desired folder, choose "Update item to revision" 6. Leave defaults of HEAD revision and "Working copy" update depth, click OK This will update your working copy with the contents of the chosen repo path including all the parent directories up to the start of the checkout working copy thus mirroring the folder hierarchy of the repository in your working copy. Notes on the "Update item to revision" context menu option: * This option only appears on repository paths that don't already exist in the local working copy * It looks like leaving the "Update Depth" to the default of "Working Copy" is fine for getting all contents of the chosen path. (Rather than having to explicitly select "Fully recursive".)
249,171
<p>I am working on a business problem in C#.NET. I have two classes, named C and W that will be instantiated independently at different times.</p> <p>An object of class C needs to contain references to 0 ... n objects of class W, i.e. a C object can contain up to n W objects.</p> <p>Each W object needs to contain a reference to exactly 1 object of class C, i.e. a W object is contained in one C object.</p> <p>An object of class C is usually instantiated first. At a later point, its W contents are discovered, and instantiated. At this later point, I need to cross reference the C and W objects to each other.</p> <p>What is a good design pattern for this? I actually have cases where I have three or four classes involved but we can talk about two classes to keep it simple.</p> <p>I was thinking of something simple like:</p> <pre><code>class C { public List&lt;W&gt; contentsW; } class W { public C containerC; } </code></pre> <p>This will work for the moment but I can foresee having to write a fair amount of code to keep track of all the references and their validity. I'd like to implement code down the road to do shallow refreshes of just the container and deep refreshes of all referenced classes. Are there any other approaches and what are their advantages?</p> <p>Edit on 11/3: Thanks to all for the good answers and good discussion. I finally chose jop's answer because that came closest to what I wanted to do, but the other answers also helped. Thanks again!</p>
[ { "answer_id": 249180, "author": "Jon Limjap", "author_id": 372, "author_profile": "https://Stackoverflow.com/users/372", "pm_score": 2, "selected": false, "text": "<p>Hmmm, looks like you almost got it, with one minor glitch -- you gotta be able to control the addition to the list within C.</p>\n\n<p>e.g.,</p>\n\n<pre><code>class C\n{\n private List&lt;W&gt; _contentsW;\n\n public List&lt;W&gt; Contents \n {\n get { return _contentsw; }\n }\n\n public void AddToContents(W content);\n {\n content.Container = this;\n _contentsW.Add(content);\n }\n}\n</code></pre>\n\n<p>For checking, you just have to iterate through your list, I think:</p>\n\n<pre><code>foreach (var w in _contentsW)\n{\n if (w.Container != this)\n {\n w.Container = this;\n }\n}\n</code></pre>\n\n<p>Not sure if that's what you need.</p>\n\n<p>Do realize that there may be multiple instances of W that would have the same values but may have different C containers.</p>\n" }, { "answer_id": 249182, "author": "Charlie", "author_id": 18529, "author_profile": "https://Stackoverflow.com/users/18529", "pm_score": 0, "selected": false, "text": "<p>One option for this would be to implement the <a href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.icontainer.aspx\" rel=\"nofollow noreferrer\">IContainer</a> and <a href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.icomponent.aspx\" rel=\"nofollow noreferrer\">IComponent</a> interfaces found under System.ComponentModel. C would be the container, and W the component. The <a href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.componentcollection.aspx\" rel=\"nofollow noreferrer\">ComponentCollection</a> class would then serve as the storage for your W instances, and IComponent.Site would provide the back-link to C.</p>\n" }, { "answer_id": 249187, "author": "Rob", "author_id": 2595, "author_profile": "https://Stackoverflow.com/users/2595", "pm_score": 2, "selected": false, "text": "<p>I generally do it something like this:</p>\n\n<pre><code>class C\n{\n private List&lt;W&gt; _contents = new List&lt;W&gt;();\n public IEnumerable&lt;W&gt; Contents\n {\n get { return _contents; }\n }\n\n public void Add(W item)\n {\n item.C = this;\n _contents.Add(item);\n }\n}\n</code></pre>\n\n<p>Thus, your Contents property is readonly and you add items through your aggregate's method only.</p>\n" }, { "answer_id": 249189, "author": "Keith Nicholas", "author_id": 10431, "author_profile": "https://Stackoverflow.com/users/10431", "pm_score": 1, "selected": false, "text": "<p>Expanding on Jons Answer....</p>\n\n<p>You may need weak references if W isnt supposed to keep C alive.</p>\n\n<p>Also...the add should be more complicated if you want to transfer ownership...</p>\n\n<pre><code>public void AddToContents(W content);\n{ \n if(content.Container!=null) content.Container.RemoveFromContents(content);\n content.Container = this;\n _contentsW.Add(content);\n}\n</code></pre>\n" }, { "answer_id": 249201, "author": "yfeldblum", "author_id": 12349, "author_profile": "https://Stackoverflow.com/users/12349", "pm_score": 0, "selected": false, "text": "<p>This is the pattern I use.</p>\n\n<pre><code>public class Parent {\n public string Name { get; set; }\n public IList&lt;Child&gt; Children { get { return ChildrenBidi; } set { ChildrenBidi.Set(value); } }\n private BidiChildList&lt;Child, Parent&gt; ChildrenBidi { get {\n return BidiChildList.Create(this, p =&gt; p._Children, c =&gt; c._Parent, (c, p) =&gt; c._Parent = p);\n } }\n internal IList&lt;Child&gt; _Children = new List&lt;Child&gt;();\n}\n\npublic class Child {\n public string Name { get; set; }\n public Parent Parent { get { return ParentBidi.Get(); } set { ParentBidi.Set(value); } }\n private BidiParent&lt;Child, Parent&gt; ParentBidi { get {\n return BidiParent.Create(this, p =&gt; p._Children, () =&gt; _Parent, p =&gt; _Parent = p);\n } }\n internal Parent _Parent = null;\n}\n</code></pre>\n\n<p>Obviously, I have classes <code>BidiParent&lt;C, P&gt;</code> and <code>BidiChildList&lt;C, P&gt;</code>, the latter of which implements <code>IList&lt;C&gt;</code>, etc. Behind-the-scenes updates are done through the internal fields, while updates from code which uses this domain model are done through the public properties.</p>\n" }, { "answer_id": 249202, "author": "jop", "author_id": 11830, "author_profile": "https://Stackoverflow.com/users/11830", "pm_score": 4, "selected": true, "text": "<p>If you have the Martin Fowler's Refactoring book, just follow the \"Change Unidirectional Association to Bidirectional\" refactoring.</p>\n\n<p>In case you don't have it, here's how your classes will look like after the refactoring:</p>\n\n<pre><code>class C\n{\n // Don't to expose this publicly so that \n // no one can get behind your back and change \n // anything\n private List&lt;W&gt; contentsW; \n\n public void Add(W theW)\n {\n theW.Container = this;\n }\n\n public void Remove(W theW)\n {\n theW.Container = null;\n }\n\n #region Only to be used by W\n internal void RemoveW(W theW)\n {\n // do nothing if C does not contain W\n if (!contentsW.Contains(theW))\n return; // or throw an exception if you consider this illegal\n contentsW.Remove(theW);\n }\n\n internal void AddW(W theW)\n {\n if (!contentW.Contains(theW))\n contentsW.Add(theW);\n }\n #endregion\n}\n\nclass W\n{\n private C containerC;\n\n public Container Container\n {\n get { return containerC; }\n set \n { \n if (containerC != null)\n containerC.RemoveW(this);\n containerC = value; \n if (containerC != null)\n containerC.AddW(this);\n }\n }\n}\n</code></pre>\n\n<p>Take note that I've made the <code>List&lt;W&gt;</code> private. Expose the list of Ws via an enumerator instead of exposing the list directly.</p>\n\n<p>e.g. public List GetWs() { return this.ContentW.ToList(); }</p>\n\n<p>The code above handles transfer of ownership properly. Say you have two instances of C -- C1 and C2 - and the instances of W -- W1 and W2.</p>\n\n<pre><code>W1.Container = C1;\nW2.Container = C2;\n</code></pre>\n\n<p>In the code above, C1 contains W1 and C2 contains W2. If you reassign W2 to C1</p>\n\n<pre><code>W2.Container = C1;\n</code></pre>\n\n<p>Then C2 will have zero items and C1 will have two items - W1 and W2. You can have a floating W</p>\n\n<pre><code>W2.Container = null;\n</code></pre>\n\n<p>In this case, W2 will be removed from C1's list and it will have no container. You can also use the Add and Remove methods from C to manipulate W's containers - so C1.Add(W2) will automatically remove W2 from it's original container and add it to the new one.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249171", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18542/" ]
I am working on a business problem in C#.NET. I have two classes, named C and W that will be instantiated independently at different times. An object of class C needs to contain references to 0 ... n objects of class W, i.e. a C object can contain up to n W objects. Each W object needs to contain a reference to exactly 1 object of class C, i.e. a W object is contained in one C object. An object of class C is usually instantiated first. At a later point, its W contents are discovered, and instantiated. At this later point, I need to cross reference the C and W objects to each other. What is a good design pattern for this? I actually have cases where I have three or four classes involved but we can talk about two classes to keep it simple. I was thinking of something simple like: ``` class C { public List<W> contentsW; } class W { public C containerC; } ``` This will work for the moment but I can foresee having to write a fair amount of code to keep track of all the references and their validity. I'd like to implement code down the road to do shallow refreshes of just the container and deep refreshes of all referenced classes. Are there any other approaches and what are their advantages? Edit on 11/3: Thanks to all for the good answers and good discussion. I finally chose jop's answer because that came closest to what I wanted to do, but the other answers also helped. Thanks again!
If you have the Martin Fowler's Refactoring book, just follow the "Change Unidirectional Association to Bidirectional" refactoring. In case you don't have it, here's how your classes will look like after the refactoring: ``` class C { // Don't to expose this publicly so that // no one can get behind your back and change // anything private List<W> contentsW; public void Add(W theW) { theW.Container = this; } public void Remove(W theW) { theW.Container = null; } #region Only to be used by W internal void RemoveW(W theW) { // do nothing if C does not contain W if (!contentsW.Contains(theW)) return; // or throw an exception if you consider this illegal contentsW.Remove(theW); } internal void AddW(W theW) { if (!contentW.Contains(theW)) contentsW.Add(theW); } #endregion } class W { private C containerC; public Container Container { get { return containerC; } set { if (containerC != null) containerC.RemoveW(this); containerC = value; if (containerC != null) containerC.AddW(this); } } } ``` Take note that I've made the `List<W>` private. Expose the list of Ws via an enumerator instead of exposing the list directly. e.g. public List GetWs() { return this.ContentW.ToList(); } The code above handles transfer of ownership properly. Say you have two instances of C -- C1 and C2 - and the instances of W -- W1 and W2. ``` W1.Container = C1; W2.Container = C2; ``` In the code above, C1 contains W1 and C2 contains W2. If you reassign W2 to C1 ``` W2.Container = C1; ``` Then C2 will have zero items and C1 will have two items - W1 and W2. You can have a floating W ``` W2.Container = null; ``` In this case, W2 will be removed from C1's list and it will have no container. You can also use the Add and Remove methods from C to manipulate W's containers - so C1.Add(W2) will automatically remove W2 from it's original container and add it to the new one.
249,188
<p>What's the most elegant way of implementing a DropDownList in <code>ASP.NET</code> that is editable without using 3rd party components.</p> <p>As a last resort I will probably try using a <code>TextBox</code> with an <code>AutoCompleteExtender</code> with an image to 'drop down' the list; or a <code>TextBox</code> overlapping a HTML Select with some JavaScript to fill values from the Select to the <code>TextBox</code>. But I'm really hoping there is a more terse and maintainable solution.</p> <p>Thanks in advance.</p>
[ { "answer_id": 1592106, "author": "Ray", "author_id": 4872, "author_profile": "https://Stackoverflow.com/users/4872", "pm_score": 3, "selected": false, "text": "<h2>One Control on a Page</h2>\n\n<p>You can follow <a href=\"http://www.codeproject.com/KB/aspnet/EditableDropdown_aspx.aspx\" rel=\"nofollow noreferrer\"><strike>this simple example for an Editable DropDownlist on Code Project</strike></a> that uses standard ASP.NET TextBox and DropDownList controls combined with some JavaScript.</p>\n\n<p>However, the code did not work for me until I added a reference to get the ClientID values for the TextBox and DropDownList:</p>\n\n<pre><code>&lt;script language=\"javascript\" type=\"text/javascript\"&gt;\n\nfunction DisplayText()\n{\n var textboxId = '&lt;% = txtDisplay.ClientID %&gt;';\n var comboBoxId = '&lt;% = ddSelect.ClientID %&gt;';\n document.getElementById(textboxId).value = document.getElementById(comboBoxId).value;\n document.getElementById(textboxId).focus();\n}\n&lt;/script&gt; \n\n&lt;asp:TextBox style=\"width:120px;position:absolute\" ID=\"txtDisplay\" runat=\"server\"&gt;&lt;/asp:TextBox&gt;\n\n&lt;asp:DropDownList ID=\"ddSelect\" style=\"width:140px\" runat=\"server\"&gt; \n &lt;asp:ListItem Value=\"test1\" &gt;test1&lt;/asp:ListItem&gt; \n &lt;asp:ListItem Value=\"test2\"&gt;test2&lt;/asp:ListItem&gt; \n&lt;/asp:DropDownList&gt;\n</code></pre>\n\n<p>Finally, in the code behind just like in the original example, I added the following to page load:</p>\n\n<pre><code>protected void Page_Load(object sender, EventArgs e)\n{\n ddSelect.Attributes.Add(\"onChange\", \"DisplayText();\");\n}\n</code></pre>\n\n<p><br/></p>\n\n<h2>Multiple Controls on a Page</h2>\n\n<p>I placed all of the above code in its own ASCX User Control to make it reusable across my project. However, the code as presented above only works if you require just one editable DropDownList on a given page. </p>\n\n<p>If you need to support multiple custom DropDownList controls on a single page, it is necessary to set the JavaScript function name to be unique to avoid conflicts. Do this by once again using the ClientID:</p>\n\n<p><em>in the ASCX file:</em></p>\n\n<pre><code>function DisplayText_&lt;% = ClientID %&gt;(){...}\n</code></pre>\n\n<p><em>in the code behind:</em></p>\n\n<pre><code>/// ...\nddSelect.Attributes.Add(\"onChange\", \"DisplayText_\" + ClientID + \"();\");\n///..\n</code></pre>\n\n<p>This is one way to avoid using 3rd party controls.</p>\n" }, { "answer_id": 4961218, "author": "Carlos", "author_id": 611897, "author_profile": "https://Stackoverflow.com/users/611897", "pm_score": 1, "selected": false, "text": "<p>The 2 solution here did the trick for me. so koodos for Ray.</p>\n\n<p>Also you should look into the <a href=\"http://ajaxcontroltoolkit.codeplex.com/releases/view/43475\" rel=\"nofollow\">http://ajaxcontroltoolkit.codeplex.com/releases/view/43475</a>, which is the ajaxcontroltoolkit.</p>\n\n<p>I don't believe the version for framework 4 comes with a comboBox component, which is here: <a href=\"http://www.asp.net/AJAX/AjaxControlToolkit/Samples/ComboBox/ComboBox.aspx\" rel=\"nofollow\">http://www.asp.net/AJAX/AjaxControlToolkit/Samples/ComboBox/ComboBox.aspx</a> and is very cool. Specially if you set it like this:</p>\n\n<pre><code>ajaxToolkit:ComboBox ID=ComboBox1 runat=server AutoPostBack=False \n DropDownStyle=DropDown AutoCompleteMode=Suggest \n CaseSensitive=False ItemInsertLocation=\"OrdinalText\" \n</code></pre>\n" }, { "answer_id": 42574573, "author": "ArthurG", "author_id": 5915783, "author_profile": "https://Stackoverflow.com/users/5915783", "pm_score": 2, "selected": false, "text": "<p>You can try using JqueryUI Autocomplete Combobox.<br />\nIt will let you type in text as well as select the item of your choice from a dropdown.<br />\nAs an extra feature it lets you use the autocomplete feature to get a enhance UI experience.<br /></p>\n\n<p>I am attaching a demo which is coupled with bootstrap 3.3.4</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-html lang-html prettyprint-override\"><code>&lt;!DOCTYPE html&gt;\r\n\r\n&lt;html xmlns=\"http://www.w3.org/1999/xhtml\"&gt;\r\n\r\n&lt;head runat=\"server\"&gt;\r\n &lt;title&gt;&lt;/title&gt;\r\n &lt;script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js\"&gt;&lt;/script&gt;\r\n\r\n &lt;script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js\"&gt;&lt;/script&gt;\r\n &lt;link href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css\" rel=\"stylesheet\" /&gt;\r\n &lt;link href=\"https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css\" rel=\"stylesheet\" /&gt;\r\n\r\n &lt;script src=\"https://code.jquery.com/jquery-1.10.2.js\"&gt;&lt;/script&gt;\r\n &lt;script src=\"https://code.jquery.com/ui/1.11.4/jquery-ui.js\"&gt;&lt;/script&gt;\r\n &lt;link href=\"https://jqueryui.com/resources/demos/style.css\" rel=\"stylesheet\" /&gt;\r\n &lt;style&gt;\r\n .custom-combobox {\r\n position: relative;\r\n display: inline-block;\r\n }\r\n .custom-combobox-toggle {\r\n position: absolute;\r\n top: 0;\r\n bottom: 0;\r\n margin-left: -1px;\r\n padding: 0;\r\n }\r\n .custom-combobox-input {\r\n margin: 0;\r\n padding: 5px 10px;\r\n }\r\n .ui-state-default,\r\n .ui-widget-content .ui-state-default,\r\n .ui-widget-header .ui-state-default {\r\n border: 1px solid #421D1D;\r\n background: #ffffff url(\"images/ui-bg_glass_75_e6e6e6_1x400.png\") 50% 50% repeat-x !important;\r\n font-weight: normal;\r\n color: #555555;\r\n }\r\n /* Corner radius */\r\n .ui-corner-all,\r\n .ui-corner-top,\r\n .ui-corner-left,\r\n .ui-corner-tl {\r\n border-top-left-radius: 0px !important;\r\n }\r\n .ui-corner-all,\r\n .ui-corner-top,\r\n .ui-corner-right,\r\n .ui-corner-tr {\r\n border-top-right-radius: 0px !important;\r\n }\r\n .ui-corner-all,\r\n .ui-corner-bottom,\r\n .ui-corner-left,\r\n .ui-corner-bl {\r\n border-bottom-left-radius: 0px !important;\r\n }\r\n .ui-corner-all,\r\n .ui-corner-bottom,\r\n .ui-corner-right,\r\n .ui-corner-br {\r\n border-bottom-right-radius: 0px !important;\r\n }\r\n &lt;/style&gt;\r\n &lt;script&gt;\r\n (function($) {\r\n $.widget(\"custom.combobox\", {\r\n _create: function() {\r\n this.wrapper = $(\"&lt;span&gt;\")\r\n .addClass(\"custom-combobox\")\r\n .insertAfter(this.element);\r\n\r\n this.element.hide();\r\n this._createAutocomplete();\r\n this._createShowAllButton();\r\n },\r\n\r\n _createAutocomplete: function() {\r\n var selected = this.element.children(\":selected\"),\r\n value = selected.val() ? selected.text() : \"\";\r\n\r\n this.input = $(\"&lt;input&gt;\")\r\n .appendTo(this.wrapper)\r\n .val(value)\r\n .attr(\"title\", \"\")\r\n .addClass(\"custom-combobox-input ui-widget ui-widget-content ui-state-default ui-corner-left\")\r\n .autocomplete({\r\n delay: 0,\r\n minLength: 0,\r\n source: $.proxy(this, \"_source\")\r\n })\r\n .tooltip({\r\n tooltipClass: \"ui-state-highlight\"\r\n });\r\n\r\n this._on(this.input, {\r\n autocompleteselect: function(event, ui) {\r\n ui.item.option.selected = true;\r\n this._trigger(\"select\", event, {\r\n item: ui.item.option\r\n });\r\n },\r\n\r\n autocompletechange: \"_removeIfInvalid\"\r\n });\r\n },\r\n\r\n _createShowAllButton: function() {\r\n var input = this.input,\r\n wasOpen = false;\r\n\r\n $(\"&lt;a&gt;\")\r\n .attr(\"tabIndex\", -1)\r\n .attr(\"title\", \"Show All Items\")\r\n .tooltip()\r\n .appendTo(this.wrapper)\r\n .button({\r\n icons: {\r\n primary: \"ui-icon-triangle-1-s\"\r\n\r\n },\r\n text: false\r\n })\r\n .removeClass(\"ui-corner-all\")\r\n .addClass(\"custom-combobox-toggle ui-corner-right\")\r\n .mousedown(function() {\r\n wasOpen = input.autocomplete(\"widget\").is(\":visible\");\r\n })\r\n .click(function() {\r\n input.focus();\r\n\r\n // Close if already visible\r\n if (wasOpen) {\r\n return;\r\n }\r\n\r\n // Pass empty string as value to search for, displaying all results\r\n input.autocomplete(\"search\", \"\");\r\n });\r\n },\r\n\r\n _source: function(request, response) {\r\n var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), \"i\");\r\n response(this.element.children(\"option\").map(function() {\r\n var text = $(this).text();\r\n if (this.value &amp;&amp; (!request.term || matcher.test(text)))\r\n return {\r\n label: text,\r\n value: text,\r\n option: this\r\n };\r\n }));\r\n },\r\n\r\n _removeIfInvalid: function(event, ui) {\r\n\r\n // Selected an item, nothing to do\r\n if (ui.item) {\r\n return;\r\n }\r\n\r\n // Search for a match (case-insensitive)\r\n var value = this.input.val(),\r\n valueLowerCase = value.toLowerCase(),\r\n valid = false;\r\n this.element.children(\"option\").each(function() {\r\n if ($(this).text().toLowerCase() === valueLowerCase) {\r\n this.selected = valid = true;\r\n return false;\r\n }\r\n });\r\n\r\n // Found a match, nothing to do\r\n if (valid) {\r\n return;\r\n }\r\n\r\n // Remove invalid value\r\n this.input\r\n .val(\"\")\r\n .attr(\"title\", value + \" didn't match any item\")\r\n .tooltip(\"open\");\r\n this.element.val(\"\");\r\n this._delay(function() {\r\n this.input.tooltip(\"close\").attr(\"title\", \"\");\r\n }, 2500);\r\n this.input.autocomplete(\"instance\").term = \"\";\r\n },\r\n\r\n _destroy: function() {\r\n this.wrapper.remove();\r\n this.element.show();\r\n }\r\n });\r\n })(jQuery);\r\n\r\n $(function() {\r\n $(\"#combobox\").combobox();\r\n $(\"#toggle\").click(function() {\r\n $(\"#combobox\").toggle();\r\n });\r\n });\r\n &lt;/script&gt;\r\n&lt;/head&gt;\r\n\r\n&lt;body&gt;\r\n &lt;form id=\"form1\" runat=\"server\"&gt;\r\n &lt;div&gt;\r\n &lt;div class=\"ui-widget\"&gt;\r\n &lt;select id=\"combobox\" class=\"form-control\"&gt;\r\n &lt;option value=\"\"&gt;Select your option&lt;/option&gt;\r\n &lt;option value=\"Apple\"&gt;Apple&lt;/option&gt;\r\n &lt;option value=\"Banana\"&gt;Banana&lt;/option&gt;\r\n &lt;option value=\"Cherry\"&gt;Cherry&lt;/option&gt;\r\n &lt;option value=\"Date\"&gt;Date&lt;/option&gt;\r\n &lt;option value=\"Fig\"&gt;Fig&lt;/option&gt;\r\n &lt;option value=\"Grape\"&gt;Grape&lt;/option&gt;\r\n &lt;option value=\"Kiwi\"&gt;Kiwi&lt;/option&gt;\r\n &lt;option value=\"Mango\"&gt;Mango&lt;/option&gt;\r\n &lt;option value=\"Orange\"&gt;Orange&lt;/option&gt;\r\n &lt;option value=\"Pumpkin\"&gt;Pumpkin&lt;/option&gt;\r\n &lt;option value=\"Strawberry\"&gt;Strawberry&lt;/option&gt;\r\n &lt;option value=\"Tomato\"&gt;Tomato&lt;/option&gt;\r\n &lt;option value=\"Watermelon\"&gt;Watermelon&lt;/option&gt;\r\n &lt;/select&gt;\r\n &lt;/div&gt;\r\n\r\n &lt;/div&gt;\r\n &lt;/form&gt;\r\n&lt;/body&gt;\r\n\r\n&lt;/html&gt;</code></pre>\r\n</div>\r\n</div>\r\n\nI have tested this code on all the below settings\nTesting Environment:<br/>\nChrome Browser Version 43.0.2334.0 dev-m (64-bit)<br/>\nInternet Explorer 11<br/>\nFirefox 36.0.1<br/>\nVisual Studio 2013 edition</p>\n\n<p>Hope this solves your issue.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249188", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8280/" ]
What's the most elegant way of implementing a DropDownList in `ASP.NET` that is editable without using 3rd party components. As a last resort I will probably try using a `TextBox` with an `AutoCompleteExtender` with an image to 'drop down' the list; or a `TextBox` overlapping a HTML Select with some JavaScript to fill values from the Select to the `TextBox`. But I'm really hoping there is a more terse and maintainable solution. Thanks in advance.
One Control on a Page --------------------- You can follow [this simple example for an Editable DropDownlist on Code Project](http://www.codeproject.com/KB/aspnet/EditableDropdown_aspx.aspx) that uses standard ASP.NET TextBox and DropDownList controls combined with some JavaScript. However, the code did not work for me until I added a reference to get the ClientID values for the TextBox and DropDownList: ``` <script language="javascript" type="text/javascript"> function DisplayText() { var textboxId = '<% = txtDisplay.ClientID %>'; var comboBoxId = '<% = ddSelect.ClientID %>'; document.getElementById(textboxId).value = document.getElementById(comboBoxId).value; document.getElementById(textboxId).focus(); } </script> <asp:TextBox style="width:120px;position:absolute" ID="txtDisplay" runat="server"></asp:TextBox> <asp:DropDownList ID="ddSelect" style="width:140px" runat="server"> <asp:ListItem Value="test1" >test1</asp:ListItem> <asp:ListItem Value="test2">test2</asp:ListItem> </asp:DropDownList> ``` Finally, in the code behind just like in the original example, I added the following to page load: ``` protected void Page_Load(object sender, EventArgs e) { ddSelect.Attributes.Add("onChange", "DisplayText();"); } ``` Multiple Controls on a Page --------------------------- I placed all of the above code in its own ASCX User Control to make it reusable across my project. However, the code as presented above only works if you require just one editable DropDownList on a given page. If you need to support multiple custom DropDownList controls on a single page, it is necessary to set the JavaScript function name to be unique to avoid conflicts. Do this by once again using the ClientID: *in the ASCX file:* ``` function DisplayText_<% = ClientID %>(){...} ``` *in the code behind:* ``` /// ... ddSelect.Attributes.Add("onChange", "DisplayText_" + ClientID + "();"); ///.. ``` This is one way to avoid using 3rd party controls.
249,222
<p>I'm a fan of extension methods in C#, but haven't had any success adding an extension method to a static class, such as <code>Console</code>.</p> <p>For example, if I want to add an extension to <code>Console</code>, called '<code>WriteBlueLine</code>', so that I can go:</p> <pre><code>Console.WriteBlueLine(&quot;This text is blue&quot;); </code></pre> <p>I tried this by adding a local, public static method, with <code>Console</code> as a '<code>this</code>' parameter... but no dice!</p> <pre><code>public static class Helpers { public static void WriteBlueLine(this Console c, string text) { Console.ForegroundColor = ConsoleColor.Blue; Console.WriteLine(text); Console.ResetColor(); } } </code></pre> <p>This didn't add a '<code>WriteBlueLine</code>' method to <code>Console</code>... am I doing it wrong? Or asking for the impossible?</p>
[ { "answer_id": 249234, "author": "Brannon", "author_id": 5745, "author_profile": "https://Stackoverflow.com/users/5745", "pm_score": 3, "selected": false, "text": "<p>You can't add <em>static</em> methods to a type. You can only add (pseudo-)instance methods to an instance of a type.</p>\n\n<p>The point of the <code>this</code> modifier is to tell the C# compiler to pass the instance on the left-side of the <code>.</code> as the first parameter of the static/extension method.</p>\n\n<p>In the case of adding static methods to a type, there is no instance to pass for the first parameter.</p>\n" }, { "answer_id": 309399, "author": "Robert S.", "author_id": 7565, "author_profile": "https://Stackoverflow.com/users/7565", "pm_score": 3, "selected": false, "text": "<p>I tried to do this with System.Environment back when I was learning extension methods and was not successful. The reason is, as others mention, because extension methods require an instance of the class.</p>\n" }, { "answer_id": 309411, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>Nope. Extension method definitions require an instance of the type you're extending. It's unfortunate; I'm not sure why it's required...</p>\n" }, { "answer_id": 309414, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 9, "selected": true, "text": "<p>No. Extension methods require an instance variable (value) for an object. You can however, write a static wrapper around the <code>ConfigurationManager</code> interface. If you implement the wrapper, you don't need an extension method since you can just add the method directly.</p>\n\n<pre><code> public static class ConfigurationManagerWrapper\n {\n public static ConfigurationSection GetSection( string name )\n {\n return ConfigurationManager.GetSection( name );\n }\n\n .....\n\n public static ConfigurationSection GetWidgetSection()\n {\n return GetSection( \"widgets\" );\n }\n }\n</code></pre>\n" }, { "answer_id": 435617, "author": "Tom Deloford", "author_id": 53541, "author_profile": "https://Stackoverflow.com/users/53541", "pm_score": 6, "selected": false, "text": "<p>It's not possible.</p>\n<p>And yes, I think MS made a mistake here.</p>\n<p>Their decision does not make sense and forces programmers to write (as described above) a pointless wrapper class.</p>\n<p>Here is a good example: Trying to extend static MS Unit testing class Assert: I want 1 more Assert method <code>AreEqual(x1,x2)</code>.</p>\n<p>The only way to do this is to point to different classes or write a wrapper around 100s of different Assert methods. <strong>Why!?</strong></p>\n<p>If the decision was being made to allow extensions of instances, I see no logical reason to not allow static extensions. The arguments about sectioning libraries does not stand up once instances can be extended.</p>\n" }, { "answer_id": 2018165, "author": "Pag Sun", "author_id": 161849, "author_profile": "https://Stackoverflow.com/users/161849", "pm_score": 4, "selected": false, "text": "<p>Maybe you could add a static class with your custom namespace and the same class name:</p>\n\n<pre><code>using CLRConsole = System.Console;\n\nnamespace ExtensionMethodsDemo\n{\n public static class Console\n {\n public static void WriteLine(string value)\n {\n CLRConsole.WriteLine(value);\n }\n\n public static void WriteBlueLine(string value)\n {\n System.ConsoleColor currentColor = CLRConsole.ForegroundColor;\n\n CLRConsole.ForegroundColor = System.ConsoleColor.Blue;\n CLRConsole.WriteLine(value);\n\n CLRConsole.ForegroundColor = currentColor;\n }\n\n public static System.ConsoleKeyInfo ReadKey(bool intercept)\n {\n return CLRConsole.ReadKey(intercept);\n }\n }\n class Program\n {\n static void Main(string[] args)\n {\n try\n {\n Console.WriteBlueLine(\"This text is blue\"); \n }\n catch (System.Exception ex)\n {\n Console.WriteLine(ex.Message);\n Console.WriteLine(ex.StackTrace);\n }\n\n Console.WriteLine(\"Press any key to continue...\");\n Console.ReadKey(true);\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 3718699, "author": "Tenaka", "author_id": 448533, "author_profile": "https://Stackoverflow.com/users/448533", "pm_score": -1, "selected": false, "text": "<p>You CAN do this if you are willing to \"frig\" it a little by making a variable of the static class and assigning it to null. However, this method would not be available to static calls on the class, so not sure how much use it would be:</p>\n\n<pre><code>Console myConsole = null;\nmyConsole.WriteBlueLine(\"my blue line\");\n\npublic static class Helpers {\n public static void WriteBlueLine(this Console c, string text)\n {\n Console.ForegroundColor = ConsoleColor.Blue;\n Console.WriteLine(text);\n Console.ResetColor();\n }\n}\n</code></pre>\n" }, { "answer_id": 5451709, "author": "Mr. Obnoxious", "author_id": 679260, "author_profile": "https://Stackoverflow.com/users/679260", "pm_score": 7, "selected": false, "text": "<p>Can you add static extensions to classes in C#? No but you can do this:</p>\n\n<pre><code>public static class Extensions\n{\n public static T Create&lt;T&gt;(this T @this)\n where T : class, new()\n {\n return Utility&lt;T&gt;.Create();\n }\n}\n\npublic static class Utility&lt;T&gt;\n where T : class, new()\n{\n static Utility()\n {\n Create = Expression.Lambda&lt;Func&lt;T&gt;&gt;(Expression.New(typeof(T).GetConstructor(Type.EmptyTypes))).Compile();\n }\n public static Func&lt;T&gt; Create { get; private set; }\n}\n</code></pre>\n\n<p>Here's how it works. While you can't technically write static extension methods, instead this code exploits a loophole in extension methods. That loophole being that you can call extension methods on null objects without getting the null exception (unless you access anything via @this).</p>\n\n<p>So here's how you would use this:</p>\n\n<pre><code> var ds1 = (null as DataSet).Create(); // as oppose to DataSet.Create()\n // or\n DataSet ds2 = null;\n ds2 = ds2.Create();\n\n // using some of the techniques above you could have this:\n (null as Console).WriteBlueLine(...); // as oppose to Console.WriteBlueLine(...)\n</code></pre>\n\n<p>Now WHY did I pick calling the default constructor as an example, and AND why don't I just return new T() in the first code snippet without doing all of that Expression garbage?\nWell todays your lucky day because you get a 2fer. As any advanced .NET developer knows, new T() is slow because it generates a call to System.Activator which uses reflection to get the default constructor before calling it. Damn you Microsoft!\nHowever my code calls the default constructor of the object directly.</p>\n\n<p>Static extensions would be better than this but desperate times call for desperate measures.</p>\n" }, { "answer_id": 8825516, "author": "Brian Griffin", "author_id": 1143998, "author_profile": "https://Stackoverflow.com/users/1143998", "pm_score": 3, "selected": false, "text": "<p>As for extension methods, extension methods themselves are static; but they are invoked as if they are instance methods. Since a static class is not instantiable, you would never have an instance of the class to invoke an extension method from. For this reason the compiler does not allow extension methods to be defined for static classes.</p>\n\n<p>Mr. Obnoxious wrote: \"As any advanced .NET developer knows, new T() is slow because it generates a call to System.Activator which uses reflection to get the default constructor before calling it\".</p>\n\n<p>New() is compiled to the IL \"newobj\" instruction if the type is known at compile time. Newobj takes a constructor for direct invocation. Calls to System.Activator.CreateInstance() compile to the IL \"call\" instruction to invoke System.Activator.CreateInstance(). New() when used against generic types will result in a call to System.Activator.CreateInstance(). The post by Mr. Obnoxious was unclear on this point... and well, obnoxious. </p>\n\n<p>This code:</p>\n\n<pre><code>System.Collections.ArrayList _al = new System.Collections.ArrayList();\nSystem.Collections.ArrayList _al2 = (System.Collections.ArrayList)System.Activator.CreateInstance(typeof(System.Collections.ArrayList));\n</code></pre>\n\n<p>produces this IL:</p>\n\n<pre><code> .locals init ([0] class [mscorlib]System.Collections.ArrayList _al,\n [1] class [mscorlib]System.Collections.ArrayList _al2)\n IL_0001: newobj instance void [mscorlib]System.Collections.ArrayList::.ctor()\n IL_0006: stloc.0\n IL_0007: ldtoken [mscorlib]System.Collections.ArrayList\n IL_000c: call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle)\n IL_0011: call object [mscorlib]System.Activator::CreateInstance(class [mscorlib]System.Type)\n IL_0016: castclass [mscorlib]System.Collections.ArrayList\n IL_001b: stloc.1\n</code></pre>\n" }, { "answer_id": 26831158, "author": "Black Dog", "author_id": 4232349, "author_profile": "https://Stackoverflow.com/users/4232349", "pm_score": 1, "selected": false, "text": "<p>yes, in a limited sense. </p>\n\n<pre><code>public class DataSet : System.Data.DataSet\n{\n public static void SpecialMethod() { }\n}\n</code></pre>\n\n<p>This works but Console doesn't because it's static.</p>\n\n<pre><code>public static class Console\n{ \n public static void WriteLine(String x)\n { System.Console.WriteLine(x); }\n\n public static void WriteBlueLine(String x)\n {\n System.Console.ForegroundColor = ConsoleColor.Blue;\n System.Console.Write(.x); \n }\n}\n</code></pre>\n\n<p>This works because as long as it's not on the same namespace. The problem is that you have to write a proxy static method for every method that System.Console have. It's not necessarily a bad thing as you can add something like this:</p>\n\n<pre><code> public static void WriteLine(String x)\n { System.Console.WriteLine(x.Replace(\"Fck\",\"****\")); }\n</code></pre>\n\n<p>or</p>\n\n<pre><code> public static void WriteLine(String x)\n {\n System.Console.ForegroundColor = ConsoleColor.Blue;\n System.Console.WriteLine(x); \n }\n</code></pre>\n\n<p>The way it works is that you hook something into the standard WriteLine. It could be a line count or bad word filter or whatever. Whenever you just specify Console in your namespace say WebProject1 and import the namespace System, WebProject1.Console will be chosen over System.Console as default for those classes in namespace WebProject1. So this code will turn all the Console.WriteLine calls into blue insofar as you never specified System.Console.WriteLine.</p>\n" }, { "answer_id": 33843065, "author": "André C. Andersen", "author_id": 604048, "author_profile": "https://Stackoverflow.com/users/604048", "pm_score": 2, "selected": false, "text": "<p>The following was rejected as an <a href=\"https://stackoverflow.com/review/suggested-edits/1868685\">edit</a> to tvanfosson's answer. I was asked to contribute it as my own answer. I used his suggestion and finished the implementation of a <code>ConfigurationManager</code> wrapper. In principle I simply filled out the <code>...</code> in tvanfosson's answer.</p>\n\n<blockquote>\n <p>No. Extension methods require an instance of an object. You can\n however, write a static wrapper around the ConfigurationManager\n interface. If you implement the wrapper, you don't need an extension\n method since you can just add the method directly.</p>\n</blockquote>\n\n<pre><code>public static class ConfigurationManagerWrapper\n{\n public static NameValueCollection AppSettings\n {\n get { return ConfigurationManager.AppSettings; }\n }\n\n public static ConnectionStringSettingsCollection ConnectionStrings\n {\n get { return ConfigurationManager.ConnectionStrings; }\n }\n\n public static object GetSection(string sectionName)\n {\n return ConfigurationManager.GetSection(sectionName);\n }\n\n public static Configuration OpenExeConfiguration(string exePath)\n {\n return ConfigurationManager.OpenExeConfiguration(exePath);\n }\n\n public static Configuration OpenMachineConfiguration()\n {\n return ConfigurationManager.OpenMachineConfiguration();\n }\n\n public static Configuration OpenMappedExeConfiguration(ExeConfigurationFileMap fileMap, ConfigurationUserLevel userLevel)\n {\n return ConfigurationManager.OpenMappedExeConfiguration(fileMap, userLevel);\n }\n\n public static Configuration OpenMappedMachineConfiguration(ConfigurationFileMap fileMap)\n {\n return ConfigurationManager.OpenMappedMachineConfiguration(fileMap);\n }\n\n public static void RefreshSection(string sectionName)\n {\n ConfigurationManager.RefreshSection(sectionName);\n }\n}\n</code></pre>\n" }, { "answer_id": 44237464, "author": "Wouter", "author_id": 4491768, "author_profile": "https://Stackoverflow.com/users/4491768", "pm_score": 1, "selected": false, "text": "<p>You can use a cast on null to make it work.</p>\n\n<pre><code>public static class YoutTypeExtensionExample\n{\n public static void Example()\n {\n ((YourType)null).ExtensionMethod();\n }\n}\n</code></pre>\n\n<p>The extension:</p>\n\n<pre><code>public static class YourTypeExtension\n{\n public static void ExtensionMethod(this YourType x) { }\n}\n</code></pre>\n\n<p>YourType:</p>\n\n<pre><code>public class YourType { }\n</code></pre>\n" }, { "answer_id": 44311302, "author": "Adel G.Eibesh", "author_id": 2533597, "author_profile": "https://Stackoverflow.com/users/2533597", "pm_score": 5, "selected": false, "text": "<p>I stumbled upon this thread while trying to find an answer to the same question the OP had. I didn't find the answer I wanted, but I ended up doing this.</p>\n<pre><code>public static class Helpers\n{\n public static void WriteLine(this ConsoleColor color, string text)\n {\n Console.ForegroundColor = color;\n Console.WriteLine(text);\n Console.ResetColor();\n }\n}\n</code></pre>\n<p>And I use it like this:</p>\n<pre><code>ConsoleColor.Cyan.WriteLine(&quot;voilà&quot;);\n</code></pre>\n" }, { "answer_id": 46466371, "author": "mbx", "author_id": 303290, "author_profile": "https://Stackoverflow.com/users/303290", "pm_score": 4, "selected": false, "text": "<p>As of C#7 this isn't supported. There are however <a href=\"https://channel9.msdn.com/Blogs/Seth-Juarez/A-Preview-of-C-8-with-Mads-Torgersen\" rel=\"noreferrer\">discussions about integrating something like that in C#8</a> and <a href=\"https://github.com/dotnet/csharplang/issues/164\" rel=\"noreferrer\">proposals worth supporting</a>.</p>\n" }, { "answer_id": 51805734, "author": "Douglas Potesta", "author_id": 8309567, "author_profile": "https://Stackoverflow.com/users/8309567", "pm_score": 2, "selected": false, "text": "<p>It is not possible to write an extension method, however it is possible to mimic the behaviour you are asking for.</p>\n\n<pre><code>using FooConsole = System.Console;\n\npublic static class Console\n{\n public static void WriteBlueLine(string text)\n {\n FooConsole.ForegroundColor = ConsoleColor.Blue;\n FooConsole.WriteLine(text);\n FooConsole.ResetColor();\n }\n}\n</code></pre>\n\n<p>This will allow you to call Console.WriteBlueLine(fooText) in other classes. If the other classes want access to the other static functions of Console, they will have to be explicitly referenced through their namespace.</p>\n\n<p>You can always add all of the methods in to the replacement class if you want to have all of them in one place.</p>\n\n<p>So you would have something like </p>\n\n<pre><code>using FooConsole = System.Console;\n\npublic static class Console\n{\n public static void WriteBlueLine(string text)\n {\n FooConsole.ForegroundColor = ConsoleColor.Blue;\n FooConsole.WriteLine(text);\n FooConsole.ResetColor();\n }\n public static void WriteLine(string text)\n {\n FooConsole.WriteLine(text);\n }\n...etc.\n}\n</code></pre>\n\n<p>This would provide the kind of behaviour you are looking for.</p>\n\n<p>*Note Console will have to be added through the namespace that you put it in.</p>\n" }, { "answer_id": 70163411, "author": "Gourav", "author_id": 17547632, "author_profile": "https://Stackoverflow.com/users/17547632", "pm_score": 0, "selected": false, "text": "<p>Use this</p>\n<pre><code>public static class ConfigurationManagerWrapper\n {\n public static ConfigurationSection GetSection( string name )\n {\n return ConfigurationManager.GetSection( name );\n }\n\n .....\n\n public static ConfigurationSection GetWidgetSection()\n {\n return GetSection( &quot;widgets&quot; );\n }\n }\n</code></pre>\n" }, { "answer_id": 70903871, "author": "Amal K", "author_id": 11455105, "author_profile": "https://Stackoverflow.com/users/11455105", "pm_score": 0, "selected": false, "text": "<p>Although the methods of <code>Console</code> are static, its static methods <code>Write()</code> and <code>WriteLine()</code> merely redirect the call to <code>Console.Out.Write()</code> and <code>Console.Out.WriteLine()</code> respectively. <code>Out</code> is an instance whose type derives from the abstract class <code>TextWriter</code>. This makes it possible to define extension methods for <code>TextWriter</code>:</p>\n<pre><code>public static class ConsoleTextWriterExtensions\n{\n public static void WriteBlueLine(this TextWriter writer, string text)\n {\n Console.ForegroundColor = ConsoleColor.Blue;\n writer.WriteLine(text);\n Console.ResetColor();\n }\n\n public static void WriteUppercase(this TextWriter writer, string text)\n {\n writer.Write(text.ToUpper());\n }\n}\n</code></pre>\n<p>The method can then be invoked like this:</p>\n<pre><code>Console.Out.WriteBlueLine();\n</code></pre>\n<p>And the best part is that the type of the standard error stream instance <code>Console.Error</code> also derives from <code>TextWriter</code> which makes the same extension method also usable for <code>Console.Error</code>:</p>\n<pre><code>Console.Error.WriteBlueLine();\n</code></pre>\n<p>This can be quite useful if you have defined an extension method like <code>WriteTable()</code>(for writing a table out to the console) because you can also use it for the error stream or any other object of <code>TextWriter</code>.</p>\n<p>Newer versions of C# allow this to be even shorter with a <code>using static</code> statement for <code>Console</code> to get red of the <code>Console.</code> prefix:</p>\n<pre><code>using static System.Console;\n\nOut.WriteBlueLine(&quot;A blue line&quot;);\nError.WriteBlueLine(&quot;A blue line&quot;);\n</code></pre>\n" }, { "answer_id": 71372621, "author": "Clark Kent", "author_id": 8680581, "author_profile": "https://Stackoverflow.com/users/8680581", "pm_score": 1, "selected": false, "text": "<p>unfotunately NO, you CANNOT extend static classes</p>\n<p><a href=\"https://onecompiler.com/csharp/3xvbe7axg\" rel=\"nofollow noreferrer\">https://onecompiler.com/csharp/3xvbe7axg</a></p>\n<pre><code>using System;\n\nnamespace HelloWorld\n{\n public static class console_extensions {\n public static void EXTENSION(this object item) {\n System.Console.WriteLine(&quot;HELLO THERE!&quot;);\n }\n }\n \n public class Program\n {\n public static void Main(string[] args)\n {\n Console.WriteLine(&quot;Hello, World!&quot;);\n Console.EXTENSION();\n ((Console)null).EXTENSION();\n Console l = new Console();\n l.EXTENSION();\n }\n }\n}\n</code></pre>\n<p>output</p>\n<pre><code>Compilation failed: 4 error(s), 0 warnings\n\nHelloWorld.cs(16,12): error CS0117: `System.Console' does not contain a definition for `EXTENSION'\n/usr/lib/mono/4.5/mscorlib.dll (Location of the symbol related to previous error)\nHelloWorld.cs(17,5): error CS0716: Cannot convert to static type `System.Console'\nHelloWorld.cs(18,4): error CS0723: `l': cannot declare variables of static types\n/usr/lib/mono/4.5/mscorlib.dll (Location of the symbol related to previous error)\nHelloWorld.cs(18,16): error CS0712: Cannot create an instance of the static class `System.Console'\n/usr/lib/mono/4.5/mscorlib.dll (Location of the symbol related to previous error)\n</code></pre>\n<p>however you CAN pass <code>null</code> to the extension method</p>\n<pre><code>using System;\n\nnamespace HelloWorld\n{\n public static class static_extensions {\n public static void print(this object item, int data = 0) {\n Console.WriteLine(&quot;EXT: I AM A STATIC EXTENSION!&quot;);\n Console.WriteLine(&quot;EXT: MY ITEM IS: &quot; + item);\n Console.WriteLine(&quot;EXT: MY DATA IS: &quot; + data);\n string i;\n if (item == null) {\n i = &quot;null&quot;;\n } else {\n i = item.GetType().Name;\n }\n Console.WriteLine(&quot;EXT: MY TYPE IS: &quot; + i + &quot;\\n&quot;);\n }\n }\n\n public class Program\n {\n \n public static void Main(string[] args)\n {\n // an extension method can be\n // called directly\n // (null is an instance)\n static_extensions.print(null);\n\n // an extension method can also be\n // called directly with arguments\n // (null is an instance)\n static_extensions.print(null, 1);\n \n // an extension method can also be\n // called as part of an instance\n int x = 0; // initialize int\n x.print();\n \n // an extension method can also be\n // called as part of an instance\n // and with data\n int x2 = 0; // initialize int\n x2.print(2);\n \n // an extension method can also be\n // called directly from null\n // since `null` is an instance\n ((string)null).print();\n \n // an extension method can also be\n // called directly from null\n // and with data\n // since `null` is an instance\n ((string)null).print(4);\n }\n }\n}\n</code></pre>\n<p>live example: <a href=\"https://onecompiler.com/csharp/3xvbc8s6w\" rel=\"nofollow noreferrer\">https://onecompiler.com/csharp/3xvbc8s6w</a></p>\n<p>output:</p>\n<pre><code>EXT: I AM A STATIC EXTENSION!\nEXT: MY ITEM IS: \nEXT: MY DATA IS: 0\nEXT: MY TYPE IS: null\n\nEXT: I AM A STATIC EXTENSION!\nEXT: MY ITEM IS: \nEXT: MY DATA IS: 1\nEXT: MY TYPE IS: null\n\nEXT: I AM A STATIC EXTENSION!\nEXT: MY ITEM IS: 0\nEXT: MY DATA IS: 0\nEXT: MY TYPE IS: Int32\n\nEXT: I AM A STATIC EXTENSION!\nEXT: MY ITEM IS: 0\nEXT: MY DATA IS: 2\nEXT: MY TYPE IS: Int32\n\nEXT: I AM A STATIC EXTENSION!\nEXT: MY ITEM IS: \nEXT: MY DATA IS: 0\nEXT: MY TYPE IS: null\n\nEXT: I AM A STATIC EXTENSION!\nEXT: MY ITEM IS: \nEXT: MY DATA IS: 4\nEXT: MY TYPE IS: null\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249222", "https://Stackoverflow.com", "https://Stackoverflow.com/users/49/" ]
I'm a fan of extension methods in C#, but haven't had any success adding an extension method to a static class, such as `Console`. For example, if I want to add an extension to `Console`, called '`WriteBlueLine`', so that I can go: ``` Console.WriteBlueLine("This text is blue"); ``` I tried this by adding a local, public static method, with `Console` as a '`this`' parameter... but no dice! ``` public static class Helpers { public static void WriteBlueLine(this Console c, string text) { Console.ForegroundColor = ConsoleColor.Blue; Console.WriteLine(text); Console.ResetColor(); } } ``` This didn't add a '`WriteBlueLine`' method to `Console`... am I doing it wrong? Or asking for the impossible?
No. Extension methods require an instance variable (value) for an object. You can however, write a static wrapper around the `ConfigurationManager` interface. If you implement the wrapper, you don't need an extension method since you can just add the method directly. ``` public static class ConfigurationManagerWrapper { public static ConfigurationSection GetSection( string name ) { return ConfigurationManager.GetSection( name ); } ..... public static ConfigurationSection GetWidgetSection() { return GetSection( "widgets" ); } } ```
249,241
<p>I have an application that uses the accelerometer. Sometimes, the application will launch without the accelerometer data updating. Relaunching the app, sometimes the problem persist, sometimes it doesn't. And even weirder, sometimes I can try 10 times and everything works as expected. Is this a bug, or maybe something I am missing. Debugging, this code is never called when the accelerometer is not updated:</p> <pre><code>- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration; </code></pre> <p>Any ideas?</p>
[ { "answer_id": 249492, "author": "MrDatabase", "author_id": 22471, "author_profile": "https://Stackoverflow.com/users/22471", "pm_score": 1, "selected": false, "text": "<p>I have this same problem. It happens perhaps 1/20 times with an app I made from the CrashLanding sample. After I noticed it with my app I grabbed a fresh version of Crashlanding, installed it, and finally got it to start with accelerometer failing.</p>\n\n<p>I don't know how to fix it. Honestly I hate the accelerometer... at least for controlling games :-\\</p>\n\n<p>Also, the accelerometer has occasionally failed when I start the \"accelerometer\" sample project.</p>\n" }, { "answer_id": 252617, "author": "carlos", "author_id": 29642, "author_profile": "https://Stackoverflow.com/users/29642", "pm_score": 4, "selected": true, "text": "<p>I finally found a work around. This is a known bug. So the work around I found is to start a thread and have this thread check if the accelerometer delegate has been called, if it has, then quit the thread, if not, set the delegate again, and re-test, until the accelerometer delegate gets called. I tested this throughly and it works flawlessly. I hope this gets resolved on the next update of the iPhone OS.</p>\n" }, { "answer_id": 253940, "author": "SytS", "author_id": 22502, "author_profile": "https://Stackoverflow.com/users/22502", "pm_score": 1, "selected": false, "text": "<p>As others have mentioned, this is a known bug; I have logged the bug with Apple (Bug Reporter problem ID 6093028), perhaps others have done so as well. As far as I know, all apps that makes use of UIAccelerometer (including Apple's sample apps) suffer from this issue, though the frequency of occurance varies.</p>\n" }, { "answer_id": 308897, "author": "Marco", "author_id": 30480, "author_profile": "https://Stackoverflow.com/users/30480", "pm_score": 1, "selected": false, "text": "<p>FWIW, my app is widely used and it uses the accelerometer, and I've never had this problem.</p>\n\n<p>My use case may be different than yours: I only enable it on user request, well after the application is launched.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249241", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29642/" ]
I have an application that uses the accelerometer. Sometimes, the application will launch without the accelerometer data updating. Relaunching the app, sometimes the problem persist, sometimes it doesn't. And even weirder, sometimes I can try 10 times and everything works as expected. Is this a bug, or maybe something I am missing. Debugging, this code is never called when the accelerometer is not updated: ``` - (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration; ``` Any ideas?
I finally found a work around. This is a known bug. So the work around I found is to start a thread and have this thread check if the accelerometer delegate has been called, if it has, then quit the thread, if not, set the delegate again, and re-test, until the accelerometer delegate gets called. I tested this throughly and it works flawlessly. I hope this gets resolved on the next update of the iPhone OS.
249,247
<p>Is it possible to add an image overlay to a google map that scales as the user zooms?</p> <p>My current code works like this:</p> <pre><code>var map = new GMap2(document.getElementById("gMap")); var customIcon = new GIcon(); customIcon.iconSize = new GSize(100, 100); customIcon.image = "/images/image.png"; map.addOverlay(new GMarker(new GLatLng(50, 50), { icon:customIcon })); </code></pre> <p>However, this adds an overlay that maintains the same size as the user zooms in and out (it is acts as a UI element like the sidebar zoom control).</p>
[ { "answer_id": 249249, "author": "moogs", "author_id": 26374, "author_profile": "https://Stackoverflow.com/users/26374", "pm_score": 1, "selected": false, "text": "<p>There is a zoomend event, fired when the map reaches a new zoom level. The event handler receives the previous and the new zoom level as arguments.</p>\n\n<p><a href=\"http://code.google.com/apis/maps/documentation/reference.html#Events_GMap\" rel=\"nofollow noreferrer\">http://code.google.com/apis/maps/documentation/reference.html#Events_GMap</a></p>\n" }, { "answer_id": 249294, "author": "Matt Mitchell", "author_id": 364, "author_profile": "https://Stackoverflow.com/users/364", "pm_score": 1, "selected": true, "text": "<p>Well after messing around trying to scale it myself for a little bit I found a helper called <a href=\"http://econym.org.uk/gmap/einsert.htm\" rel=\"nofollow noreferrer\">EInserts</a> which I'm going to check out.</p>\n\n<p>Addition:</p>\n\n<p>Okay EInserts is about the coolest thing ever.\nIt even has a method to allow you to drag the image and place it in development mode for easy lining up.</p>\n" }, { "answer_id": 249551, "author": "diciu", "author_id": 2811, "author_profile": "https://Stackoverflow.com/users/2811", "pm_score": 1, "selected": false, "text": "<p>You might want to check out <a href=\"http://openlayers.org/\" rel=\"nofollow noreferrer\">openlayers</a></p>\n\n<p>It's a very capable Javascript API - it supports a bunch of back ends, allowing you to transparently switch between, say, Google Map tiles and Yahoo Map tiles.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249247", "https://Stackoverflow.com", "https://Stackoverflow.com/users/364/" ]
Is it possible to add an image overlay to a google map that scales as the user zooms? My current code works like this: ``` var map = new GMap2(document.getElementById("gMap")); var customIcon = new GIcon(); customIcon.iconSize = new GSize(100, 100); customIcon.image = "/images/image.png"; map.addOverlay(new GMarker(new GLatLng(50, 50), { icon:customIcon })); ``` However, this adds an overlay that maintains the same size as the user zooms in and out (it is acts as a UI element like the sidebar zoom control).
Well after messing around trying to scale it myself for a little bit I found a helper called [EInserts](http://econym.org.uk/gmap/einsert.htm) which I'm going to check out. Addition: Okay EInserts is about the coolest thing ever. It even has a method to allow you to drag the image and place it in development mode for easy lining up.
249,253
<p>I have a script to extract certain data from a much bigger table, with one field in particular changing regularly, e.g.</p> <pre><code>SELECT CASE @Flag WHEN 1 THEN t.field1 WHEN 2 THEN t.field2 WHEN 3 THEN t.field3 END as field, ...[A bunch of other fields] FROM table t </code></pre> <p>However, the issue is now I want to do other processing on the data. I'm trying to figure out the most effective method. I need to have some way of getting the flag through, so I know I'm talking about data sliced by the right field.</p> <p>One possible solution I was playing around with a bit (mostly to see what would happen) is to dump the contents of the script into a table function which has the flag passed to it, and then use a SELECT query on the results of the function. I've managed to get it to work, but it's significantly slower than...</p> <p>The obvious solution, and probably the most efficient use of processor cycles: to create a series of cache tables, one for each of the three flag values. However, the problem then is to find some way of extracting the data from the right cache table to perform the calculation. The obvious, though incorrect, response would be something like</p> <pre><code>SELECT CASE @Flag WHEN 1 THEN table1.field WHEN 2 THEN table2.field WHEN 3 THEN table3.field END as field, ...[The various calculated fields] FROM table1, table2, table3 </code></pre> <p>Unfortunately, as is obvious, this creates a massive cross join - which is not my intended result at all.</p> <p>Does anyone know how to turn that cross join into an "Only look at x table"? (Without use of Dynamic SQL, which makes things hard to deal with?) Or an alternative solution, that's still reasonably speedy?</p> <p>EDIT: Whether it's a good reason or not, the idea I was trying to implement was to not have three largely identical queries, that differ only by table - which would then have to be edited identically whenever a change is made to the logic. Which is why I've avoided the "Have the flag entirely separate" thing thus far...</p>
[ { "answer_id": 249313, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 3, "selected": false, "text": "<p>I think you need to pull <code>@Flag</code> out of the query altogether, and use it to decide which of three separate SELECT statements to run.</p>\n" }, { "answer_id": 249323, "author": "dkretz", "author_id": 31641, "author_profile": "https://Stackoverflow.com/users/31641", "pm_score": 0, "selected": false, "text": "<p>You seem to be focusing your attention on the technology rather than the problem to be solved. Think about one select from the main table for each case - which is how you describe it here, isn't it?</p>\n" }, { "answer_id": 249344, "author": "WW.", "author_id": 14663, "author_profile": "https://Stackoverflow.com/users/14663", "pm_score": 2, "selected": false, "text": "<p>How about a UNION ALL for each value of FLAG.</p>\n\n<p>In the where clause of the first bit include:</p>\n\n<pre><code>AND @flag = 1\n</code></pre>\n\n<p>Although the comment about running different select statements for different flag values also makes sense to me.</p>\n" }, { "answer_id": 555527, "author": "Margaret", "author_id": 27290, "author_profile": "https://Stackoverflow.com/users/27290", "pm_score": 1, "selected": true, "text": "<p>A simpler solution, and one suggested by a workmate:</p>\n\n<pre><code>SELECT CASE @Flag WHEN 1 THEN t.field1 WHEN 2 THEN t.field2 WHEN 3 \n THEN t.field3 END as field,\n [A bunch of other fields],\n @Flag as flag\nFROM table t\n</code></pre>\n\n<p>Then base the decision making on the last field. A lot simpler, and probably should have occurred to me in the first place.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249253", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27290/" ]
I have a script to extract certain data from a much bigger table, with one field in particular changing regularly, e.g. ``` SELECT CASE @Flag WHEN 1 THEN t.field1 WHEN 2 THEN t.field2 WHEN 3 THEN t.field3 END as field, ...[A bunch of other fields] FROM table t ``` However, the issue is now I want to do other processing on the data. I'm trying to figure out the most effective method. I need to have some way of getting the flag through, so I know I'm talking about data sliced by the right field. One possible solution I was playing around with a bit (mostly to see what would happen) is to dump the contents of the script into a table function which has the flag passed to it, and then use a SELECT query on the results of the function. I've managed to get it to work, but it's significantly slower than... The obvious solution, and probably the most efficient use of processor cycles: to create a series of cache tables, one for each of the three flag values. However, the problem then is to find some way of extracting the data from the right cache table to perform the calculation. The obvious, though incorrect, response would be something like ``` SELECT CASE @Flag WHEN 1 THEN table1.field WHEN 2 THEN table2.field WHEN 3 THEN table3.field END as field, ...[The various calculated fields] FROM table1, table2, table3 ``` Unfortunately, as is obvious, this creates a massive cross join - which is not my intended result at all. Does anyone know how to turn that cross join into an "Only look at x table"? (Without use of Dynamic SQL, which makes things hard to deal with?) Or an alternative solution, that's still reasonably speedy? EDIT: Whether it's a good reason or not, the idea I was trying to implement was to not have three largely identical queries, that differ only by table - which would then have to be edited identically whenever a change is made to the logic. Which is why I've avoided the "Have the flag entirely separate" thing thus far...
A simpler solution, and one suggested by a workmate: ``` SELECT CASE @Flag WHEN 1 THEN t.field1 WHEN 2 THEN t.field2 WHEN 3 THEN t.field3 END as field, [A bunch of other fields], @Flag as flag FROM table t ``` Then base the decision making on the last field. A lot simpler, and probably should have occurred to me in the first place.
249,256
<p>I was browsing the <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c">Hidden Features of C#</a> question and thought I would try out one of the features I was unfamiliar with. Unfortunately I use Visual Studio 2005 and the feature in question was introduced later. Is there a good list for new features in C# 3.0 (Visual Studio 2008) vs. C# 2.0 (Visual Studio 2005)? </p>
[ { "answer_id": 249261, "author": "ojrac", "author_id": 20760, "author_profile": "https://Stackoverflow.com/users/20760", "pm_score": 1, "selected": false, "text": "<p>Here's a link to the MS page on .NET 3.0: <a href=\"http://msdn.microsoft.com/en-us/library/bb822048.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/bb822048.aspx</a>\n...and on VS 2008 for C#: <a href=\"http://msdn.microsoft.com/en-us/library/bb383815.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/bb383815.aspx</a></p>\n\n<p>I haven't tried VS2008 and .NET 3.0 out, but I figure the links might help ;)</p>\n" }, { "answer_id": 249300, "author": "Matt Ephraim", "author_id": 22291, "author_profile": "https://Stackoverflow.com/users/22291", "pm_score": 4, "selected": true, "text": "<p>This is not a comprehensive list but these are some of my favorite new features of C# 3.0:</p>\n\n<p>New type initializers. Instead of saying this: </p>\n\n<pre><code>Person person = new Person();\nperson.Name = \"John Smith\";\n</code></pre>\n\n<p>I can say this:</p>\n\n<pre><code>Person person = new Person() { Name = \"John Smith\" };\n</code></pre>\n\n<p>Similarly, instead of adding items individually, I can initialize types that implement IEnumerable like this:</p>\n\n<pre><code>List&lt;string&gt; list = new List&lt;string&gt; { \"foo\", \"bar\" }; \n</code></pre>\n\n<p>The new syntax for lambda expressions is also nice. Instead of typing this:</p>\n\n<pre><code>people.Where(delegate(person) { return person.Age &gt;= 21;);\n</code></pre>\n\n<p>I can type this:</p>\n\n<pre><code>people.Where(person =&gt; person.Age &gt;= 21 );\n</code></pre>\n\n<p>You can also write extension methods to built in types:</p>\n\n<pre><code>public static class StringUtilities\n{\n public static string Pluralize(this word)\n {\n ...\n }\n}\n</code></pre>\n\n<p>Which allows something like this:</p>\n\n<pre><code>string word = \"person\";\nword.Pluralize(); // Returns \"people\"\n</code></pre>\n\n<p>And finally. Anonymous types. So you can create anonymous classes on the fly, like this:</p>\n\n<pre><code>var book = new { Title: \"...\", Cost: \"...\" };\n</code></pre>\n" }, { "answer_id": 249308, "author": "Shiju", "author_id": 27753, "author_profile": "https://Stackoverflow.com/users/27753", "pm_score": 0, "selected": false, "text": "<p>One of the unknown but powerful feature of Visual Studio 2008 is <a href=\"http://msdn.microsoft.com/en-us/library/bb126445.aspx\" rel=\"nofollow noreferrer\">T4 (Text Template Transformation Toolkit)</a>. T4 is a code generator built right into Visual Studio 2008.</p>\n\n<p>Check the <a href=\"http://weblogs.asp.net/scottgu/default.aspx\" rel=\"nofollow noreferrer\">Scott Guthrie's</a> blog post <a href=\"http://weblogs.asp.net/scottgu/archive/2007/11/19/visual-studio-2008-and-net-3-5-released.aspx\" rel=\"nofollow noreferrer\">Visual Studio 2008 and .NET 3.5 Released</a>. This post was written when Visual Studio 2008 and .NET 3.5 is Released. This post has included lot of links for the new features of Visual Studio 2008 and C# 3.0. </p>\n" }, { "answer_id": 249380, "author": "Mike Henry", "author_id": 14934, "author_profile": "https://Stackoverflow.com/users/14934", "pm_score": 2, "selected": false, "text": "<p>A couple features I like:</p>\n\n<ul>\n<li><p>VS 2008 supports targeting various version of the .NET framework so you can target 2.0, 3.0 or 3.5</p></li>\n<li><p>Automatic properties are nice.</p></li>\n</ul>\n\n<p>For example:</p>\n\n<pre><code>public int Id { get; set; }\n</code></pre>\n\n<p>instead of:</p>\n\n<pre><code>private int _id;\npublic int Id {\n get { return _id; }\n set { _id = value; }\n}\n</code></pre>\n" }, { "answer_id": 249382, "author": "Aaron Powell", "author_id": 11388, "author_profile": "https://Stackoverflow.com/users/11388", "pm_score": 2, "selected": false, "text": "<p>Multi-targetting support. You can build .NET 2 -> .NET 3.5 all from the one IDE.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249256", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6180/" ]
I was browsing the [Hidden Features of C#](https://stackoverflow.com/questions/9033/hidden-features-of-c) question and thought I would try out one of the features I was unfamiliar with. Unfortunately I use Visual Studio 2005 and the feature in question was introduced later. Is there a good list for new features in C# 3.0 (Visual Studio 2008) vs. C# 2.0 (Visual Studio 2005)?
This is not a comprehensive list but these are some of my favorite new features of C# 3.0: New type initializers. Instead of saying this: ``` Person person = new Person(); person.Name = "John Smith"; ``` I can say this: ``` Person person = new Person() { Name = "John Smith" }; ``` Similarly, instead of adding items individually, I can initialize types that implement IEnumerable like this: ``` List<string> list = new List<string> { "foo", "bar" }; ``` The new syntax for lambda expressions is also nice. Instead of typing this: ``` people.Where(delegate(person) { return person.Age >= 21;); ``` I can type this: ``` people.Where(person => person.Age >= 21 ); ``` You can also write extension methods to built in types: ``` public static class StringUtilities { public static string Pluralize(this word) { ... } } ``` Which allows something like this: ``` string word = "person"; word.Pluralize(); // Returns "people" ``` And finally. Anonymous types. So you can create anonymous classes on the fly, like this: ``` var book = new { Title: "...", Cost: "..." }; ```
249,262
<pre><code>'''use Jython''' import shutil print dir(shutil) </code></pre> <p>There is no, shutil.move, how does one move a file with Jython? and while we at it, how does one delete a file with Jython?</p>
[ { "answer_id": 249279, "author": "Charles Duffy", "author_id": 14122, "author_profile": "https://Stackoverflow.com/users/14122", "pm_score": 3, "selected": true, "text": "<p><code>os.rename()</code> to move, and <code>os.unlink()</code> to delete -- just like Python pre-<code>shutil</code>.</p>\n" }, { "answer_id": 250933, "author": "Charles Duffy", "author_id": 14122, "author_profile": "https://Stackoverflow.com/users/14122", "pm_score": 1, "selected": false, "text": "<p>If you need support for moving across filesystems, consider just copying CPython's <code>shutil.py</code> into your project. <A HREF=\"http://www.python.org/download/releases/2.4.2/license/\" rel=\"nofollow noreferrer\">The Python License</A> is flexible enough to allow this (even for commercial projects), as long as licensing and attribution information are retained.</p>\n" }, { "answer_id": 2334425, "author": "David Zhang", "author_id": 281251, "author_profile": "https://Stackoverflow.com/users/281251", "pm_score": 0, "selected": false, "text": "<pre><code>f1 = File(filename_old)\nf1.nameTo(File(filename_new))\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249262", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21537/" ]
``` '''use Jython''' import shutil print dir(shutil) ``` There is no, shutil.move, how does one move a file with Jython? and while we at it, how does one delete a file with Jython?
`os.rename()` to move, and `os.unlink()` to delete -- just like Python pre-`shutil`.
249,266
<p>I have a large xml document that needs to be processed 100 records at a time</p> <p>It is being done within a Windows Service written in c#. </p> <p>The structure is as follows :</p> <pre><code>&lt;docket xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="docket.xsd"&gt; &lt;order&gt; &lt;Date&gt;2008-10-13&lt;/Date&gt; &lt;orderNumber&gt;050758023&lt;/orderNumber&gt; &lt;ParcelID/&gt; &lt;CustomerName&gt;sddsf&lt;/CustomerName&gt; &lt;DeliveryName&gt;dsfd&lt;/DeliveryName&gt; &lt;Address1&gt;sdf&lt;/Address1&gt; &lt;Address2&gt;sdfsdd&lt;/Address2&gt; &lt;Address3&gt;sdfdsfdf&lt;/Address3&gt; &lt;Address4&gt;dffddf&lt;/Address4&gt; &lt;PostCode/&gt; &lt;/order&gt; &lt;order&gt; &lt;Date&gt;2008-10-13&lt;/Date&gt; &lt;orderNumber&gt;050758023&lt;/orderNumber&gt; &lt;ParcelID/&gt; &lt;CustomerName&gt;sddsf&lt;/CustomerName&gt; &lt;DeliveryName&gt;dsfd&lt;/DeliveryName&gt; &lt;Address1&gt;sdf&lt;/Address1&gt; &lt;Address2&gt;sdfsdd&lt;/Address2&gt; &lt;Address3&gt;sdfdsfdf&lt;/Address3&gt; &lt;Address4&gt;dffddf&lt;/Address4&gt; &lt;PostCode/&gt; &lt;/order&gt; ..... ..... &lt;/docket&gt; </code></pre> <p>There could be thousands of orders in a docket.</p> <p>I need to chop this into 100 element chunks</p> <p>However each of the 100 orders still need to be wrapped with the parent "docket" node and have the same namespace etc</p> <p>is this possible? </p>
[ { "answer_id": 249310, "author": "Jim Burger", "author_id": 20164, "author_profile": "https://Stackoverflow.com/users/20164", "pm_score": 1, "selected": false, "text": "<p>Naive, iterative, but works [EDIT: in .NET 3.5 only]</p>\n\n<pre><code> public List&lt;XDocument&gt; ChunkDocket(XDocument docket, int chunkSize)\n {\n var newDockets = new List&lt;XDocument&gt;();\n var d = new XDocument(docket);\n var orders = d.Root.Elements(\"order\");\n XDocument newDocket = null;\n\n do\n {\n newDocket = new XDocument(new XElement(\"docket\"));\n var chunk = orders.Take(chunkSize);\n newDocket.Root.Add(chunk);\n chunk.Remove();\n newDockets.Add(newDocket);\n } while (orders.Any());\n\n return newDockets;\n }\n</code></pre>\n" }, { "answer_id": 249408, "author": "Jim Burger", "author_id": 20164, "author_profile": "https://Stackoverflow.com/users/20164", "pm_score": 4, "selected": true, "text": "<p>Another naive solution; this time for .NET 2.0. It should give you an idea of how to go about what you want. Uses Xpath expressions instead of Linq to XML. Chunks a 100 order docket into 10 dockets in under a second on my devbox.</p>\n\n<pre><code> public List&lt;XmlDocument&gt; ChunkDocket(XmlDocument docket, int chunkSize)\n {\n List&lt;XmlDocument&gt; newDockets = new List&lt;XmlDocument&gt;();\n // \n int orderCount = docket.SelectNodes(\"//docket/order\").Count;\n int chunkStart = 0;\n XmlDocument newDocket = null;\n XmlElement root = null;\n XmlNodeList chunk = null;\n\n while (chunkStart &lt; orderCount)\n {\n newDocket = new XmlDocument();\n root = newDocket.CreateElement(\"docket\");\n newDocket.AppendChild(root);\n\n chunk = docket.SelectNodes(String.Format(\"//docket/order[position() &gt; {0} and position() &lt;= {1}]\", chunkStart, chunkStart + chunkSize));\n\n chunkStart += chunkSize;\n\n XmlNode targetNode = null;\n foreach (XmlNode c in chunk)\n {\n targetNode = newDocket.ImportNode(c, true);\n root.AppendChild(targetNode);\n }\n\n newDockets.Add(newDocket);\n } \n\n return newDockets;\n }\n</code></pre>\n" }, { "answer_id": 249435, "author": "Ray Lu", "author_id": 11413, "author_profile": "https://Stackoverflow.com/users/11413", "pm_score": 0, "selected": false, "text": "<p>If the reason to process 100 orders at a time is for performance purposes, e.g. taking too much time and resource to open a big file, You can utilize XmlReader to process order element one at a time without degrading the performance.</p>\n\n<pre><code>XmlReader reader = XmlReader.Create(@\"c:\\foo\\Doket.xml\")\nwhile( reader.Read())\n{\n if(reader.LocalName == \"order\")\n {\n // read each child element and its value from the reader.\n // or you can deserialize the order element by using a XmlSerializer and Order class\n } \n}\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249266", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17194/" ]
I have a large xml document that needs to be processed 100 records at a time It is being done within a Windows Service written in c#. The structure is as follows : ``` <docket xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="docket.xsd"> <order> <Date>2008-10-13</Date> <orderNumber>050758023</orderNumber> <ParcelID/> <CustomerName>sddsf</CustomerName> <DeliveryName>dsfd</DeliveryName> <Address1>sdf</Address1> <Address2>sdfsdd</Address2> <Address3>sdfdsfdf</Address3> <Address4>dffddf</Address4> <PostCode/> </order> <order> <Date>2008-10-13</Date> <orderNumber>050758023</orderNumber> <ParcelID/> <CustomerName>sddsf</CustomerName> <DeliveryName>dsfd</DeliveryName> <Address1>sdf</Address1> <Address2>sdfsdd</Address2> <Address3>sdfdsfdf</Address3> <Address4>dffddf</Address4> <PostCode/> </order> ..... ..... </docket> ``` There could be thousands of orders in a docket. I need to chop this into 100 element chunks However each of the 100 orders still need to be wrapped with the parent "docket" node and have the same namespace etc is this possible?
Another naive solution; this time for .NET 2.0. It should give you an idea of how to go about what you want. Uses Xpath expressions instead of Linq to XML. Chunks a 100 order docket into 10 dockets in under a second on my devbox. ``` public List<XmlDocument> ChunkDocket(XmlDocument docket, int chunkSize) { List<XmlDocument> newDockets = new List<XmlDocument>(); // int orderCount = docket.SelectNodes("//docket/order").Count; int chunkStart = 0; XmlDocument newDocket = null; XmlElement root = null; XmlNodeList chunk = null; while (chunkStart < orderCount) { newDocket = new XmlDocument(); root = newDocket.CreateElement("docket"); newDocket.AppendChild(root); chunk = docket.SelectNodes(String.Format("//docket/order[position() > {0} and position() <= {1}]", chunkStart, chunkStart + chunkSize)); chunkStart += chunkSize; XmlNode targetNode = null; foreach (XmlNode c in chunk) { targetNode = newDocket.ImportNode(c, true); root.AppendChild(targetNode); } newDockets.Add(newDocket); } return newDockets; } ```
249,283
<p>I've been using virtualenv lately while developing in python. I like the idea of a segregated development environment using the <strong>--no-site-packages</strong> option, but doing this while developing a PyGTK app can be a bit tricky. The PyGTK modules are installed on Ubuntu by default, and I would like to make a virtualenv (with --no-site-packages) aware of specific modules that are located elsewhere on the system.</p> <p>What's the best way to do this? Or should I just suck it up and drop the --no-site-packages option?</p>
[ { "answer_id": 249342, "author": "monkut", "author_id": 24718, "author_profile": "https://Stackoverflow.com/users/24718", "pm_score": 3, "selected": false, "text": "<p>One way is to add the paths to your code using sys.path.</p>\n\n<pre><code>import sys\n\nsys.path.append(somepath)\n</code></pre>\n\n<p>Another way is to use site, which processes .pth files in addition to adding to sys.path.</p>\n\n<pre><code>import site\n\nsite.addsitedir(sitedir, known_paths=None)\n</code></pre>\n\n<p><a href=\"https://docs.python.org/library/site.html\" rel=\"nofollow noreferrer\">https://docs.python.org/library/site.html</a></p>\n\n<p>But you probably don't want to add this to all your related code. </p>\n\n<p>I've seen mention of sitecustomize.py being used to perform something like this, but after some testing I couldn't get it to work as might be expected. </p>\n\n<p>Here it mentions that auto-import of sitecustomize.py ended in 2.5, if your not on 2.5 try it out. (just add one of the path add methods above to the file and drop it in the directory your program is run)\nA work around method is mentioned in the post for users of 2.5 and up. </p>\n\n<p><a href=\"http://code.activestate.com/recipes/552729/\" rel=\"nofollow noreferrer\">http://code.activestate.com/recipes/552729/</a></p>\n" }, { "answer_id": 249708, "author": "Ali Afshar", "author_id": 28380, "author_profile": "https://Stackoverflow.com/users/28380", "pm_score": 1, "selected": false, "text": "<p>I find in this situation, symlinks, or even copying specific files (packages, modules, extensions) works really well.</p>\n\n<p>It allows the program to emulate being run in the target environment, rather than changing the application to suit the development environment.</p>\n\n<p>Same deal for something like AppEngine.</p>\n" }, { "answer_id": 1670513, "author": "iElectric", "author_id": 133235, "author_profile": "https://Stackoverflow.com/users/133235", "pm_score": 6, "selected": true, "text": "<pre><code>$ virtualenv --no-site-packages --python=/usr/bin/python2.6 myvirtualenv\n$ cd myvirtualenv\n$ source bin/activate\n$ cd lib/python2.6/\n$ ln -s /usr/lib/pymodules/python2.6/gtk-2.0/ \n$ ln -s /usr/lib/pymodules/python2.6/pygtk.pth \n$ ln -s /usr/lib/pymodules/python2.6/pygtk.py \n$ ln -s /usr/lib/pymodules/python2.6/cairo/\n$ python\n&gt;&gt;&gt; import pygtk\n&gt;&gt;&gt; import gtk\n</code></pre>\n" }, { "answer_id": 12134232, "author": "Shane H", "author_id": 60247, "author_profile": "https://Stackoverflow.com/users/60247", "pm_score": 1, "selected": false, "text": "<p>Check out the postmkvirtualenv hook script here: </p>\n\n<p><a href=\"https://stackoverflow.com/a/9716100/60247\">https://stackoverflow.com/a/9716100/60247</a></p>\n\n<p>In that case, he's using it to import PyQt and SIP after a new Virtualenv is created, but you can add the packages that you need to LIBS. </p>\n\n<p>And vote that script up because it's fantastic :)</p>\n" }, { "answer_id": 27471458, "author": "Anthon", "author_id": 1307905, "author_profile": "https://Stackoverflow.com/users/1307905", "pm_score": 0, "selected": false, "text": "<p>If you want to include the links to the relevant system's python gtk-2.0 in the virtualenv, you can just use pip to install <a href=\"https://pypi.python.org/pypi/ruamel.venvgtk\" rel=\"nofollow noreferrer\">ruamel.venvgtk</a>:</p>\n\n<p>pip install ruamel.venvgtk\nYou don't have import anything, the links are setup during installation.</p>\n\n<p>This is especially handy if you are using <code>tox</code>, in that case you only need to include the dependency (for tox):</p>\n\n<pre><code>deps:\n pytest\n ruamel.venvgtk\n</code></pre>\n\n<p>and a newly setup python2.7 environment will have the relevant links included before the tests are run.</p>\n\n<p>More detailed information on how the links are setup can be found in <a href=\"https://stackoverflow.com/a/27471354/1307905\">this answer</a></p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249283", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18866/" ]
I've been using virtualenv lately while developing in python. I like the idea of a segregated development environment using the **--no-site-packages** option, but doing this while developing a PyGTK app can be a bit tricky. The PyGTK modules are installed on Ubuntu by default, and I would like to make a virtualenv (with --no-site-packages) aware of specific modules that are located elsewhere on the system. What's the best way to do this? Or should I just suck it up and drop the --no-site-packages option?
``` $ virtualenv --no-site-packages --python=/usr/bin/python2.6 myvirtualenv $ cd myvirtualenv $ source bin/activate $ cd lib/python2.6/ $ ln -s /usr/lib/pymodules/python2.6/gtk-2.0/ $ ln -s /usr/lib/pymodules/python2.6/pygtk.pth $ ln -s /usr/lib/pymodules/python2.6/pygtk.py $ ln -s /usr/lib/pymodules/python2.6/cairo/ $ python >>> import pygtk >>> import gtk ```
249,301
<p>How do I take an efficient simple random sample in SQL? The database in question is running MySQL; my table is at least 200,000 rows, and I want a simple random sample of about 10,000.</p> <p>The &quot;obvious&quot; answer is to:</p> <pre><code>SELECT * FROM table ORDER BY RAND() LIMIT 10000 </code></pre> <p>For large tables, that's too slow: it calls <code>RAND()</code> for every row (which already puts it at O(n)), and sorts them, making it O(n lg n) at best. Is there a way to do this faster than O(n)?</p> <p><em>Note</em>: As Andrew Mao points out in the comments, If you're using this approach on SQL Server, you should use the T-SQL function <code>NEWID()</code>, because RAND() <a href="http://msdn.microsoft.com/en-us/library/ms177610.asp" rel="noreferrer">may return the same value for all rows</a>.</p> <p><em>EDIT: 5 YEARS LATER</em></p> <p>I ran into this problem again with a bigger table, and ended up using a version of @ignorant's solution, with two tweaks:</p> <ul> <li>Sample the rows to 2-5x my desired sample size, to cheaply <code>ORDER BY RAND()</code></li> <li>Save the result of <code>RAND()</code> to an indexed column on every insert/update. (If your data set isn't very update-heavy, you may need to find another way to keep this column fresh.)</li> </ul> <p>To take a 1000-item sample of a table, I count the rows and sample the result down to, on average, 10,000 rows with the the frozen_rand column:</p> <pre><code>SELECT COUNT(*) FROM table; -- Use this to determine rand_low and rand_high SELECT * FROM table WHERE frozen_rand BETWEEN %(rand_low)s AND %(rand_high)s ORDER BY RAND() LIMIT 1000 </code></pre> <p>(My actual implementation involves more work to make sure I don't undersample, and to manually wrap rand_high around, but the basic idea is &quot;randomly cut your N down to a few thousand.&quot;)</p> <p>While this makes some sacrifices, it allows me to sample the database down using an index scan, until it's small enough to <code>ORDER BY RAND()</code> again.</p>
[ { "answer_id": 249351, "author": "staticsan", "author_id": 28832, "author_profile": "https://Stackoverflow.com/users/28832", "pm_score": -1, "selected": false, "text": "<p>Maybe you could do</p>\n\n<pre><code>SELECT * FROM table LIMIT 10000 OFFSET FLOOR(RAND() * 190000)\n</code></pre>\n" }, { "answer_id": 252563, "author": "user12861", "author_id": 12861, "author_profile": "https://Stackoverflow.com/users/12861", "pm_score": 6, "selected": true, "text": "<p>There's a very interesting discussion of this type of issue here: <a href=\"http://www.titov.net/2005/09/21/do-not-use-order-by-rand-or-how-to-get-random-rows-from-table/\" rel=\"noreferrer\"><a href=\"http://www.titov.net/2005/09/21/do-not-use-order-by-rand-or-how-to-get-random-rows-from-table/\" rel=\"noreferrer\">http://www.titov.net/2005/09/21/do-not-use-order-by-rand-or-how-to-get-random-rows-from-table/</a></a></p>\n\n<p>I think with absolutely no assumptions about the table that your O(n lg n) solution is the best. Though actually with a good optimizer or a slightly different technique the query you list may be a bit better, O(m*n) where m is the number of random rows desired, as it wouldn't necesssarily have to sort the whole large array, it could just search for the smallest m times. But for the sort of numbers you posted, m is bigger than lg n anyway.</p>\n\n<p>Three asumptions we might try out:</p>\n\n<ol>\n<li><p>there is a unique, indexed, primary key in the table</p></li>\n<li><p>the number of random rows you want to select (m) is much smaller than the number of rows in the table (n)</p></li>\n<li><p>the unique primary key is an integer that ranges from 1 to n with no gaps</p></li>\n</ol>\n\n<p>With only assumptions 1 and 2 I think this can be done in O(n), though you'll need to write a whole index to the table to match assumption 3, so it's not necesarily a fast O(n). If we can ADDITIONALLY assume something else nice about the table, we can do the task in O(m log m). Assumption 3 would be an easy nice additional property to work with. With a nice random number generator that guaranteed no duplicates when generating m numbers in a row, an O(m) solution would be possible. </p>\n\n<p>Given the three assumptions, the basic idea is to generate m unique random numbers between 1 and n, and then select the rows with those keys from the table. I don't have mysql or anything in front of me right now, so in slightly pseudocode this would look something like:</p>\n\n<pre><code>\ncreate table RandomKeys (RandomKey int)\ncreate table RandomKeysAttempt (RandomKey int)\n\n-- generate m random keys between 1 and n\nfor i = 1 to m\n insert RandomKeysAttempt select rand()*n + 1\n\n-- eliminate duplicates\ninsert RandomKeys select distinct RandomKey from RandomKeysAttempt\n\n-- as long as we don't have enough, keep generating new keys,\n-- with luck (and m much less than n), this won't be necessary\nwhile count(RandomKeys) &lt m\n NextAttempt = rand()*n + 1\n if not exists (select * from RandomKeys where RandomKey = NextAttempt)\n insert RandomKeys select NextAttempt\n\n-- get our random rows\nselect *\nfrom RandomKeys r\njoin table t ON r.RandomKey = t.UniqueKey\n</code></pre>\n\n<p>If you were really concerned about efficiency, you might consider doing the random key generation in some sort of procedural language and inserting the results in the database, as almost anything other than SQL would probably be better at the sort of looping and random number generation required.</p>\n" }, { "answer_id": 10656932, "author": "David F Mayer", "author_id": 1382887, "author_profile": "https://Stackoverflow.com/users/1382887", "pm_score": 3, "selected": false, "text": "<p>Just use </p>\n\n<pre><code>WHERE RAND() &lt; 0.1 \n</code></pre>\n\n<p>to get 10% of the records or</p>\n\n<pre><code>WHERE RAND() &lt; 0.01 \n</code></pre>\n\n<p>to get 1% of the records, etc.</p>\n" }, { "answer_id": 14629551, "author": "ignorant", "author_id": 2029648, "author_profile": "https://Stackoverflow.com/users/2029648", "pm_score": 6, "selected": false, "text": "<p>I think the fastest solution is </p>\n\n<pre><code>select * from table where rand() &lt;= .3\n</code></pre>\n\n<p>Here is why I think this should do the job. </p>\n\n<ul>\n<li>It will create a random number for each row. The number is between 0 and 1</li>\n<li>It evaluates whether to display that row if the number generated is between 0 and .3 (30%).</li>\n</ul>\n\n<p>This assumes that rand() is generating numbers in a uniform distribution. It is the quickest way to do this.</p>\n\n<p>I saw that someone had recommended that solution and they got shot down without proof.. here is what I would say to that -</p>\n\n<ul>\n<li>This is O(n) but no sorting is required so it is faster than the O(n lg n)</li>\n<li><p>mysql is very capable of generating random numbers for each row. Try this -</p>\n\n<p>select rand() from INFORMATION_SCHEMA.TABLES limit 10;</p></li>\n</ul>\n\n<p>Since the database in question is mySQL, this is the right solution.</p>\n" }, { "answer_id": 18671107, "author": "KitKat", "author_id": 2626112, "author_profile": "https://Stackoverflow.com/users/2626112", "pm_score": 0, "selected": false, "text": "<p>Starting with the observation that we can retrieve the ids of a table (eg. count 5) based on a set:</p>\n\n<pre><code>select *\nfrom table_name\nwhere _id in (4, 1, 2, 5, 3)\n</code></pre>\n\n<p>we can come to the result that if we could generate the string <code>\"(4, 1, 2, 5, 3)\"</code>, then we would have a more efficient way than <code>RAND()</code>.</p>\n\n<p>For example, in Java:</p>\n\n<pre><code>ArrayList&lt;Integer&gt; indices = new ArrayList&lt;Integer&gt;(rowsCount);\nfor (int i = 0; i &lt; rowsCount; i++) {\n indices.add(i);\n}\nCollections.shuffle(indices);\nString inClause = indices.toString().replace('[', '(').replace(']', ')');\n</code></pre>\n\n<p>If ids have gaps, then the initial arraylist <code>indices</code> is the result of an sql query on ids.</p>\n" }, { "answer_id": 23400284, "author": "gatoatigrado", "author_id": 81636, "author_profile": "https://Stackoverflow.com/users/81636", "pm_score": 3, "selected": false, "text": "<p>Apparently in some versions of SQL there's a <code>TABLESAMPLE</code> command, but it's not in all SQL implementations (notably, Redshift).</p>\n\n<p><a href=\"http://technet.microsoft.com/en-us/library/ms189108%28v=sql.105%29.aspx\" rel=\"noreferrer\">http://technet.microsoft.com/en-us/library/ms189108(v=sql.105).aspx</a></p>\n" }, { "answer_id": 25632000, "author": "gazzman", "author_id": 1591026, "author_profile": "https://Stackoverflow.com/users/1591026", "pm_score": 1, "selected": false, "text": "<p>I want to point out that all of these solutions appear to sample without replacement. Selecting the top K rows from a random sort or joining to a table that contains unique keys in random order will yield a random sample generated without replacement.</p>\n\n<p>If you want your sample to be independent, you'll need to sample with replacement. See <a href=\"https://stackoverflow.com/questions/25451034/generating-bootstrapped-samples-in-t-sql\">Question 25451034</a> for one example of how to do this using a JOIN in a manner similar to user12861's solution. The solution is written for T-SQL, but the concept works in any SQL db.</p>\n" }, { "answer_id": 25774531, "author": "Muposat", "author_id": 3395374, "author_profile": "https://Stackoverflow.com/users/3395374", "pm_score": 3, "selected": false, "text": "<h1>Faster Than ORDER BY RAND()</h1>\n<p>I tested this method to be much faster than <code>ORDER BY RAND()</code>, hence it runs in <strong>O(n)</strong> time, and does so impressively fast.</p>\n<p>From <a href=\"http://technet.microsoft.com/en-us/library/ms189108%28v=sql.105%29.aspx\" rel=\"noreferrer\">http://technet.microsoft.com/en-us/library/ms189108%28v=sql.105%29.aspx</a>:</p>\n<p><strong>Non-MSSQL version</strong> -- I did not test this</p>\n<pre><code>SELECT * FROM Sales.SalesOrderDetail\nWHERE 0.01 &gt;= RAND()\n</code></pre>\n<p><strong>MSSQL version:</strong></p>\n<pre><code>SELECT * FROM Sales.SalesOrderDetail\nWHERE 0.01 &gt;= CAST(CHECKSUM(NEWID(), SalesOrderID) &amp; 0x7fffffff AS float) / CAST (0x7fffffff AS int)\n</code></pre>\n<p>This will select ~1% of records. So if you need exact # of percents or records to be selected, estimate your percentage with some safety margin, then randomly pluck excess records from resulting set, using the more expensive <code>ORDER BY RAND()</code> method.</p>\n<h1>Even Faster</h1>\n<p>I was able to improve upon this method even further because I had a well-known indexed column value range.</p>\n<p>For example, if you have an indexed column with uniformly distributed integers [0..max], you can use that to randomly select N small intervals. Do this dynamically in your program to get a different set for each query run. This subset selection will be <strong>O(N)</strong>, which can many orders of magnitude smaller than your full data set.</p>\n<p>In my test I reduced the time needed to get 20 (out 20 mil) sample records from <strong>3 mins</strong> using ORDER BY RAND() down to <strong>0.0 seconds</strong>!</p>\n" }, { "answer_id": 47440872, "author": "concat", "author_id": 3925507, "author_profile": "https://Stackoverflow.com/users/3925507", "pm_score": 0, "selected": false, "text": "<p>If you need exactly <code>m</code> rows, realistically you'll generate your subset of IDs outside of SQL. Most methods require at some point to select the \"nth\" entry, and SQL tables are really not arrays at all. The assumption that the keys are consecutive in order to just join random ints between 1 and the count is also difficult to satisfy &mdash; MySQL for example doesn't support it natively, and the lock conditions are... <a href=\"https://dev.mysql.com/doc/refman/5.7/en/innodb-auto-increment-handling.html\" rel=\"nofollow noreferrer\">tricky</a>.</p>\n\n<p>Here's an <code>O(max(n, m lg n))</code>-time, <code>O(n)</code>-space solution assuming just plain BTREE keys:</p>\n\n<ol>\n<li>Fetch all values of the key column of the data table in any order into an array in your favorite scripting language in <code>O(n)</code></li>\n<li>Perform a <a href=\"https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#The_modern_algorithm\" rel=\"nofollow noreferrer\">Fisher-Yates shuffle</a>, stopping after <code>m</code> swaps, and extract the subarray <code>[0:m-1]</code> in <code>ϴ(m)</code></li>\n<li>\"Join\" the subarray with the original dataset (e.g. <code>SELECT ... WHERE id IN (&lt;subarray&gt;)</code>) in <code>O(m lg n)</code></li>\n</ol>\n\n<p>Any method that generates the random subset outside of SQL must have at least this complexity. The join can't be any faster than <code>O(m lg n)</code> with BTREE (so <code>O(m)</code> claims are fantasy for most engines) and the shuffle is bounded below <code>n</code> and <code>m lg n</code> and doesn't affect the asymptotic behavior.</p>\n\n<p>In Pythonic pseudocode:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>ids = sql.query('SELECT id FROM t')\nfor i in range(m):\n r = int(random() * (len(ids) - i))\n ids[i], ids[i + r] = ids[i + r], ids[i]\n\nresults = sql.query('SELECT * FROM t WHERE id IN (%s)' % ', '.join(ids[0:m-1])\n</code></pre>\n" }, { "answer_id": 60458147, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Select 3000 random records in Netezza:</p>\n\n<pre><code>WITH IDS AS (\n SELECT ID\n FROM MYTABLE;\n)\n\nSELECT ID FROM IDS ORDER BY mt_random() LIMIT 3000\n</code></pre>\n" }, { "answer_id": 64368133, "author": "Northernlad", "author_id": 6835923, "author_profile": "https://Stackoverflow.com/users/6835923", "pm_score": 1, "selected": false, "text": "<p>Try</p>\n<pre><code>SELECT TOP 10000 * FROM table ORDER BY NEWID()\n</code></pre>\n<p>Would this give the desired results, without being too over complicated?</p>\n" }, { "answer_id": 64612123, "author": "Zhanwen Chen", "author_id": 3853537, "author_profile": "https://Stackoverflow.com/users/3853537", "pm_score": 2, "selected": false, "text": "<p>In certain dialects like Microsoft SQL Server, PostgreSQL, and Oracle (but not MySQL or SQLite), you can do something like</p>\n<pre><code>select distinct top 10000 customer_id from nielsen.dbo.customer TABLESAMPLE (20000 rows) REPEATABLE (123);\n</code></pre>\n<p>The reason for not just doing <code>(10000 rows)</code> without the <code>top</code> is that the <code>TABLESAMPLE</code> logic gives you an extremely inexact number of rows (like sometimes 75% that, sometimes 1.25% times that), so you want to oversample and select the exact number you want. The <code>REPEATABLE (123)</code> is for providing a random seed.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249301", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20760/" ]
How do I take an efficient simple random sample in SQL? The database in question is running MySQL; my table is at least 200,000 rows, and I want a simple random sample of about 10,000. The "obvious" answer is to: ``` SELECT * FROM table ORDER BY RAND() LIMIT 10000 ``` For large tables, that's too slow: it calls `RAND()` for every row (which already puts it at O(n)), and sorts them, making it O(n lg n) at best. Is there a way to do this faster than O(n)? *Note*: As Andrew Mao points out in the comments, If you're using this approach on SQL Server, you should use the T-SQL function `NEWID()`, because RAND() [may return the same value for all rows](http://msdn.microsoft.com/en-us/library/ms177610.asp). *EDIT: 5 YEARS LATER* I ran into this problem again with a bigger table, and ended up using a version of @ignorant's solution, with two tweaks: * Sample the rows to 2-5x my desired sample size, to cheaply `ORDER BY RAND()` * Save the result of `RAND()` to an indexed column on every insert/update. (If your data set isn't very update-heavy, you may need to find another way to keep this column fresh.) To take a 1000-item sample of a table, I count the rows and sample the result down to, on average, 10,000 rows with the the frozen\_rand column: ``` SELECT COUNT(*) FROM table; -- Use this to determine rand_low and rand_high SELECT * FROM table WHERE frozen_rand BETWEEN %(rand_low)s AND %(rand_high)s ORDER BY RAND() LIMIT 1000 ``` (My actual implementation involves more work to make sure I don't undersample, and to manually wrap rand\_high around, but the basic idea is "randomly cut your N down to a few thousand.") While this makes some sacrifices, it allows me to sample the database down using an index scan, until it's small enough to `ORDER BY RAND()` again.
There's a very interesting discussion of this type of issue here: [<http://www.titov.net/2005/09/21/do-not-use-order-by-rand-or-how-to-get-random-rows-from-table/>](http://www.titov.net/2005/09/21/do-not-use-order-by-rand-or-how-to-get-random-rows-from-table/) I think with absolutely no assumptions about the table that your O(n lg n) solution is the best. Though actually with a good optimizer or a slightly different technique the query you list may be a bit better, O(m\*n) where m is the number of random rows desired, as it wouldn't necesssarily have to sort the whole large array, it could just search for the smallest m times. But for the sort of numbers you posted, m is bigger than lg n anyway. Three asumptions we might try out: 1. there is a unique, indexed, primary key in the table 2. the number of random rows you want to select (m) is much smaller than the number of rows in the table (n) 3. the unique primary key is an integer that ranges from 1 to n with no gaps With only assumptions 1 and 2 I think this can be done in O(n), though you'll need to write a whole index to the table to match assumption 3, so it's not necesarily a fast O(n). If we can ADDITIONALLY assume something else nice about the table, we can do the task in O(m log m). Assumption 3 would be an easy nice additional property to work with. With a nice random number generator that guaranteed no duplicates when generating m numbers in a row, an O(m) solution would be possible. Given the three assumptions, the basic idea is to generate m unique random numbers between 1 and n, and then select the rows with those keys from the table. I don't have mysql or anything in front of me right now, so in slightly pseudocode this would look something like: ``` create table RandomKeys (RandomKey int) create table RandomKeysAttempt (RandomKey int) -- generate m random keys between 1 and n for i = 1 to m insert RandomKeysAttempt select rand()*n + 1 -- eliminate duplicates insert RandomKeys select distinct RandomKey from RandomKeysAttempt -- as long as we don't have enough, keep generating new keys, -- with luck (and m much less than n), this won't be necessary while count(RandomKeys) < m NextAttempt = rand()*n + 1 if not exists (select * from RandomKeys where RandomKey = NextAttempt) insert RandomKeys select NextAttempt -- get our random rows select * from RandomKeys r join table t ON r.RandomKey = t.UniqueKey ``` If you were really concerned about efficiency, you might consider doing the random key generation in some sort of procedural language and inserting the results in the database, as almost anything other than SQL would probably be better at the sort of looping and random number generation required.
249,312
<p>What does the following code do? A link to something in the PHP manual would also be nice.</p> <pre><code>if ($_SERVER['SERVER_PORT'] &lt;&gt; 443) { doSomething(); } </code></pre>
[ { "answer_id": 249315, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 6, "selected": true, "text": "<p>Same as !=, \"Not equal\"</p>\n\n<pre><code>false &lt;&gt; true // operator will evaluate expression as true\nfalse != true // operator will evaluate expression as true\n</code></pre>\n\n<p>Here is some reference: <a href=\"http://www.php.net/operators.comparison\" rel=\"noreferrer\">PHP Comparison Operators</a></p>\n" }, { "answer_id": 249316, "author": "C. Broadbent", "author_id": 28859, "author_profile": "https://Stackoverflow.com/users/28859", "pm_score": 3, "selected": false, "text": "<p>It's equivalent to <code>!=</code>:</p>\n\n<p><a href=\"http://au.php.net/operators.comparison\" rel=\"nofollow noreferrer\">http://au.php.net/operators.comparison</a></p>\n\n<p>​​​​​​</p>\n" }, { "answer_id": 249317, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 3, "selected": false, "text": "<p>It's another way of saying \"not equal to\" (the <code>!=</code> operator). I think of it as the \"less than or greater than\" operator which really just means \"not equal to\".</p>\n" }, { "answer_id": 249321, "author": "indyfromoz", "author_id": 32649, "author_profile": "https://Stackoverflow.com/users/32649", "pm_score": 2, "selected": false, "text": "<p><code>$_SERVER['SERVER_PORT']</code> gets the port used by the web server to serve HTTP requests. <code>$_SERVER['SERVER_PORT'] &lt;&gt; 443</code> checks if the port is not equal to 443 (the default HTTPS port) and if not, invokes <code>doSomething()</code> </p>\n" }, { "answer_id": 249345, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 2, "selected": false, "text": "<p>Note that <code>&lt;&gt;</code> behaves as <code>!=</code> even where <code>&lt;</code> and <code>&gt;</code> are not obvious comparison operators (eg <code>$str1 &lt;&gt; $str2</code>).</p>\n" }, { "answer_id": 249390, "author": "Bob Somers", "author_id": 1384, "author_profile": "https://Stackoverflow.com/users/1384", "pm_score": 2, "selected": false, "text": "<p>Although PHP is mostly based on C-style syntax, this is one of the weird things that comes from the BASIC-style syntax world.</p>\n\n<p>Needless to say, I'd just use <code>!=</code> and be consistent with it, as <code>&lt;&gt;</code> is really never used.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18285/" ]
What does the following code do? A link to something in the PHP manual would also be nice. ``` if ($_SERVER['SERVER_PORT'] <> 443) { doSomething(); } ```
Same as !=, "Not equal" ``` false <> true // operator will evaluate expression as true false != true // operator will evaluate expression as true ``` Here is some reference: [PHP Comparison Operators](http://www.php.net/operators.comparison)
249,314
<p>I was just watching a video on MSDN Channel 9 which can be found <a href="http://channel9.msdn.com/posts/Dan/Lucian-Wischik-and-Lisa-Feigenbaum-Whats-new-in-Visual-Basic-10/" rel="noreferrer">here</a>, about some of the new features in Visual Basic 10. Now I like most of the new features, some of which have been long awaited(auto properties and Collection Initializers), one that caught my eye was the multiline lambdas like in C#. </p> <p>In the video he used an example like this:</p> <pre><code>Dim scores = {10,20,30,40,50} Dim thread as new Threading.Thread(Sub() For Each o in scores console.writeline(o) Next End Sub) </code></pre> <p>Now I like VB in all it verbosity but I'm just a bit worried that writing sub...end sub inline could get a bit messy, I can see some merit in inlining when you are writing C# when you only have to use something like c => {....} and you can cut out a lot of code.</p> <p>What are your throughts of multiline lambdas in VB?</p> <p>Would you find them useful and where?</p>
[ { "answer_id": 249325, "author": "MichaelGG", "author_id": 27012, "author_profile": "https://Stackoverflow.com/users/27012", "pm_score": 0, "selected": false, "text": "<p>Full anonymous method support in VB means you can start taking a more functional style with things. If the Sub() End Sub need to go on separate lines... that hurts. I'd hope they'd allow single-line anonymous methods, so long there was only one statement.</p>\n" }, { "answer_id": 249405, "author": "Jonathan Allen", "author_id": 5274, "author_profile": "https://Stackoverflow.com/users/5274", "pm_score": 0, "selected": false, "text": "<p>You are going to need multi-line once we get the ParallelFX library.</p>\n\n<p>For example, lets say you wanted to make this loop parallel:</p>\n\n<pre><code>For i = 0 to 100\n '12 lines of code'\nNext\n</code></pre>\n\n<p>The parallel version would be:</p>\n\n<pre><code>Parallel.For( 0, 100, sub(i)\n '12 lines of code'\n End Sub )\n</code></pre>\n\n<p>It works by turning the guts of the loop into a brand new sub. That new sub is called by N threads, N usually being the number of available cores.</p>\n" }, { "answer_id": 249446, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>I can think of two reasons off the top of my head why I love it! Been waiting too long for this.</p>\n\n<p><strong>First:</strong> </p>\n\n<pre><code> Private Sub SomeMethod()\n Dim SomeVariable as String = \"Some text.\"\n\n AddHandler SomeButton.Click, Sub()\n SomeVariable += \" Some more text\"\n MessageBox.Show(SomeVariable)\n End Sub\n</code></pre>\n\n<p><strong>Second:</strong> </p>\n\n<pre><code> Private Sub SomeMethodRunningInAnotherThread()\n Me.Dispatcher.Invoke(Normal, Sub()\n 'Do some other stuff '\n SomeTextBox.Text = \"Test\"\n End Sub)\n End Sub\n</code></pre>\n" }, { "answer_id": 249521, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 5, "selected": true, "text": "<p>Personally, I think that VB's syntax for delegates and lambdas is completely bogus. I mean, come on, <code>AddressOf</code>! This was fine in VB6. It is definitely <em>not</em> fine in a language such as VB.NET where functions <em>should</em> be treated as first-class citizens (although they really aren't, of course) and where conversion from method groups to delegates is more or less transparent.</p>\n\n<p>Now the introduction of inline functions is horribly verbose. I actually believe that the C# approach – <code>x =&gt; f(x)</code> would fare very well in VB because it shows exactly what it does. At the current state, I prefer C# for any functional programming work, which is a pity because I generally favour VB.</p>\n\n<p>Now, I really rejoice that VB finally gets multiline lambdas and statement lambdas because they're still useful sometimes (take the case of <code>Parallel.For</code>). But the syntax is messed up. The same goes for iterators, by the way (if they should make it into VB10).</p>\n" }, { "answer_id": 262444, "author": "pettys", "author_id": 27846, "author_profile": "https://Stackoverflow.com/users/27846", "pm_score": 2, "selected": false, "text": "<p>By preference I'm a C# developer, but have been using VB 9 almost exclusively for about a year now. The #1 thing about VB 9 that breaks my heart is the limited lambdas. Lambdas in VB 9 are limited in the following ways:</p>\n\n<ul>\n<li>Only one statement.</li>\n<li>They must return a value.</li>\n</ul>\n\n<p>So the ForEach method on collections will not work with lambdas, and only the very simplest of operations will work. So most of the time you have to move your logic to some other method and use AddressOf. Many times this cleaves the readability of the code in a dramatic and heartbreaking way.</p>\n\n<p>It's something that I feel many would not pick up on unless they've used anonymous methods fluently in another language that fully supports them (C#, JavaScript, etc.), rather than the crippled support they have in VB 9.</p>\n\n<p>I'm extremely relieved that they're fixing lambdas in VB 10.</p>\n" }, { "answer_id": 1568740, "author": "Adam Davis", "author_id": 2915, "author_profile": "https://Stackoverflow.com/users/2915", "pm_score": 0, "selected": false, "text": "<p>There are no easy ways to manage this:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/1568526/convert-c-statement-body-lambda-to-vb\">Convert C# statement body lambda to VB</a></p>\n\n<p>without multiline lambdas. </p>\n\n<p><em>sigh</em></p>\n\n<p>So yes, I'm anxious for this to be fully released.</p>\n\n<p>-Adam</p>\n" }, { "answer_id": 4005314, "author": "Erx_VB.NExT.Coder", "author_id": 220064, "author_profile": "https://Stackoverflow.com/users/220064", "pm_score": 2, "selected": false, "text": "<p>Same here, I love vb. Most of the time you are thinking and not actually writing code anyway, so the verbosity argument fails in my opinion, as you are usually staring at code or editing it, and imagine The time you are saving understanding your code when you read it in its verbosity in vb? Much easier and less error and bug prone as opposed to c#. </p>\n\n<p>Also, c# still has no with clause, and vb has had this even prior to the .net days.</p>\n\n<pre><code>With obj.class.methods\n\n .property = 1\n\n .attribute = 2\n\nEnd with\n</code></pre>\n\n<p>Imagine this with 10 things that need to be set? In c# you'd have to create a reference to obj.class.methods and use that for shorthand expressing, which is wasted memory and inefficient, so in that respect vb does use less memory and you are not punished for using less memory unlike with c# .</p>\n\n<p>And the \"using\" keyword argument fails since using doesn't work with most objects or objects that don't implement idisposable which is absolutely annoying.</p>\n\n<p>Then, think of all the explicit castings you have to do in c# as opposed to vb. C#errs will argue that is encourages better coding but that is nonsense, as any good developer doesn't need to explicitly cast something 500 times a day to understand that if he didn't an implicit casting would take place (as it does in vb).</p>\n\n<p>Most c#errs use it because they come from a c background, which is fine, but I find a lot of them started with it because it contains the letter c and they think its cooler because it lacks the language innovation that vb has, making it harder for the developer, and that makes them feel smarter and cooler and above everyone else - lol, they don't understand that hiding complexity at 0 cost is the ultimate goal, which is what vb can do for you. Notice the at zero cost part, as it would not be a good thing if it was at above zero cost. </p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6335/" ]
I was just watching a video on MSDN Channel 9 which can be found [here](http://channel9.msdn.com/posts/Dan/Lucian-Wischik-and-Lisa-Feigenbaum-Whats-new-in-Visual-Basic-10/), about some of the new features in Visual Basic 10. Now I like most of the new features, some of which have been long awaited(auto properties and Collection Initializers), one that caught my eye was the multiline lambdas like in C#. In the video he used an example like this: ``` Dim scores = {10,20,30,40,50} Dim thread as new Threading.Thread(Sub() For Each o in scores console.writeline(o) Next End Sub) ``` Now I like VB in all it verbosity but I'm just a bit worried that writing sub...end sub inline could get a bit messy, I can see some merit in inlining when you are writing C# when you only have to use something like c => {....} and you can cut out a lot of code. What are your throughts of multiline lambdas in VB? Would you find them useful and where?
Personally, I think that VB's syntax for delegates and lambdas is completely bogus. I mean, come on, `AddressOf`! This was fine in VB6. It is definitely *not* fine in a language such as VB.NET where functions *should* be treated as first-class citizens (although they really aren't, of course) and where conversion from method groups to delegates is more or less transparent. Now the introduction of inline functions is horribly verbose. I actually believe that the C# approach – `x => f(x)` would fare very well in VB because it shows exactly what it does. At the current state, I prefer C# for any functional programming work, which is a pity because I generally favour VB. Now, I really rejoice that VB finally gets multiline lambdas and statement lambdas because they're still useful sometimes (take the case of `Parallel.For`). But the syntax is messed up. The same goes for iterators, by the way (if they should make it into VB10).
249,330
<p>I'm writing a utility in Python that will attach changed files in Subversion to an email and send it when a subset of folders that are under source control in SVN have been changed. I am using the pysvn library to access the repository.</p> <p>I have a copy of the files on my local file system and I do an update to check if the files have changed since the last time the utility was run.</p> <p>I am at the point where I am translating the path names in SVN to the path names on my local copy.</p> <p>Currently I have written the following to do the job:</p> <pre><code>def formatPaths(self, paths): newPaths = list() for path in paths: path = path[len(self.basePath):] path = path.replace("/", "\\") newPaths.append(path) return newPaths </code></pre> <p>self.basePath would be something like "/trunk/project1" and I'm looking to just get the relative path of a subset of folders (I.e. folder1 under "/trunk/project1").</p> <p>Is this a good way to solve this problem or is there some magical function I missed?</p>
[ { "answer_id": 249444, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 0, "selected": false, "text": "<p>Hm... That would do it:</p>\n\n<pre><code>baselen = len(self.basePath)\nfor path in paths:\n path = path[baselen:].replace(\"/\", \"\\\\\")\n newPaths.append(path)\nreturn newPaths\n</code></pre>\n\n<p>If you like, you can do it like this:</p>\n\n<pre><code>baselen = len(self.basePath)\nreturn (path[baselen:].replace(\"/\", \"\\\\\") for path in paths)\n</code></pre>\n\n<p>Not calculating <code>baselen</code> in every loop iteration is also good practice.</p>\n" }, { "answer_id": 249650, "author": "gimel", "author_id": 6491, "author_profile": "https://Stackoverflow.com/users/6491", "pm_score": 3, "selected": true, "text": "<p>Stay with the slice operator, but do not change the loop variable inside the loop. for fun, try the generator expression (or keep the listcomp).</p>\n\n<pre><code>baselen = len(self.basePath)\nreturn (path[baselen:].replace(\"/\", \"\\\\\") for path in paths)\n</code></pre>\n\n<p>Edit: `lstrip()' is not relevant here. From the <a href=\"http://docs.python.org/library/stdtypes.html#string-methods\" rel=\"nofollow noreferrer\">manual</a>:</p>\n\n<blockquote>\n <p>str.lstrip([chars])</p>\n \n <p>Return a copy of the string with leading characters removed. If chars is omitted or\n None, whitespace characters are removed. If given and not None, chars must be a\n string; the characters in the string will be stripped from the beginning of the \n string this method is called on.</p>\n</blockquote>\n" }, { "answer_id": 249743, "author": "Ali Afshar", "author_id": 28380, "author_profile": "https://Stackoverflow.com/users/28380", "pm_score": 0, "selected": false, "text": "<p>Your specific solution to the path name copy is reasonable, but your general solution to the entire problem could be improved.</p>\n\n<p>I would <code>easy_install anyvc</code>, a library developed for the <a href=\"http://pida.co.uk/\" rel=\"nofollow noreferrer\">PIDA IDE</a> which is a uniform python interface into version control systems, and use it instead:</p>\n\n<pre><code>from anyvc import Subversion\nvc = Subversion('/trunk')\n\nmodified = [f.relpath for f in vc.list() if f.state != 'clean']\n\nfor f in modified:\n print f.relpath # the relative path of the file to the source root\n</code></pre>\n\n<p>Additionally, I would probably attach a diff to an email rather than the actual file. But I guess that's your choice.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249330", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1804/" ]
I'm writing a utility in Python that will attach changed files in Subversion to an email and send it when a subset of folders that are under source control in SVN have been changed. I am using the pysvn library to access the repository. I have a copy of the files on my local file system and I do an update to check if the files have changed since the last time the utility was run. I am at the point where I am translating the path names in SVN to the path names on my local copy. Currently I have written the following to do the job: ``` def formatPaths(self, paths): newPaths = list() for path in paths: path = path[len(self.basePath):] path = path.replace("/", "\\") newPaths.append(path) return newPaths ``` self.basePath would be something like "/trunk/project1" and I'm looking to just get the relative path of a subset of folders (I.e. folder1 under "/trunk/project1"). Is this a good way to solve this problem or is there some magical function I missed?
Stay with the slice operator, but do not change the loop variable inside the loop. for fun, try the generator expression (or keep the listcomp). ``` baselen = len(self.basePath) return (path[baselen:].replace("/", "\\") for path in paths) ``` Edit: `lstrip()' is not relevant here. From the [manual](http://docs.python.org/library/stdtypes.html#string-methods): > > str.lstrip([chars]) > > > Return a copy of the string with leading characters removed. If chars is omitted or > None, whitespace characters are removed. If given and not None, chars must be a > string; the characters in the string will be stripped from the beginning of the > string this method is called on. > > >
249,346
<p>I am building a utility page for a web app that I am working on. I have an element that I want to use as a "console" of sorts.</p> <p>I get entries for the console via Ajax calls (using prototype's <code>Ajax.PeriodicalUpdater</code>).</p> <p>The problem I'm having is that when I insert new lines to the bottom of the "console", the scrollbar stays in the initial position (so I always see the top lines unless I manually scroll down).</p> <p>How can I make the scrollbar automatically stay at the bottom?</p> <p>I am using prototype for a few libraries that require it in this project, so I would prefer to stick with that or regular javascript if possible.</p> <p>Just as a note, I already tried this:</p> <pre><code>onComplete: function() { $('console').scrollTop = $('console').scrollHeight; } </code></pre> <p>It <em>almost</em> works, except that it is always "one step behind", and I can't see the most recent item.</p>
[ { "answer_id": 249349, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 3, "selected": true, "text": "<pre><code>new Ajax.PeriodicalUpdater(container, url, {\n onComplete: function() {\n (function() {\n container.scrollTop = container.scrollHeight;\n }).defer();\n }\n});\n</code></pre>\n" }, { "answer_id": 249384, "author": "Bob Somers", "author_id": 1384, "author_profile": "https://Stackoverflow.com/users/1384", "pm_score": 1, "selected": false, "text": "<p>Heh, I was building almost exactly the same thing (an Ajax console) and had issues with my overflowed div not scolling all the way to the bottom.</p>\n\n<p>And Stack Overflow helped me solve it! Hope it helps you too!</p>\n\n<p><a href=\"https://stackoverflow.com/questions/13362/scrolling-overflowed-divs-with-javascript\">Scrolling Overflowed DIVs with JavaScript</a></p>\n\n<p>EDIT: My question used jQuery, but the problem isn't with the JS framework it's with the CSS attributes you're using. Basically you need get Math.max(div.scrollHeight, div.clientHeight) because some browsers are a bit buggy with those attributes.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249346", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12983/" ]
I am building a utility page for a web app that I am working on. I have an element that I want to use as a "console" of sorts. I get entries for the console via Ajax calls (using prototype's `Ajax.PeriodicalUpdater`). The problem I'm having is that when I insert new lines to the bottom of the "console", the scrollbar stays in the initial position (so I always see the top lines unless I manually scroll down). How can I make the scrollbar automatically stay at the bottom? I am using prototype for a few libraries that require it in this project, so I would prefer to stick with that or regular javascript if possible. Just as a note, I already tried this: ``` onComplete: function() { $('console').scrollTop = $('console').scrollHeight; } ``` It *almost* works, except that it is always "one step behind", and I can't see the most recent item.
``` new Ajax.PeriodicalUpdater(container, url, { onComplete: function() { (function() { container.scrollTop = container.scrollHeight; }).defer(); } }); ```
249,348
<p>I wrote this scheme code to compute one solution of the quadratic equation a<em>x2 + b</em>x + c = 0</p> <pre><code>(define (solve-quadratic-equation a b c) (define disc (sqrt (- (* b b) (* 4.0 a c)))) (/ (+ (- b) disc) (* 2.0 a))) </code></pre> <p>However, someone told me that this procedure is hard to understand. Why?</p> <p>What would a cleaned up version of this procedure look like? Please let me know why the new procedure would be easier to understand.</p> <p>Thanks</p>
[ { "answer_id": 249352, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 3, "selected": false, "text": "<p>Well, one reason is that it's all on one line. You can make it more readable using something called <strong>pretty-printing</strong>, where you break it up into multiple lines and use whitespace:</p>\n\n<pre><code>(define (solve-quadratic-equation a b c)\n (define disc (sqrt (- (* b b)\n (* 4.0 a c))))\n (/ (+ (- b) disc)\n (* 2.0 a)))\n</code></pre>\n\n<p>This way you can more clearly see the structure of the expressions.</p>\n\n<p>And here's a quote from <a href=\"http://mitpress.mit.edu/sicp/full-text/book/book.html\" rel=\"noreferrer\">SICP</a>:</p>\n\n<blockquote>\n <p>There is no limit (in principle) to the depth of such nesting and to the overall complexity of the expressions that the Lisp interpreter can evaluate. It is we humans who get confused by still relatively simple expressions such as</p>\n\n<pre><code>(+ (* 3 (+ (* 2 4) (+ 3 5))) (+ (- 10 7) 6))</code></pre>\n \n <p>which the interpreter would readily evaluate to be 57. We can help ourselves by writing such an expression in the form</p>\n\n<pre><code>(+ (* 3\n (+ (* 2 4)\n (+ 3 5)))\n (+ (- 10 7)\n 6))</code></pre>\n \n <p>following a formatting convention known as <em>pretty-printing</em>, in which each long combination is written so that the operands are aligned vertically. The resulting indentations display clearly the structure of the expression.</p>\n</blockquote>\n" }, { "answer_id": 249354, "author": "Nick Stinemates", "author_id": 4960, "author_profile": "https://Stackoverflow.com/users/4960", "pm_score": 1, "selected": false, "text": "<p>Isn't scheme all about developing a language to solve a problem? I admit I don't know much scheme, but I would add some indentation and add a square definelike so.</p>\n\n<pre><code> (define (solve-quadratic-equation a b c)\n (define square (x) (* x x) \n (define disc (sqrt (- (square b) (* 4.0 a c)))) \n (/ (+ (- b) disc) (* 2.0 a))))\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249348", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30622/" ]
I wrote this scheme code to compute one solution of the quadratic equation a*x2 + b*x + c = 0 ``` (define (solve-quadratic-equation a b c) (define disc (sqrt (- (* b b) (* 4.0 a c)))) (/ (+ (- b) disc) (* 2.0 a))) ``` However, someone told me that this procedure is hard to understand. Why? What would a cleaned up version of this procedure look like? Please let me know why the new procedure would be easier to understand. Thanks
Well, one reason is that it's all on one line. You can make it more readable using something called **pretty-printing**, where you break it up into multiple lines and use whitespace: ``` (define (solve-quadratic-equation a b c) (define disc (sqrt (- (* b b) (* 4.0 a c)))) (/ (+ (- b) disc) (* 2.0 a))) ``` This way you can more clearly see the structure of the expressions. And here's a quote from [SICP](http://mitpress.mit.edu/sicp/full-text/book/book.html): > > There is no limit (in principle) to the depth of such nesting and to the overall complexity of the expressions that the Lisp interpreter can evaluate. It is we humans who get confused by still relatively simple expressions such as > > > > ``` > (+ (* 3 (+ (* 2 4) (+ 3 5))) (+ (- 10 7) 6)) > ``` > > which the interpreter would readily evaluate to be 57. We can help ourselves by writing such an expression in the form > > > > ``` > (+ (* 3 > (+ (* 2 4) > (+ 3 5))) > (+ (- 10 7) > 6)) > ``` > > following a formatting convention known as *pretty-printing*, in which each long combination is written so that the operands are aligned vertically. The resulting indentations display clearly the structure of the expression. > > >
249,350
<p>I have seen some declaration of a union inside a struct as follows. Example code given below.</p> <p>My questions is does it help in any memory savings(typical use for which a union is used for)? I do not see the benefit. </p> <pre><code>typedef struct { int x1; unsigned int x2; ourstruct1 ov1; ourstruct1 ov2; union { struct { mystruct1 v1; mystruct2 v2; mystruct3 v3; int* ctxSC; mystruct4 v4; Bool v5; Long v6; Long v7; Long v8; Long v9; }mystr; }; }structvar1; </code></pre> <p>-AD</p>
[ { "answer_id": 249355, "author": "bog", "author_id": 20909, "author_profile": "https://Stackoverflow.com/users/20909", "pm_score": 2, "selected": false, "text": "<p>Hmm. Well, the example above seems a little strange to me--the usual reason for a union is to have two different symbolic paths into the same storage (by bytes, by words, etc). However, the example you've given has only one member of the union.</p>\n\n<p>The only thing I can think is that the code is written with an eye towards future expansion--I.E. that the union will, in subsequent versions, have additional members.</p>\n" }, { "answer_id": 249356, "author": "Greg Rogers", "author_id": 5963, "author_profile": "https://Stackoverflow.com/users/5963", "pm_score": 2, "selected": false, "text": "<p>This is not a typical use for a union at all. Unions are variant types - you can put many different kind of types into them and retrieve them. <strong>Putting only one type into a union gives you nothing</strong>, except weird looking code.</p>\n" }, { "answer_id": 249358, "author": "Ty.", "author_id": 16948, "author_profile": "https://Stackoverflow.com/users/16948", "pm_score": 0, "selected": false, "text": "<p>It would seem to me that the union isn't actually used here. I've never seen a lone struct inside a union like that either. Strange.</p>\n" }, { "answer_id": 249395, "author": "Jim Buck", "author_id": 2666, "author_profile": "https://Stackoverflow.com/users/2666", "pm_score": 0, "selected": false, "text": "<p>It's hard to say with the obfuscated names of variables and types meant to make the code anonymous, but is it possible the person that wrote it was erroneously expecting the fields inside of the mystr struct to be union'ed?</p>\n" }, { "answer_id": 250453, "author": "philant", "author_id": 18804, "author_profile": "https://Stackoverflow.com/users/18804", "pm_score": 0, "selected": false, "text": "<p>Is this code valid ? Not because the union has only one field (albeit this seems weird), but because the union is anonymous ; how do you tell the compiler you want to address in the inner struct mystr ? </p>\n\n<pre><code> structvar1 var1;\n var1.mystr.ctxSC = NULL; // compile error : structvar1 has no mystr member\n</code></pre>\n\n<p>And GCC 3.4.4 reports this as invalid ISO C. </p>\n\n<p>EDIT: <a href=\"https://stackoverflow.com/users/18882/steve-fallows\">Steve Fallows</a> gave me the answer in a comment: this is a proprietary Microsoft extension that allow seamless structure aggregation: all the fields of the \"included\" structure are considered as being part of the containing structure.</p>\n" }, { "answer_id": 251148, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 2, "selected": false, "text": "<p>To add to what <a href=\"https://stackoverflow.com/questions/249350/unions-declaration-c-code#250453\">Philippe</a> wrote: Microsoft uses this in DirectX to define its <code>D3DMATRIX</code> (and the derived structure `D3DXMATRIX) as follows:</p>\n\n<pre><code>typedef struct _D3DMATRIX {\n union {\n struct {\n float _11, _12, _13, _14;\n float _21, _22, _23, _24;\n float _31, _32, _33, _34;\n float _41, _42, _43, _44;\n\n };\n float m[4][4];\n };\n} D3DMATRIX;</code></pre>\n\n<p>This allows you to address the matrix elements either by name or by index: both <code>myMat._12</code> and <code>myMat.m[0][1]</code> refer to the second element in the first row of the matrix <code>myMat</code>. It's really just syntactic sugar, since even the most braindead compiler will optimize accesses such as <code>myMat.m[0][1]</code> into a constant offset calculation.</p>\n" }, { "answer_id": 252651, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>no you can not acheive benifit unoin should contain someother members but not only structure in.there is nothing wrong in it,but you can't get memory optimisation. </p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2759376/" ]
I have seen some declaration of a union inside a struct as follows. Example code given below. My questions is does it help in any memory savings(typical use for which a union is used for)? I do not see the benefit. ``` typedef struct { int x1; unsigned int x2; ourstruct1 ov1; ourstruct1 ov2; union { struct { mystruct1 v1; mystruct2 v2; mystruct3 v3; int* ctxSC; mystruct4 v4; Bool v5; Long v6; Long v7; Long v8; Long v9; }mystr; }; }structvar1; ``` -AD
Hmm. Well, the example above seems a little strange to me--the usual reason for a union is to have two different symbolic paths into the same storage (by bytes, by words, etc). However, the example you've given has only one member of the union. The only thing I can think is that the code is written with an eye towards future expansion--I.E. that the union will, in subsequent versions, have additional members.
249,357
<p>I am currently working on my first website. I have no idea where to start on the CSS page, or if there are any standards that I should be following.</p> <p>I would appreciate any links or first-hand advise.</p>
[ { "answer_id": 249359, "author": "wprl", "author_id": 17847, "author_profile": "https://Stackoverflow.com/users/17847", "pm_score": 2, "selected": false, "text": "<p>Not exactly beginner material, but <a href=\"http://www.alistapart.com/\" rel=\"nofollow noreferrer\">A List Apart</a> is a very interesting blog about CSS and its intricacies.</p>\n\n<p>I find the W3 School's <a href=\"http://www.w3schools.com/css/\" rel=\"nofollow noreferrer\">pages on CSS</a> great for reference.</p>\n" }, { "answer_id": 249362, "author": "Ty.", "author_id": 16948, "author_profile": "https://Stackoverflow.com/users/16948", "pm_score": 2, "selected": false, "text": "<p>This is a decent overview:</p>\n\n<p><a href=\"http://www.onlinetools.org/articles/cssguides.html\" rel=\"nofollow noreferrer\">http://www.onlinetools.org/articles/cssguides.html</a></p>\n" }, { "answer_id": 249387, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 6, "selected": true, "text": "<p>An error that beginners make quite often:</p>\n<p>CSS is semantic as well. Try to express concepts, not formats. Contrived example:</p>\n<h3>Wrong:</h3>\n<pre><code>div.red\n{\n color: red;\n}\n</code></pre>\n<p>as opposed to:</p>\n<h3>Good:</h3>\n<pre><code>div.error\n{\n color: red;\n}\n</code></pre>\n<p>CSS should be the formatting companion for the concepts you use on your web site, so they should be reflected in it. You will be much more flexible this way.</p>\n" }, { "answer_id": 249407, "author": "cowgod", "author_id": 6406, "author_profile": "https://Stackoverflow.com/users/6406", "pm_score": 1, "selected": false, "text": "<p>The <a href=\"http://www.westciv.com/style_master/academy/css_tutorial/index.html\" rel=\"nofollow noreferrer\">Complete CSS Guide on westciv.com</a> has an exhaustive amount of information on CSS. It's a great place to start diving in.</p>\n" }, { "answer_id": 249409, "author": "Franci Penov", "author_id": 17028, "author_profile": "https://Stackoverflow.com/users/17028", "pm_score": 4, "selected": false, "text": "<p>Aside from the great resources pointed in the other answers, here are some tips to structure the way you work on the CSS:</p>\n\n<p>Do the work in the following order...</p>\n\n<ol>\n<li>Lay out the semantic structure of your page in HTML. Make sure it's right without any CSS.\n\n<ul>\n<li>Create the basic layout of the page in a CSS - columns, headers, floating boxes.</li>\n<li>Add typography - fonts, sizes and colors.</li>\n<li>Add the graphical elements - background pictures, logos and so on</li>\n</ul></li>\n</ol>\n\n<p>Put a link on your page to the <a href=\"http://jigsaw.w3.org/css-validator/check/referer\" rel=\"noreferrer\">W3C CSS validator</a> (if your site is visible from the internet) and keep hitting it every so often.</p>\n\n<p>Keep all your styles outside of the HTML.</p>\n\n<p>It's good to have IE6/7/8, FF2/3 and Chrome/Safari. Opera would be nice too. Keep changing the browser you open your page in while working (unless you're digging into a particular browser issue :-)).</p>\n\n<p>Add comments what each rule does and why. Keep the dev version of the CSS checked in and once you're done, then remove comments and whitespaces and compress multiple rules into one for production.</p>\n\n<p><strong>Update</strong>: As Bobby Jack mentioned, I missed to mention the debugging tools. You can use <a href=\"http://www.microsoft.com/downloads/details.aspx?FamilyId=E59C3964-672D-4511-BB3E-2D5E1DB91038&amp;displaylang=en\" rel=\"noreferrer\">IE Developer Toolbar</a> (for IE) or <a href=\"http://getfirebug.com/\" rel=\"noreferrer\">Firebug</a> (for FF) or the integrated Inspection tools in Chrome to inspect which rules are applied to particular element, or modify the style of an element on the fly.</p>\n" }, { "answer_id": 249410, "author": "cofiem", "author_id": 31567, "author_profile": "https://Stackoverflow.com/users/31567", "pm_score": 2, "selected": false, "text": "<p>My first tip would be to always use only external style sheets - try to avoid inline or header styles.</p>\n\n<p>Use classes and ids as much as possible.</p>\n\n<p>I second the suggestion for <a href=\"http://www.alistapart.com/\" rel=\"nofollow noreferrer\">A List Apart</a></p>\n\n<p>Although not very pretty, and sometimes a little old, <a href=\"http://htmlhelp.com/reference/css/style-html.html\" rel=\"nofollow noreferrer\">HTML Help by WDG</a> has some good references.</p>\n\n<p><a href=\"http://www.quirksmode.org/css/contents.html\" rel=\"nofollow noreferrer\">Quirksmode.org</a> has a great css compatibility table.</p>\n" }, { "answer_id": 249518, "author": "Gene", "author_id": 22673, "author_profile": "https://Stackoverflow.com/users/22673", "pm_score": 2, "selected": false, "text": "<p>You've already gotten a good set of answers regarding your question put here is a point you may find usefull.</p>\n\n<p>Use Firefox with Firebug extension. If you don't have firefox I recommend you install it even if it's just for this. Firebug allows you to select element from the page and shows you th applied css. Then you can edit this css with the fire bug without any page reloads. Once you're happy with a style you can easily copy the definitions from firbug to your css editor.</p>\n\n<p>At least for me firebug is an absolute necessity when working with styles.</p>\n\n<p>Couple of tips for the css itself. When defining your styles use id's only when the element in question is unique. That way your styles are reusable. Use hierarchical definitions eg.\n<code>#header .navigationElement a{color:red;}</code> and <code>#footer .navigationElement a{color:black;}</code> That way you can move youre html code around and the correct style is applied automaticly.</p>\n" }, { "answer_id": 251294, "author": "Andy Ford", "author_id": 17252, "author_profile": "https://Stackoverflow.com/users/17252", "pm_score": 2, "selected": false, "text": "<p>Have a look at \n<a href=\"http://natbat.net/2008/Sep/28/css-systems/\" rel=\"nofollow noreferrer\">CSS Systems for writing maintainable CSS</a> by Natalie Downe of <a href=\"http://clearleft.com/\" rel=\"nofollow noreferrer\">ClearLeft</a>. There are a lot of great concepts in her presentation (I recommend downloading the PDF because her notes are pretty detailed).</p>\n\n<p>I think her presentation is aimed at full time CSS devs more so than beginners, but even beginners could take a lot away from it.</p>\n" }, { "answer_id": 251348, "author": "Nathan Long", "author_id": 4376, "author_profile": "https://Stackoverflow.com/users/4376", "pm_score": 3, "selected": false, "text": "<p>You can save yourself a lot of headache by <strong>understanding specificity</strong>. When you set a rule for something, if there is a conflicting rule, <strong>specificity decides which rule wins</strong>.</p>\n\n<p>A quick (incomplete) rundown: </p>\n\n<p>An element-wide rule (like <code>p {color:green;}</code>) will be trumped by:<br>\nA class-specific rule (like <code>p.sidenote {color: blue;}</code>), which will be trumped by:<br>\nAn id-specific rule (like <code>p#final {color: red;}</code>), which will be trumped by:<br>\nAn inline declaration (like <code>&lt;p style=\"color: orange;\"&gt;</code>), which will be trumped by:<br>\nAn important rule (like <code>p#final {color: inherit !important;}</code>)</p>\n\n<p>...all of which can be trumped by the user's rules.</p>\n\n<p>The interactions can be complex, but there are mathematic rules underlying them. For a more complete treatment, see Chapter 3 of Eric Meyer's \"CSS: The Definitive Guide.\"</p>\n\n<p>To recap: <strong>if you set a rule and it doesn't seem to affect anything, you've probably got a conflicting rule.</strong> To understand why one rule beats the other, learn about specificity.</p>\n" }, { "answer_id": 251415, "author": "activout.se", "author_id": 20444, "author_profile": "https://Stackoverflow.com/users/20444", "pm_score": 2, "selected": false, "text": "<p>I just have to mention <a href=\"http://www.csszengarden.com/\" rel=\"nofollow noreferrer\">css Zen Garden</a> as a source of inspiration.</p>\n" }, { "answer_id": 251422, "author": "Ryan Rodemoyer", "author_id": 1444511, "author_profile": "https://Stackoverflow.com/users/1444511", "pm_score": 2, "selected": false, "text": "<p>If this is your first time, good luck!</p>\n\n<p>I'm not sure that as a beginner you need extensive or exhaustive resources. Take things slow and do everything you can to keep your code <em>readable</em>. Spacing, spacing, spacing.</p>\n\n<p>Use external style sheets (someone said above) and as good of an idea as it sounds now, do not keep adding new style sheets for different sections of the site. It will make your life so much easier down the road.</p>\n" }, { "answer_id": 251568, "author": "sliderhouserules", "author_id": 31385, "author_profile": "https://Stackoverflow.com/users/31385", "pm_score": 2, "selected": false, "text": "<p>Well if this is your first website and you're trying to go the CSS route then you should go read up on CSS layout and CSS box model. Understand how to use block elements to do your layout and stay away from tables for layout.</p>\n\n<p>The other thing I'd recommend is you use FireFox for all primary development and make your site work and look how you want it to in FF. <em>Then</em> fire up IE and fix any problems that quirky IE has. You will end up with a much cleaner site and much cleaner CSS if you do it this way.</p>\n" }, { "answer_id": 251712, "author": "Bryan M.", "author_id": 4636, "author_profile": "https://Stackoverflow.com/users/4636", "pm_score": 4, "selected": false, "text": "<p>Resist the urge to over-specify class or id names. Use contextual or descendent selectors. This let's you easily define styles for areas of your page, but save on the sanity of having to manage and remember tons of names. For example:</p>\n\n<pre><code>&lt;ul id=\"nav\"&gt;\n &lt;li class=\"navItem\"&gt;&lt;span class=\"itemText\"&gt;Nav Item&lt;/span&gt;&lt;/li&gt;\n &lt;li class=\"navItem\"&gt;&lt;span class=\"itemText\"&gt;Nav Item&lt;/span&gt;&lt;/li&gt;\n&lt;/ul&gt;\n\n#nav { }\n#nav .navItem { }\n#nav .itemText { }\n</code></pre>\n\n<p>This is needlessly complex, and you'll find yourself quickly running out of good semantic descriptions. You'd be better off with something like:</p>\n\n<pre><code>&lt;ul id=\"nav\"&gt;\n &lt;li&gt;&lt;span&gt;Nav Item&lt;/span&gt;&lt;/li&gt;\n &lt;li&gt;&lt;span&gt;Nav Item&lt;/span&gt;&lt;/li&gt;\n&lt;/ul&gt;\n\n#nav {}\n#nav li {}\n#nav li span {}\n</code></pre>\n" }, { "answer_id": 255727, "author": "Gene T", "author_id": 413049, "author_profile": "https://Stackoverflow.com/users/413049", "pm_score": 1, "selected": false, "text": "<p>i learned what i need to know from Mc Farland's Missing Manual (Oreilly book), and by staring at a <a href=\"http://oreilly.com/catalog/9780596527440/index.html\" rel=\"nofollow noreferrer\">sample rails' app's</a> stylesheet. That works pretty well, google \"example / sample projects / app / repositories\" for PHP, ASP.net, whatever you're using.</p>\n" }, { "answer_id": 257604, "author": "codeinthehole", "author_id": 32640, "author_profile": "https://Stackoverflow.com/users/32640", "pm_score": 1, "selected": false, "text": "<p>If you use a reset script - it'll iron out some of the quirks between different browsers. Doing so has made my life easier.</p>\n\n<p>I've seen some people swear by simply using </p>\n\n<pre><code>* { padding: 0; margin: 0; }\n</code></pre>\n\n<p>But you can also use more thorough implementations - like the one in the YUI library... <a href=\"http://developer.yahoo.com/yui/reset/\" rel=\"nofollow noreferrer\">http://developer.yahoo.com/yui/reset/</a></p>\n\n<p>When it comes to testing your site renders - browsershots.org is pretty useful.</p>\n\n<p>The webdev firefox plugin is brilliant - CTRL+SHIFT+E allows you to edit css, and see changes on the fly. If you CTRL+F, you can also hover yr mouse over an element to find out what it is.</p>\n\n<p>To add to the sites other people have mentioned - I've found <a href=\"http://css-discuss.incutio.com\" rel=\"nofollow noreferrer\">http://css-discuss.incutio.com</a> useful. Freenode #css is handy too.</p>\n" }, { "answer_id": 257663, "author": "Josh Hunt", "author_id": 2592, "author_profile": "https://Stackoverflow.com/users/2592", "pm_score": 2, "selected": false, "text": "<p>Alot of people have some excellent suggestions. I would like to second what codeinthewhole said.</p>\n\n<p>I would strongly recommend using a <a href=\"http://massiveatom.com/factoider/css/reset.css\" rel=\"nofollow noreferrer\">reset.css</a> style-sheet:</p>\n\n<pre><code>*{margin:0;padding:0}iframe,a img,fieldset,form,table{border:0}h6,h5,h4,h3,h2,h1,caption,th,td{font-size:100%;font-weight:normal}dd,dt,li,dl,ol,ul{list-style:none}legend{color:#000}button,select,textarea,input{font:100% serif}table{border-collapse:collapse}caption,th,td{text-align:left}p, h1{margin:0;padding:0;bording:0}\n</code></pre>\n\n<p>Either copy and paste or just save the one i linked to.</p>\n\n<p>Also, a mistake i used in my early days was over use of <code>&lt;div id=\"\"&gt;</code> apposed to <code>&lt;div class=\"\"&gt;</code>. An id=\"\" is only supposed to be used once (never have two <code>&lt;div id=\"content\"&gt;</code>'s), whereas you can have thousands of class=\"\" (like <code>&lt;div class=\"box\"&gt;</code>). </p>\n\n<p>And besides, having more than one id with the same name isnt valid html</p>\n" }, { "answer_id": 9539207, "author": "John Magnolia", "author_id": 560287, "author_profile": "https://Stackoverflow.com/users/560287", "pm_score": 1, "selected": false, "text": "<p>I have been building websites for 5 years now and still learn a lot by reading this every so often: <a href=\"http://code.google.com/speed/page-speed/docs/rendering.html\" rel=\"nofollow\">http://code.google.com/speed/page-speed/docs/rendering.html</a></p>\n\n<p>Also check out <a href=\"http://www.zeldman.com\" rel=\"nofollow\">http://www.zeldman.com</a> blog on CSS. This guy is a legend in the web world. </p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249357", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2598/" ]
I am currently working on my first website. I have no idea where to start on the CSS page, or if there are any standards that I should be following. I would appreciate any links or first-hand advise.
An error that beginners make quite often: CSS is semantic as well. Try to express concepts, not formats. Contrived example: ### Wrong: ``` div.red { color: red; } ``` as opposed to: ### Good: ``` div.error { color: red; } ``` CSS should be the formatting companion for the concepts you use on your web site, so they should be reflected in it. You will be much more flexible this way.
249,374
<p>Is anyone familiar with this?</p> <blockquote> <p>Write a procedure that takes as inputs a procedure that computes f and a positive integer n and returns the procedure that computes the nth repeated application of f. The procedure should be able to be used as follows:</p> <pre><code>((repeated square 2) 5) 625 </code></pre> </blockquote> <p>I know that the following code I've created for the composition of functions will help make the solution simpler, but I'm not sure where to go from here:</p> <pre><code>(define (compose f g) (lambda (x) (f (g x)))) </code></pre>
[ { "answer_id": 249490, "author": "Matthias Benkard", "author_id": 15517, "author_profile": "https://Stackoverflow.com/users/15517", "pm_score": 1, "selected": false, "text": "<p>Well, you probably want something like this, right?</p>\n\n<pre><code>((repeated square 3) 5)\n-&gt; (square ((repeated square 2) 5))\n-&gt; (square (square ((repeated square 1) 5)))\n-&gt; (square (square (square ((repeated square 0) 5))))\n-&gt; (square (square (square (identity 5))))\n</code></pre>\n\n<p>(I don't know whether <code>identity</code> is predefined in Scheme. If not, it's easy to write.)</p>\n\n<p>Now, this is not directly reproducible because you can't magically enclose code outside of the call to <code>repeated</code> with arbitrary stuff. However, what do these reduction steps look like when rewritten using <code>compose</code>? Can you make out a pattern in the resulting list of steps and reproduce it?</p>\n" }, { "answer_id": 956173, "author": "Mark Probst", "author_id": 80410, "author_profile": "https://Stackoverflow.com/users/80410", "pm_score": 0, "selected": false, "text": "<pre><code>(define (repeated f n)\n (if (zero? n)\n identity\n (lambda (x) ((repeated f (- n 1)) (f x)))))\n</code></pre>\n\n<p>or, if you insist on using \"compose\":</p>\n\n<pre><code>(define (repeated f n)\n (if (zero? n)\n identity\n (compose (repeated f (- n 1)) f)))\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249374", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30622/" ]
Is anyone familiar with this? > > Write a procedure that takes as inputs > a procedure that computes f and a > positive integer n and returns the > procedure that computes the nth > repeated application of f. The > procedure should be able to be used as > follows: > > > > ``` > ((repeated square 2) 5) > 625 > > ``` > > I know that the following code I've created for the composition of functions will help make the solution simpler, but I'm not sure where to go from here: ``` (define (compose f g) (lambda (x) (f (g x)))) ```
Well, you probably want something like this, right? ``` ((repeated square 3) 5) -> (square ((repeated square 2) 5)) -> (square (square ((repeated square 1) 5))) -> (square (square (square ((repeated square 0) 5)))) -> (square (square (square (identity 5)))) ``` (I don't know whether `identity` is predefined in Scheme. If not, it's easy to write.) Now, this is not directly reproducible because you can't magically enclose code outside of the call to `repeated` with arbitrary stuff. However, what do these reduction steps look like when rewritten using `compose`? Can you make out a pattern in the resulting list of steps and reproduce it?
249,375
<p>How do you programmatically set a DataContext that specifies the selected item of a list? </p> <p>More simply, how do you reproduce this type of binding in code?</p> <pre><code>&lt;StackPanel&gt; &lt;ListBox Name="listBox1" /&gt; &lt;TextBox Name="textBox1" DataContext="{Binding ElementName=listBox1, Path=SelectedItem}" /&gt; &lt;/StackPanel&gt; </code></pre>
[ { "answer_id": 249378, "author": "Ty.", "author_id": 16948, "author_profile": "https://Stackoverflow.com/users/16948", "pm_score": 4, "selected": true, "text": "<p>You need to set a Name for the textbox so you can refer to it in code. Then you should just be able to assign an object to the DataContext property. You can create a data binding programatically like so:</p>\n\n<pre><code>Binding binding = new Binding();\nbinding.ElementName = \"listBox1\";\nbinding.Path = new PropertyPath(\"SelectedItem\");\nbinding.Mode = BindingMode.OneWay;\ntxtMyTextBox.SetBinding(TextBox.TextProperty, binding);\n</code></pre>\n" }, { "answer_id": 249386, "author": "Toji", "author_id": 25968, "author_profile": "https://Stackoverflow.com/users/25968", "pm_score": 1, "selected": false, "text": "<p>Wow, sometimes you just have to spell the question out to get that extra nudge in the right direction, huh?</p>\n\n<p>This code works for me:</p>\n\n<pre><code>Binding b = new Binding();\nb.Path = new PropertyPath(ListBox.SelectedItemProperty);\nb.Source = listBox1;\ntextBox1.SetBinding(TextBox.DataContextProperty, b);\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249375", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25968/" ]
How do you programmatically set a DataContext that specifies the selected item of a list? More simply, how do you reproduce this type of binding in code? ``` <StackPanel> <ListBox Name="listBox1" /> <TextBox Name="textBox1" DataContext="{Binding ElementName=listBox1, Path=SelectedItem}" /> </StackPanel> ```
You need to set a Name for the textbox so you can refer to it in code. Then you should just be able to assign an object to the DataContext property. You can create a data binding programatically like so: ``` Binding binding = new Binding(); binding.ElementName = "listBox1"; binding.Path = new PropertyPath("SelectedItem"); binding.Mode = BindingMode.OneWay; txtMyTextBox.SetBinding(TextBox.TextProperty, binding); ```
249,388
<p>I'm having trouble getting pictures supported with PIL - it throws me this:</p> <pre><code>IOError: decoder jpeg not available </code></pre> <p>I installed PIL from binary, not realizing I needed libjpeg.</p> <p>I installed libjpeg and freetype2 through fink. </p> <p>I tried to reinstall PIL using instructions from <a href="http://timhatch.com/" rel="nofollow noreferrer">http://timhatch.com/</a> (bottom of the page)</p> <ul> <li>Download PIL 1.1.6 source package and have the Developer Tools already installed</li> <li><p>Patch setup.py with this patch so it can find the Freetype you already have.</p> <p><code>patch -p0 &lt; leopard_freetype2.diff</code></p></li> <li>sudo apt-get install libjpeg if you have fink (otherwise, build by hand and adjust paths)</li> </ul> <p>But I'm still getting the same error. </p> <p>I'm on Leopard PPC. </p>
[ { "answer_id": 249406, "author": "Doug Miller", "author_id": 3431280, "author_profile": "https://Stackoverflow.com/users/3431280", "pm_score": 0, "selected": false, "text": "<p>Is the python path still looking at the old binary version of libjpeg?</p>\n\n<p>You will need to modify it to point to the new place if it is.</p>\n\n<p>When you compiled the new version of the PIL did it say that it found libjpeg? It will compile happily without it (iirc) and the first sign of trouble you will see is at include time.</p>\n\n<p>You will need to adjust the path at ./configure time.</p>\n\n<p>The diff might just not work for you. You should test some more and then perhaps file a bug.</p>\n" }, { "answer_id": 249414, "author": "ayaz", "author_id": 23191, "author_profile": "https://Stackoverflow.com/users/23191", "pm_score": 1, "selected": false, "text": "<p>I had the similar 'jpeg decoder problem' recently when deploying a django project on a product RHEL box that required PIL. I downloaded PIL, and ran 'python setup.py install' instantly, and was happy that everything was working, until I bumped into the problem. Solution: libjpeg was already installed on the system, so I installed libjpeg-devel. I went back into the source of PIL and ran 'python setup.py build', at the end of which, in the output where it shows whether PIL configure was able to detect support for jpeg, gif, freetype, etc, it said that jpeg support was ok. After installing PIL, it worked fine.</p>\n" }, { "answer_id": 1252888, "author": "William Knight", "author_id": 19125, "author_profile": "https://Stackoverflow.com/users/19125", "pm_score": 1, "selected": false, "text": "<p>I had the same problem and this guy's post provided the solution for me:</p>\n\n<p>rm the PIL subdir and the PIL.pth file in the Imaging-1.1.6 subdir</p>\n\n<p>full details here:</p>\n\n<p><a href=\"http://blog.tlensing.org/2008/12/04/kill-pil-%E2%80%93-the-python-imaging-library-headache/\" rel=\"nofollow noreferrer\">http://blog.tlensing.org/2008/12/04/kill-pil-%E2%80%93-the-python-imaging-library-headache/</a></p>\n\n<p>After doing this, the selftest.py worked fine. I should also note that I am using the macports version of the jpeg library and I had already specified the JPEG_ROOT to point to the include and lib paths in my macports root</p>\n" }, { "answer_id": 1475112, "author": "Tim Hatch", "author_id": 98182, "author_profile": "https://Stackoverflow.com/users/98182", "pm_score": 0, "selected": false, "text": "<p>If you build with libjpeg, but selftest fails, you probably have another install of PIL that's confusing things. Try installing it, and see if selftest works then.</p>\n\n<p>Also the direct link to the instructions referenced in the OP is <a href=\"http://timhatch.com/ark/2008/08/12/quick-howto-for-pil-on-leopard\" rel=\"nofollow noreferrer\" title=\"Quick Howto for PIL on Leopard\">here</a></p>\n" }, { "answer_id": 4533995, "author": "Walty Yeung", "author_id": 176423, "author_profile": "https://Stackoverflow.com/users/176423", "pm_score": 0, "selected": false, "text": "<p>I have stuck to this problem for quite a few hours today. And my advice is do NOT do trial and error again and again, unless u could fix the problem in first 15 minutes.</p>\n\n<p>there are a few tools for you to diagnose the problem:</p>\n\n<p>1.check the if jpeg lib architcture matches your machine architecture:</p>\n\n<pre><code>file /usr/local/lib/libjpeg.7.dylib \n</code></pre>\n\n<p>2.check if the _imaging.so acutally linked to your compiled jpeg lib</p>\n\n<pre><code>cd ImageSrc\n\npython setup.py build_ext -i\n\notool -L PIL/_imaging.so \n</code></pre>\n\n<p>3.try to import _imaging.so and see what's the problem</p>\n\n<pre><code>cd PIL\n\npython\n\nimport _imaging\n</code></pre>\n\n<p>4.finally, try to remove all previous installed PIL* from python \"site-package\" directory to make sure set up does work</p>\n\n<pre><code>python setup.py install\n</code></pre>\n\n<p>For me, it's due to I am using 32 bit python on snow leopard, and solved the problem by install jpeg lib in this way:</p>\n\n<pre><code>./configure CFLAGS=\"-arch i386\" --enable-shared --enable-static\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249388", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20824/" ]
I'm having trouble getting pictures supported with PIL - it throws me this: ``` IOError: decoder jpeg not available ``` I installed PIL from binary, not realizing I needed libjpeg. I installed libjpeg and freetype2 through fink. I tried to reinstall PIL using instructions from <http://timhatch.com/> (bottom of the page) * Download PIL 1.1.6 source package and have the Developer Tools already installed * Patch setup.py with this patch so it can find the Freetype you already have. `patch -p0 < leopard_freetype2.diff` * sudo apt-get install libjpeg if you have fink (otherwise, build by hand and adjust paths) But I'm still getting the same error. I'm on Leopard PPC.
I had the similar 'jpeg decoder problem' recently when deploying a django project on a product RHEL box that required PIL. I downloaded PIL, and ran 'python setup.py install' instantly, and was happy that everything was working, until I bumped into the problem. Solution: libjpeg was already installed on the system, so I installed libjpeg-devel. I went back into the source of PIL and ran 'python setup.py build', at the end of which, in the output where it shows whether PIL configure was able to detect support for jpeg, gif, freetype, etc, it said that jpeg support was ok. After installing PIL, it worked fine.
249,392
<p>How would I implement a binary search using just an array? </p>
[ { "answer_id": 249404, "author": "mmcdole", "author_id": 2635, "author_profile": "https://Stackoverflow.com/users/2635", "pm_score": 6, "selected": true, "text": "<p>Ensure that your array is sorted since this is the crux of a binary search. </p>\n\n<p>Any indexed/random-access data structure can be binary searched. So when you say using \"just an array\", I would say arrays are the most basic/common data structure that a binary search is employed on. </p>\n\n<p>You can do it recursively (easiest) or iteratively. Time complexity of a binary search is O(log N) which is considerably faster than a linear search of checking each element at O(N). Here are some examples from <a href=\"http://en.wikipedia.org/wiki/Binary_search\" rel=\"noreferrer\">Wikipedia: Binary Search Algorithm</a>:</p>\n\n<p>Recursive: </p>\n\n<pre><code>BinarySearch(A[0..N-1], value, low, high) { \n if (high &lt; low) \n return -1 // not found \n mid = low + ((high - low) / 2) \n if (A[mid] &gt; value) \n return BinarySearch(A, value, low, mid-1) \n else if (A[mid] &lt; value) \n return BinarySearch(A, value, mid+1, high) \n else\n return mid // found\n }\n</code></pre>\n\n<p>Iterative:</p>\n\n<pre><code> BinarySearch(A[0..N-1], value) {\n low = 0\n high = N - 1\n while (low &lt;= high) {\n mid = low + ((high - low) / 2)\n if (A[mid] &gt; value)\n high = mid - 1\n else if (A[mid] &lt; value)\n low = mid + 1\n else\n return mid // found\n }\n return -1 // not found\n}\n</code></pre>\n" }, { "answer_id": 255007, "author": "Jed", "author_id": 33208, "author_profile": "https://Stackoverflow.com/users/33208", "pm_score": 0, "selected": false, "text": "<p>The single comparison version is fast and concise</p>\n\n<pre><code>int bsearch_double(const double a[], int n, double v) {\n int low = 0, mid;\n while (n - low &gt; 1) {\n mid = low + (n - low) / 2;\n if (v &lt; a[mid]) n = mid;\n else low = mid;\n }\n return (low &lt; n &amp;&amp; a[low] == v) ? low : -1;\n}\n</code></pre>\n" }, { "answer_id": 39693211, "author": "Mohammad", "author_id": 5475941, "author_profile": "https://Stackoverflow.com/users/5475941", "pm_score": 0, "selected": false, "text": "<p>It depends if you have repetition of one element in your array or no and if you care about multiple findings or not. I have two methods in this implementation. One of them returns only first finding, but the other one returns all findings of the key. </p>\n\n<pre><code>import java.util.Arrays;\n\npublic class BinarySearchExample {\n\n //Find one occurrence\n public static int indexOf(int[] a, int key) {\n int lo = 0;\n int hi = a.length - 1;\n while (lo &lt;= hi) {\n // Key is in a[lo..hi] or not present.\n int mid = lo + (hi - lo) / 2;\n if (key &lt; a[mid]) hi = mid - 1;\n else if (key &gt; a[mid]) lo = mid + 1;\n else return mid;\n }\n return -1;\n }\n\n //Find all occurrence\n public static void PrintIndicesForValue(int[] numbers, int target) {\n if (numbers == null)\n return;\n\n int low = 0, high = numbers.length - 1;\n // get the start index of target number\n int startIndex = -1;\n while (low &lt;= high) {\n int mid = (high - low) / 2 + low;\n if (numbers[mid] &gt; target) {\n high = mid - 1;\n } else if (numbers[mid] == target) {\n startIndex = mid;\n high = mid - 1;\n } else\n low = mid + 1;\n }\n\n // get the end index of target number\n int endIndex = -1;\n low = 0;\n high = numbers.length - 1;\n while (low &lt;= high) {\n int mid = (high - low) / 2 + low;\n if (numbers[mid] &gt; target) {\n high = mid - 1;\n } else if (numbers[mid] == target) {\n endIndex = mid;\n low = mid + 1;\n } else\n low = mid + 1;\n }\n\n if (startIndex != -1 &amp;&amp; endIndex != -1){\n System.out.print(\"All: \");\n for(int i=0; i+startIndex&lt;=endIndex;i++){\n if(i&gt;0)\n System.out.print(',');\n System.out.print(i+startIndex);\n }\n }\n }\n\n public static void main(String[] args) {\n\n // read the integers from a file\n int[] arr = {23,34,12,24,266,1,3,66,78,93,22,24,25,27};\n Boolean[] arrFlag = new Boolean[arr.length];\n Arrays.fill(arrFlag,false);\n\n // sort the array\n Arrays.sort(arr);\n\n //Search\n System.out.print(\"Array: \");\n for(int i=0; i&lt;arr.length; i++)\n if(i != arr.length-1){\n System.out.print(arr[i]+\",\");\n }else{\n System.out.print(arr[i]);\n }\n\n System.out.println(\"\\nOnly one: \"+indexOf(arr,24));\n PrintIndicesForValue(arr,24);\n\n }\n\n}\n</code></pre>\n\n<p>For more information, please visit <a href=\"https://github.com/m-vahidalizadeh/foundations/blob/master/src/algorithms/BinarySearchExample.java\" rel=\"nofollow\">https://github.com/m-vahidalizadeh/foundations/blob/master/src/algorithms/BinarySearchExample.java</a>. I hope it helps.</p>\n" }, { "answer_id": 50189125, "author": "user7258708", "author_id": 7258708, "author_profile": "https://Stackoverflow.com/users/7258708", "pm_score": 0, "selected": false, "text": "<p>Did implement below code in Java,simple and fast\n /**\n * Binary Search using Recursion\n * @author asharda\n *\n */\n public class BinSearch {</p>\n\n<pre><code> /**\n * Simplistic BInary Search using Recursion\n * @param arr\n * @param low\n * @param high\n * @param num\n * @return int\n */\n public int binSearch(int []arr,int low,int high,int num)\n {\n int mid=low+high/2;\n if(num &gt;arr[high] || num &lt;arr[low])\n {\n return -1;\n }\n\n while(low&lt;high)\n {\n if(num==arr[mid])\n {\n return mid;\n\n }\n else if(num&lt;arr[mid])\n {\n return binSearch(arr,low,high-1, num);\n }\n\n else if(num&gt;arr[mid])\n {\n return binSearch(arr,low+1,high, num);\n }\n\n }//end of while\n\n return -1;\n }\n\n public static void main(String args[])\n {\n int arr[]= {2,4,6,8,10};\n BinSearch s=new BinSearch();\n int n=s.binSearch(arr, 0, arr.length-1, 10);\n String result= n&gt;1?\"Number found at \"+n:\"Number not found\";\n System.out.println(result);\n }\n}\n</code></pre>\n" }, { "answer_id": 50545530, "author": "Lior Elrom", "author_id": 1843451, "author_profile": "https://Stackoverflow.com/users/1843451", "pm_score": 2, "selected": false, "text": "<h2>Binary Search in Javascript (ES6)</h2>\n\n<p><em>(If anyone needs)</em></p>\n\n<p><strong>Bottom-up:</strong></p>\n\n<pre><code>function binarySearch (arr, val) {\n let start = 0;\n let end = arr.length - 1;\n let mid;\n\n while (start &lt;= end) {\n mid = Math.floor((start + end) / 2);\n\n if (arr[mid] === val) {\n return mid;\n }\n if (val &lt; arr[mid]) {\n end = mid - 1;\n } else {\n start = mid + 1;\n }\n }\n return -1;\n}\n</code></pre>\n\n<p><strong>Recursion</strong>:</p>\n\n<pre><code>function binarySearch(arr, val, start = 0, end = arr.length - 1) {\n const mid = Math.floor((start + end) / 2);\n\n if (val === arr[mid]) {\n return mid;\n }\n if (start &gt;= end) {\n return -1;\n }\n return val &lt; arr[mid]\n ? binarySearch(arr, val, start, mid - 1)\n : binarySearch(arr, val, mid + 1, end);\n}\n</code></pre>\n" }, { "answer_id": 68149436, "author": "bhargav3vedi", "author_id": 6763678, "author_profile": "https://Stackoverflow.com/users/6763678", "pm_score": 0, "selected": false, "text": "<p>Here is simple solution in python programming language:</p>\n<pre><code>def bin(search, h, l):\n mid = (h+l)//2\n if m[mid] == search:\n return mid\n else:\n if l == h:\n return -1\n elif search &gt; m[mid]:\n l = mid+1\n return bin(search, h, l)\n elif search &lt; m[mid]:\n h = mid-1\n return bin(search, h, l)\n \nm = [1,2,3,4,5,6,7,8]\ntot = len(m)\nprint(bin(10, len(m)-1, 0))\n</code></pre>\n<p>Here is the process :</p>\n<ul>\n<li>get mid point</li>\n<li>if mid point == search return mid point</li>\n<li>else if higher and lower points are same then return -1</li>\n<li>if search value is greater than mid point then make mid point+1 as lower value</li>\n<li>if search value is less than mid point then make mid point-1 as higher value</li>\n</ul>\n" }, { "answer_id": 68322246, "author": "qulinxao", "author_id": 660391, "author_profile": "https://Stackoverflow.com/users/660391", "pm_score": 0, "selected": false, "text": "<p>short loop for binary search:</p>\n<pre><code>function search( nums, target){ \n for(let mid,look,p=[0,,nums.length-1]; p[0]&lt;=p[2]; p[look+1]=mid-look){\n mid = (p[0] + p[2])&gt;&gt;&gt;1\n look = Math.sign(nums[mid]-target)\n if(!look) \n return mid\n }\n return -1\n}\n</code></pre>\n<hr />\n<p>idea is replacing:</p>\n<pre><code>if(nums[mid]==target)\n return mid\nelse if(nums[mid]&gt;target)\n right = mid - 1\nelse //here must nums[mid]&lt;target\n left = mid + 1\n</code></pre>\n<p>with more tacit(and possible less computation hungry) if observe\nformer is equal:</p>\n<pre><code>switch(dir=Math.sign(nums[mid]-target)){\n case -1: left = mid - dir;break;\n case 0: return mid\n case 1: right = mid - dir;break;\n}\n</code></pre>\n<p>so if left,mid,right vars situated sequentially we can address to all of them throw &amp;mid[-1,0,1 respectively] in C pointer sense :</p>\n<pre><code>dir=Math.sign(nums[mid]-target)\n&amp;mid[dir] = mid - dir\n</code></pre>\n<p>now we get body of loop so we can construct binary search:</p>\n<pre><code>while(dir &amp;&amp; left &lt;= right){\n mid = (left + right)&gt;&gt;&gt;2\n dir=Math.sign(nums[mid]-target)\n &amp;mid[dir] = mid - dir\n}\n</code></pre>\n<p>after while we just:</p>\n<pre><code>return [dir,mid]\n</code></pre>\n<p>with semantic that</p>\n<pre><code>for dir == -1 then nums[mid]&lt;target&lt;nums[mid+1] // if nums[mid+1 ] in start seaching domain\nfor dir == 0 then mid is place of target in array \nfor dir == 1 then nums[mid-1]&lt;target&lt;nums[mid] // if nums[mid-1 ] in start seaching domain \n</code></pre>\n<p>so in some more human pseudocode javascript function equivalent:</p>\n<pre><code> function search( nums, target){\n let dir=!0,[left, mid, right]=[0, , nums.length-1]\n while(dir &amp;&amp; left &lt;=right){\n mid = (left + right)&gt;&gt;&gt;1\n dir = Math.sign(nums[mid]-target)\n &amp;mid[dir]=mid - dir\n }\n return [dir, mid]\n }\n</code></pre>\n<p>for js sintax we need use q={'-1':0,1:nums.length-1} where left name for q[-1], mid for q[0] and right for q[1] or for q for all 3 is q[dir]</p>\n<p>or the same for array indexing from 0:</p>\n<p>we can use p=[0,,nums.length-1] where left is nikname for p[0], mid for p[1] and right for p[2] which is for all 3 of them is p[1+dir]</p>\n<p>. :)</p>\n" }, { "answer_id": 70013435, "author": "Niyousha Mohammadshafie", "author_id": 11705232, "author_profile": "https://Stackoverflow.com/users/11705232", "pm_score": 0, "selected": false, "text": "<p>Assuming the array is sorted, here is a Pythonic answer with O(log n) runtime complexity:</p>\n<pre><code>def binary_search(nums: List[int], target: int) -&gt; int:\n n = len(nums) - 1\n left = 0\n right = n\n \n \n while left &lt;= right:\n mid = left + (right - left) // 2\n if target == nums[mid]:\n return mid\n elif target &lt; nums[mid]:\n right = mid - 1\n else:\n left = mid + 1\n \n \n return -1\n</code></pre>\n" }, { "answer_id": 72664752, "author": "Sanpreet", "author_id": 2557590, "author_profile": "https://Stackoverflow.com/users/2557590", "pm_score": 1, "selected": false, "text": "<p><strong>Implementing a binary search using just an array</strong></p>\n<p>Binary search is an <strong>optimized solution</strong> for searching an element in an array as it reduces search time by following three ways</p>\n<ul>\n<li>Either the element to be searched can be the middle element.</li>\n<li>If not middle then would be less than middle</li>\n<li>If both cases are not true would be greater than middle</li>\n</ul>\n<p>If any of the above cases is not satisfied then such element is not present in an array.</p>\n<p><strong>Benefits of binary search</strong></p>\n<ul>\n<li>One donot need to search the whole array. Either search to the middle or less than middle or greater than middle. Saves time of search.</li>\n</ul>\n<p><strong>Algorithm Steps</strong></p>\n<ul>\n<li><p><strong>Step 1:</strong> Calculate the <code>mid index</code> using the floor of <code>lowest index and highest index</code> in an array.</p>\n</li>\n<li><p><strong>Step 2</strong>: Compare the element to be searched with the element present at the <code>middle index</code></p>\n</li>\n<li><p><strong>Step 3:</strong> If <strong>step 2</strong> is not satisfied, then check for all element to the left of middle element. To do so equate <code>high index = mid index - 1</code></p>\n</li>\n<li><p><strong>Step 4:</strong> If <strong>step 3</strong> is not satisfied, then check for all elements to the right of the middle element. To do so equate <code>low index = mid index + 1</code></p>\n</li>\n</ul>\n<p>if no case is satisfied then return -1 which means that element to be searched is not present in the whole array.</p>\n<p><strong>Code</strong></p>\n<pre><code># iterative approach of binary search\ndef binary_search(array, element_to_search):\n n = len(array)\n low = 0\n high = n - 1\n while low &lt;= high:\n mid = (low + high) // 2\n if element_to_search == array[mid]:\n return mid\n elif element_to_search &lt; array[mid]:\n high = mid - 1\n elif element_to_search &gt; array[mid]:\n low = mid + 1\n\n return -1\n\n\narray = [1, 3, 5, 7]\nelement_to_search = 8\nprint(binary_search(array=array,\n element_to_search=element_to_search))\n</code></pre>\n<p><strong>Recursive code</strong> can also be written for the binary search. Both (iterative and recursive) take <code>O(logn)</code> as the time complexity but when space complexity is to be considered then iterative approach for this solution will win as it takes <code>O(1)</code> whereas for recursive algo, three functions calls will be used in the function call stack and hence space complexity becomes equal to <code>O(logn)</code>. Below is the recursive solution.</p>\n<pre><code>def recurs_binary_search(arr, element, low, high):\n if low &gt; high:\n return -1\n mid = (low + high) // 2\n if arr[mid] == element:\n return mid\n elif arr[mid] &gt; element:\n return recurs_binary_search(arr,element, low, mid - 1) \n else:\n return recurs_binary_search(arr,element, mid + 1, high)\n\n\narray = [1, 3, 5, 7]\nelement_to_search = 7\nlow = 0\nhigh = len(array) - 1\nprint(recurs_binary_search(arr=array, element=element_to_search,\nlow=low, high=high))\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15055/" ]
How would I implement a binary search using just an array?
Ensure that your array is sorted since this is the crux of a binary search. Any indexed/random-access data structure can be binary searched. So when you say using "just an array", I would say arrays are the most basic/common data structure that a binary search is employed on. You can do it recursively (easiest) or iteratively. Time complexity of a binary search is O(log N) which is considerably faster than a linear search of checking each element at O(N). Here are some examples from [Wikipedia: Binary Search Algorithm](http://en.wikipedia.org/wiki/Binary_search): Recursive: ``` BinarySearch(A[0..N-1], value, low, high) { if (high < low) return -1 // not found mid = low + ((high - low) / 2) if (A[mid] > value) return BinarySearch(A, value, low, mid-1) else if (A[mid] < value) return BinarySearch(A, value, mid+1, high) else return mid // found } ``` Iterative: ``` BinarySearch(A[0..N-1], value) { low = 0 high = N - 1 while (low <= high) { mid = low + ((high - low) / 2) if (A[mid] > value) high = mid - 1 else if (A[mid] < value) low = mid + 1 else return mid // found } return -1 // not found } ```
249,423
<p>Can someone explain to me how XOR swapping of two variables with no temp variable works?</p> <pre><code>void xorSwap (int *x, int *y) { if (x != y) { *x ^= *y; *y ^= *x; *x ^= *y; } } </code></pre> <p>I understand WHAT it does, but can someone walk me through the logic of how it works? </p>
[ { "answer_id": 249427, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 4, "selected": false, "text": "<p>Most people would swap two variables x and y using a temporary variable, like this:</p>\n\n<pre><code>tmp = x\nx = y\ny = tmp\n</code></pre>\n\n<p>Here’s a neat programming trick to swap two values without needing a temp:</p>\n\n<pre><code>x = x xor y\ny = x xor y\nx = x xor y\n</code></pre>\n\n<p>More details in <a href=\"http://betterexplained.com/articles/swap-two-variables-using-xor/\" rel=\"noreferrer\">Swap two variables using XOR</a></p>\n\n<blockquote>\n <p>On line 1 we combine x and y (using XOR) to get this “hybrid” and we store it back in x. XOR is a great way to save information, because you can remove it by doing an XOR again.</p>\n \n <p>On line 2. We XOR the hybrid with y, which cancels out all the y information, leaving us only with x. We save this result back into y, so now they have swapped.</p>\n \n <p>On the last line, x still has the hybrid value. We XOR it yet again with y (now with x’s original value) to remove all traces of x out of the hybrid. This leaves us with y, and the swap is complete!</p>\n</blockquote>\n\n<hr>\n\n<blockquote>\n <p>The computer actually has an implicit “temp” variable that stores intermediate results before writing them back to a register. For example, if you add 3 to a register (in machine-language pseudocode):</p>\n</blockquote>\n\n<pre><code>ADD 3 A // add 3 to register A\n</code></pre>\n\n<blockquote>\n <p>The ALU (Arithmetic Logic Unit) is actually what executes the instruction 3+A. It takes the inputs (3,A) and creates a result (3 + A), which the CPU then stores back into A’s original register. So, we used the ALU as temporary scratch space before we had the final answer.</p>\n \n <p>We take the ALU’s implicit temporary data for granted, but it’s always there. In a similar way, the ALU can return the intermediate result of the XOR in the case of x = x xor y, at which point the CPU stores it into x’s original register.</p>\n \n <p>Because we aren’t used to thinking about the poor, neglected ALU, the XOR swap seems magical because it doesn’t have an explicit temporary variable. Some machines have a 1-step exchange XCHG instruction to swap two registers.</p>\n</blockquote>\n" }, { "answer_id": 249431, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 8, "selected": true, "text": "<p>You can see how it works by doing the substitution:</p>\n\n<pre><code>x1 = x0 xor y0\ny2 = x1 xor y0\nx2 = x1 xor y2\n</code></pre>\n\n<p>Substituting,</p>\n\n<pre><code>x1 = x0 xor y0\ny2 = (x0 xor y0) xor y0\nx2 = (x0 xor y0) xor ((x0 xor y0) xor y0)\n</code></pre>\n\n<p>Because xor is fully associative and commutative:</p>\n\n<pre><code>y2 = x0 xor (y0 xor y0)\nx2 = (x0 xor x0) xor (y0 xor y0) xor y0\n</code></pre>\n\n<p>Since <code>x xor x == 0</code> for any x,</p>\n\n<pre><code>y2 = x0 xor 0\nx2 = 0 xor 0 xor y0\n</code></pre>\n\n<p>And since <code>x xor 0 == x</code> for any x,</p>\n\n<pre><code>y2 = x0\nx2 = y0\n</code></pre>\n\n<p>And the swap is done.</p>\n" }, { "answer_id": 249438, "author": "Matt J", "author_id": 18528, "author_profile": "https://Stackoverflow.com/users/18528", "pm_score": 5, "selected": false, "text": "<p>Here's one that should be slightly easier to grok:</p>\n\n<pre><code>int x = 10, y = 7;\n\ny = x + y; //x = 10, y = 17\nx = y - x; //x = 7, y = 17\ny = y - x; //x = 7, y = 10\n</code></pre>\n\n<p>Now, one can understand the XOR trick a little more easily by understanding that <em>^</em> can be thought of as <em>+</em> <strong>or</strong> <em>-</em>. Just as:</p>\n\n<pre><code>x + y - ((x + y) - x) == x \n</code></pre>\n\n<p>, so:</p>\n\n<pre><code>x ^ y ^ ((x ^ y) ^ x) == x\n</code></pre>\n" }, { "answer_id": 249469, "author": "Patrick", "author_id": 429, "author_profile": "https://Stackoverflow.com/users/429", "pm_score": 7, "selected": false, "text": "<p>Other people have explained it, now I want to explain why it was a good idea, but now isn't.</p>\n\n<p>Back in the day when we had simple single cycle or multi-cycle CPUs, it was cheaper to use this trick to avoid costly memory dereferences or spilling registers to the stack. However, we now have CPUs with massive pipelines instead. The P4's pipeline ranged from having 20 to 31 (or so) stages in their pipelines, where any dependence between reading and writing to a register could cause the whole thing to stall. The xor swap has some very heavy dependencies between A and B that don't actually matter at all but stall the pipeline in practice. A stalled pipeline causes a slow code path, and if this swap's in your inner loop, you're going to be moving very slowly.</p>\n\n<p>In general practice, your compiler can figure out what you really want to do when you do a swap with a temp variable and can compile it to a single XCHG instruction. Using the xor swap makes it much harder for the compiler to guess your intent and therefore much less likely to optimize it correctly. Not to mention code maintenance, etc.</p>\n" }, { "answer_id": 249552, "author": "kenny", "author_id": 3225, "author_profile": "https://Stackoverflow.com/users/3225", "pm_score": 3, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/questions/249423/how-does-xor-variable-swapping-work#249427\">@VonC</a> has it right, it's a neat mathematical trick. Imagine 4 bit words and see if this helps.</p>\n\n<pre><code>word1 ^= word2;\nword2 ^= word1;\nword1 ^= word2;\n\n\nword1 word2\n0101 1111\nafter 1st xor\n1010 1111\nafter 2nd xor\n1010 0101\nafter 3rd xor\n1111 0101\n</code></pre>\n" }, { "answer_id": 412837, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>Basically there are 3 steps in the XOR approach:</p>\n\n<p>a’ = a XOR b (1) <br>\nb’ = a’ XOR b (2)<br>\na” = a’ XOR b’ (3)<br></p>\n\n<p>To understand <strong><em>why</em></strong> this works first note that:</p>\n\n<ol>\n<li>XOR will produce a 1 only if exactly one of it’s operands is 1, and the other is zero; </li>\n<li>XOR is <strong>commutative</strong> so a XOR b = b XOR a; </li>\n<li>XOR is <strong>associative</strong> so (a XOR b) XOR c = a XOR (b XOR c); and </li>\n<li>a XOR a = 0 (this should be obvious from the definition in <a href=\"http://www.necessaryandsufficient.net/2009/01/swapping-integers/\" rel=\"noreferrer\">1</a> above)</li>\n</ol>\n\n<p>After Step (1), the binary representation of a will have 1-bits only in the bit positions where a and b have opposing bits. That is either (ak=1, bk=0) or (ak=0, bk=1). Now when we do the substitution in Step (2) we get: </p>\n\n<p>b’ = (a XOR b) XOR b <br>\n = a XOR (b XOR b) because XOR is associative <br>\n = a XOR 0 because of [4] above <br>\n = a due to definition of XOR (see <a href=\"http://www.necessaryandsufficient.net/2009/01/swapping-integers/\" rel=\"noreferrer\">1</a> above) <br></p>\n\n<p>Now we can substitute into Step (3): <br></p>\n\n<p>a” = (a XOR b) XOR a <br>\n = (b XOR a) XOR a because XOR is commutative<br>\n = b XOR (a XOR a) because XOR is associative<br>\n = b XOR 0 because of [4] above<br>\n = b due to definition of XOR (see <a href=\"http://www.necessaryandsufficient.net/2009/01/swapping-integers/\" rel=\"noreferrer\">1</a> above)<br></p>\n\n<p>More detailed information here: \n<a href=\"http://www.necessaryandsufficient.net/2009/01/swapping-integers/\" rel=\"noreferrer\">Necessary and Sufficient</a></p>\n" }, { "answer_id": 528594, "author": "Mike Dunlavey", "author_id": 23771, "author_profile": "https://Stackoverflow.com/users/23771", "pm_score": 4, "selected": false, "text": "<p>The reason WHY it works is because XOR doesn't lose information. You could do the same thing with ordinary addition and subtraction if you could ignore overflow. For example, if the variable pair A,B originally contains the values 1,2, you could swap them like this:</p>\n\n<pre><code> // A,B = 1,2\nA = A+B // 3,2\nB = A-B // 3,1\nA = A-B // 2,1\n</code></pre>\n\n<p>BTW there's an old trick for encoding a 2-way linked list in a single \"pointer\".\nSuppose you have a list of memory blocks at addresses A, B, and C. The first word in each block is , respectively:</p>\n\n<pre><code> // first word of each block is sum of addresses of prior and next block\n 0 + &amp;B // first word of block A\n&amp;A + &amp;C // first word of block B\n&amp;B + 0 // first word of block C\n</code></pre>\n\n<p>If you have access to block A, it gives you the address of B. To get to C, you take the \"pointer\" in B and subtract A, and so on. It works just as well backwards. To run along the list, you need to keep pointers to two consecutive blocks. Of course you would use XOR in place of addition/subtration, so you wouldn't have to worry about overflow.</p>\n\n<p>You could extend this to a \"linked web\" if you wanted to have some fun.</p>\n" }, { "answer_id": 528869, "author": "jheriko", "author_id": 17604, "author_profile": "https://Stackoverflow.com/users/17604", "pm_score": 2, "selected": false, "text": "<p>As a side note I reinvented this wheel independently several years ago in the form of swapping integers by doing:</p>\n\n<pre><code>a = a + b\nb = a - b ( = a + b - b once expanded)\na = a - b ( = a + b - a once expanded).\n</code></pre>\n\n<p>(This is mentioned above in a difficult to read way), </p>\n\n<p>The exact same reasoning applies to xor swaps: a ^ b ^ b = a and a ^ b ^ a = a. Since xor is commutative, x ^ x = 0 and x ^ 0 = x, this is quite easy to see since</p>\n\n<pre><code>= a ^ b ^ b\n= a ^ 0\n= a\n</code></pre>\n\n<p>and </p>\n\n<pre><code>= a ^ b ^ a \n= a ^ a ^ b \n= 0 ^ b \n= b\n</code></pre>\n\n<p>Hope this helps. This explanation has already been given... but not very clearly imo.</p>\n" }, { "answer_id": 528946, "author": "plinth", "author_id": 20481, "author_profile": "https://Stackoverflow.com/users/20481", "pm_score": 6, "selected": false, "text": "<p>I like to think of it graphically rather than numerically.</p>\n\n<p>Let's say you start with x = 11 and y = 5\nIn binary (and I'm going to use a hypothetical 4 bit machine), here's x and y</p>\n\n<pre><code> x: |1|0|1|1| -&gt; 8 + 2 + 1\n y: |0|1|0|1| -&gt; 4 + 1\n</code></pre>\n\n<p>Now to me, XOR is an invert operation and doing it twice is a mirror:</p>\n\n<pre><code> x^y: |1|1|1|0|\n (x^y)^y: |1|0|1|1| &lt;- ooh! Check it out - x came back\n (x^y)^x: |0|1|0|1| &lt;- ooh! y came back too!\n</code></pre>\n" }, { "answer_id": 61323856, "author": "Sungfu Chiu", "author_id": 8408846, "author_profile": "https://Stackoverflow.com/users/8408846", "pm_score": 2, "selected": false, "text": "<p>I just want to add a mathematical explanation to make the answer more complete. In <a href=\"https://en.wikipedia.org/wiki/Group_theory\" rel=\"nofollow noreferrer\">group theory</a>, XOR is an <a href=\"https://en.wikipedia.org/wiki/Abelian_group\" rel=\"nofollow noreferrer\">abelian group</a>, also called a commutative group. It means it satisfies five requirements: Closure, Associativity, Identity element, Inverse element, Commutativity.</p>\n\n<p>XOR swap formula:</p>\n\n<pre><code>a = a XOR b\nb = a XOR b\na = a XOR b \n</code></pre>\n\n<p>Expand the formula, substitute a, b with previous formula:</p>\n\n<pre><code>a = a XOR b\nb = a XOR b = (a XOR b) XOR b\na = a XOR b = (a XOR b) XOR (a XOR b) XOR b\n</code></pre>\n\n<p>Commutativity means \"a XOR b\" equal to \"b XOR a\":</p>\n\n<pre><code>a = a XOR b\nb = a XOR b = (a XOR b) XOR b\na = a XOR b = (a XOR b) XOR (a XOR b) XOR b \n = (b XOR a) XOR (a XOR b) XOR b\n</code></pre>\n\n<p>Associativity means \"(a XOR b) XOR c\" equal to \"a XOR (b XOR c)\":</p>\n\n<pre><code>a = a XOR b\nb = a XOR b = (a XOR b) XOR b \n = a XOR (b XOR b)\na = a XOR b = (a XOR b) XOR (a XOR b) XOR b \n = (b XOR a) XOR (a XOR b) XOR b \n = b XOR (a XOR a) XOR (b XOR b)\n</code></pre>\n\n<p>The inverse element in XOR is itself, it means that any value XOR with itself gives zero:</p>\n\n<pre><code>a = a XOR b\nb = a XOR b = (a XOR b) XOR b \n = a XOR (b XOR b) \n = a XOR 0\na = a XOR b = (a XOR b) XOR (a XOR b) XOR b \n = (b XOR a) XOR (a XOR b) XOR b \n = b XOR (a XOR a) XOR (b XOR b) \n = b XOR 0 XOR 0\n</code></pre>\n\n<p>The identity element in XOR is zero, it means that any value XOR with zero is left unchanged:</p>\n\n<pre><code>a = a XOR b\nb = a XOR b = (a XOR b) XOR b \n = a XOR (b XOR b) \n = a XOR 0 \n = a\na = a XOR b = (a XOR b) XOR (a XOR b) XOR b \n = (b XOR a) XOR (a XOR b) XOR b \n = b XOR (a XOR a) XOR (b XOR b) \n = b XOR 0 XOR 0 \n = b XOR 0\n = b\n</code></pre>\n\n<p>And you can get further information in <a href=\"https://en.wikipedia.org/wiki/Group_theory\" rel=\"nofollow noreferrer\">group theory</a>.</p>\n" }, { "answer_id": 65581923, "author": "LifelessG", "author_id": 12135716, "author_profile": "https://Stackoverflow.com/users/12135716", "pm_score": 0, "selected": false, "text": "<p>Others have posted explanations but I think it would be better understood if its accompanied with a good example.</p>\n<p><a href=\"https://i.stack.imgur.com/MkNUN.jpg\" rel=\"nofollow noreferrer\">XOR Truth Table</a></p>\n<p>If we consider the above truth table and take the values <code>A = 1100</code> and <code>B = 0101</code> we are able to swap the values as such:</p>\n<pre><code>A = 1100\nB = 0101\n\n\nA ^= B; =&gt; A = 1100 XOR 0101\n(A = 1001)\n\nB ^= A; =&gt; B = 0101 XOR 1001\n(B = 1100)\n\nA ^= B; =&gt; A = 1001 XOR 1100\n(A = 0101)\n\n\nA = 0101\nB = 1100\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249423", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2635/" ]
Can someone explain to me how XOR swapping of two variables with no temp variable works? ``` void xorSwap (int *x, int *y) { if (x != y) { *x ^= *y; *y ^= *x; *x ^= *y; } } ``` I understand WHAT it does, but can someone walk me through the logic of how it works?
You can see how it works by doing the substitution: ``` x1 = x0 xor y0 y2 = x1 xor y0 x2 = x1 xor y2 ``` Substituting, ``` x1 = x0 xor y0 y2 = (x0 xor y0) xor y0 x2 = (x0 xor y0) xor ((x0 xor y0) xor y0) ``` Because xor is fully associative and commutative: ``` y2 = x0 xor (y0 xor y0) x2 = (x0 xor x0) xor (y0 xor y0) xor y0 ``` Since `x xor x == 0` for any x, ``` y2 = x0 xor 0 x2 = 0 xor 0 xor y0 ``` And since `x xor 0 == x` for any x, ``` y2 = x0 x2 = y0 ``` And the swap is done.
249,432
<p>I'm reading through the <a href="http://framework.zend.com/manual/en/coding-standard.coding-style.html" rel="nofollow noreferrer">Zend Framework coding standards</a>, where they state that curly brace after a Class definitions should be on the next line, the "one true brace form".</p> <pre><code>class MyClass { function.... } </code></pre> <p>I usually have the braces on the same line:</p> <pre><code>class OtherClass { function ... } </code></pre> <p>What's the reason for putting the brace on the next line? Or using any other style, for that matter?</p>
[ { "answer_id": 249434, "author": "Kyle Trauberman", "author_id": 21461, "author_profile": "https://Stackoverflow.com/users/21461", "pm_score": 1, "selected": false, "text": "<p>User preference. It really makes no difference. When I developed in PHP, I used the second option, but now using C#, I use the first.</p>\n" }, { "answer_id": 249436, "author": "Levi Rosol", "author_id": 23458, "author_profile": "https://Stackoverflow.com/users/23458", "pm_score": 4, "selected": true, "text": "<p>Personal preference is really the only real \"reason\".</p>\n" }, { "answer_id": 249437, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 3, "selected": false, "text": "<p>I find that the first style you mentioned helps visually offset the class name from its member definitions. This helps me find the top of the class declaration more easily when scanning code.</p>\n" }, { "answer_id": 249441, "author": "HS.", "author_id": 1398, "author_profile": "https://Stackoverflow.com/users/1398", "pm_score": 3, "selected": false, "text": "<p>Having the braces on lines by themselves helps to visually separate the inner part from the outer part. That makes it easier to quickly scan through source code and distinguish blocks from their surroundings.</p>\n\n<p>Plus, having the braces at the same indentation level makes it easier for the eye to find a match.</p>\n" }, { "answer_id": 249443, "author": "Grey Panther", "author_id": 1265, "author_profile": "https://Stackoverflow.com/users/1265", "pm_score": 2, "selected": false, "text": "<p>Often cited reasons are:</p>\n\n<ul>\n<li>easier to match up opening and closing braces (for the first example)</li>\n<li>don't waste an other line (so that you can fit more lines of code on the screen - the second example)</li>\n</ul>\n\n<p>As others have said: if you work on 3rd party code, just follow its conventions. If you work on your own code, just use whichever style you find better.</p>\n" }, { "answer_id": 249450, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 1, "selected": false, "text": "<p>There are already several topics on this highly subjective topic...</p>\n\n<p>Some people are passionate about it, personally I chose the \"readable\" option of aligning braces (I don't pay for real estate used by my code on screen... so compactness doesn't interest me) but when I contribute to a project using another style, I just use the one around my contribution.<br>\nSame for tab size, hard vs. soft, etc.</p>\n" }, { "answer_id": 249495, "author": "a2800276", "author_id": 27408, "author_profile": "https://Stackoverflow.com/users/27408", "pm_score": 0, "selected": false, "text": "<p>The real reason is to have uniform looking code throughout the codebase. Both styles have their advantages, which style is \"better\" depends on personal preference and what has been used \"traditionally\" in the language and the project. </p>\n\n<p>If a style of braces is prescribed, use that, else use what was being used before you arrived. If you're starting a new project use what is normally used in the language of choice.</p>\n\n<p>Same goes for tabs vs. spaces.</p>\n" }, { "answer_id": 249508, "author": "Aron Rotteveel", "author_id": 11568, "author_profile": "https://Stackoverflow.com/users/11568", "pm_score": 2, "selected": false, "text": "<p>I think coding style and naming conventions on personal or team projects are mostly a matter of personal taste (although it is wise a team adopts a single coding style and naming conventions).</p>\n\n<p>Personally, I like to follow the <a href=\"http://en.wikipedia.org/wiki/Indent_style#Allman_style_.28bsd_in_Emacs.29\" rel=\"nofollow noreferrer\">Allman Style</a> convention, as it gives me a quick overview of my code and indent structure. Sure, it will cost you some extra lines in your code, but I don't think that weighs up to the advantages.</p>\n\n<p>Good resources on this matter are the following Wikipedia articles:</p>\n\n<blockquote>\n <p><a href=\"http://en.wikipedia.org/wiki/Indent_style\" rel=\"nofollow noreferrer\">Indent Style</a></p>\n \n <p><a href=\"http://en.wikipedia.org/wiki/Programming_style\" rel=\"nofollow noreferrer\">Programming Style</a></p>\n \n <p><a href=\"http://en.wikipedia.org/wiki/Naming_conventions_(programming)\" rel=\"nofollow noreferrer\">Naming Conventions</a></p>\n</blockquote>\n" }, { "answer_id": 46472687, "author": "Bill Evans at Mariposa", "author_id": 668445, "author_profile": "https://Stackoverflow.com/users/668445", "pm_score": 0, "selected": false, "text": "<p>Does it matter which brace style you use? No. Does it matter that everyone working on the same project or source file use the same brace style? No; not only does it not matter, but it's useful if brace styles differ from one coder to the next, even in the same file.</p>\n\n<p>\"Why exactly does this chunk of code do this?\"</p>\n\n<p>\"I don't know. It's in Kevin's handwriting. Let's go ask him.\"</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249432", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6681/" ]
I'm reading through the [Zend Framework coding standards](http://framework.zend.com/manual/en/coding-standard.coding-style.html), where they state that curly brace after a Class definitions should be on the next line, the "one true brace form". ``` class MyClass { function.... } ``` I usually have the braces on the same line: ``` class OtherClass { function ... } ``` What's the reason for putting the brace on the next line? Or using any other style, for that matter?
Personal preference is really the only real "reason".
249,448
<p>I have a textbox with the <strong>Text</strong> property bound to a dataset column with the DataType set to System.DateTime.<br> The FormatString on the Binding is set to <strong>dd-MM-yyyy</strong>.</p> <p>When the user enters a date it attempts to convert it to a date but can come up with some strange values for a seemingly invalid date.</p> <p>For example:</p> <pre><code>textBox1.Text = "01-02-200"; </code></pre> <p>Should be an invalid date but it formats it as <strong>01-02-0200</strong>.</p> <p>Is there an easy way to catch these out-of-bounds values either through setting a valid range or overriding an event on the binding/textbox?</p>
[ { "answer_id": 249517, "author": "dove", "author_id": 30913, "author_profile": "https://Stackoverflow.com/users/30913", "pm_score": 0, "selected": false, "text": "<p>Any reason not to use a date picker control instead of a textbox? Would solve validation problem and probably make it a better experience for the user.</p>\n" }, { "answer_id": 249519, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 3, "selected": true, "text": "<p>A .NET DateTime is in the range 01/01/0001 to 31/12/9999 23:59:59.9999999, so 01/01/200 is considered to be valid.</p>\n\n<p>You can validate the input and restrict the range: the Validating event would be the place to do your validation. You'll need to parse the string into a DateTime and validate its range.</p>\n\n<p>The allowed range will be application dependent. For example, the following code will restrict the datetime to values that can be stored in a SQL Server 2005 DATETIME column (01-01-1753 to 31-12-999):</p>\n\n<pre><code>private void textBox1_Validating(object sender, CancelEventArgs e)\n{\n DateTime date;\n if (!DateTime.TryParseExact(textBox1.Text, \n \"dd-MM-yyyy\", \n CultureInfo.CurrentCulture, \n DateTimeStyles.None, \n out date))\n {\n MessageBox.Show(textBox1.Text + \" is not a valid date\");\n textBox1.Focus();\n e.Cancel = true;\n return;\n }\n if ((date &lt; (DateTime) System.Data.SqlTypes.SqlDateTime.MinValue) ||\n (date &gt; (DateTime) System.Data.SqlTypes.SqlDateTime.MaxValue))\n {\n MessageBox.Show(textBox1.Text + \" is out of range\");\n textBox1.Focus();\n e.Cancel = true;\n return;\n }\n}\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249448", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4490/" ]
I have a textbox with the **Text** property bound to a dataset column with the DataType set to System.DateTime. The FormatString on the Binding is set to **dd-MM-yyyy**. When the user enters a date it attempts to convert it to a date but can come up with some strange values for a seemingly invalid date. For example: ``` textBox1.Text = "01-02-200"; ``` Should be an invalid date but it formats it as **01-02-0200**. Is there an easy way to catch these out-of-bounds values either through setting a valid range or overriding an event on the binding/textbox?
A .NET DateTime is in the range 01/01/0001 to 31/12/9999 23:59:59.9999999, so 01/01/200 is considered to be valid. You can validate the input and restrict the range: the Validating event would be the place to do your validation. You'll need to parse the string into a DateTime and validate its range. The allowed range will be application dependent. For example, the following code will restrict the datetime to values that can be stored in a SQL Server 2005 DATETIME column (01-01-1753 to 31-12-999): ``` private void textBox1_Validating(object sender, CancelEventArgs e) { DateTime date; if (!DateTime.TryParseExact(textBox1.Text, "dd-MM-yyyy", CultureInfo.CurrentCulture, DateTimeStyles.None, out date)) { MessageBox.Show(textBox1.Text + " is not a valid date"); textBox1.Focus(); e.Cancel = true; return; } if ((date < (DateTime) System.Data.SqlTypes.SqlDateTime.MinValue) || (date > (DateTime) System.Data.SqlTypes.SqlDateTime.MaxValue)) { MessageBox.Show(textBox1.Text + " is out of range"); textBox1.Focus(); e.Cancel = true; return; } } ```
249,452
<p>How to add new item in existing string array in C#.net?</p> <p>I need to preserve the existing data.</p>
[ { "answer_id": 249455, "author": "Ed S.", "author_id": 1053, "author_profile": "https://Stackoverflow.com/users/1053", "pm_score": 7, "selected": false, "text": "<p>I would use a List if you need a dynamically sized array:</p>\n\n<pre><code>List&lt;string&gt; ls = new List&lt;string&gt;();\nls.Add(\"Hello\");\n</code></pre>\n" }, { "answer_id": 249465, "author": "harpo", "author_id": 4525, "author_profile": "https://Stackoverflow.com/users/4525", "pm_score": 1, "selected": false, "text": "<p>I agree with Ed. C# does not make this easy the way VB does with ReDim Preserve. Without a collection, you'll have to copy the array into a larger one.</p>\n" }, { "answer_id": 249486, "author": "Ali Ersöz", "author_id": 4215, "author_profile": "https://Stackoverflow.com/users/4215", "pm_score": 7, "selected": false, "text": "<p>That could be a solution;</p>\n\n<pre><code>Array.Resize(ref array, newsize);\narray[newsize - 1] = \"newvalue\"\n</code></pre>\n\n<p>But for dynamic sized array I would prefer list too.</p>\n" }, { "answer_id": 249792, "author": "artur02", "author_id": 13937, "author_profile": "https://Stackoverflow.com/users/13937", "pm_score": 5, "selected": false, "text": "<p><strong>Arrays in C# are immutable</strong>, e.g. <code>string[]</code>, <code>int[]</code>. That means you can't resize them. You need to create a brand new array.</p>\n\n<p>Here is the code for <strong>Array.Resize</strong>:</p>\n\n<pre><code>public static void Resize&lt;T&gt;(ref T[] array, int newSize)\n{\n if (newSize &lt; 0)\n {\n throw new ArgumentOutOfRangeException(\"newSize\", Environment.GetResourceString(\"ArgumentOutOfRange_NeedNonNegNum\"));\n }\n T[] sourceArray = array;\n if (sourceArray == null)\n {\n array = new T[newSize];\n }\n else if (sourceArray.Length != newSize)\n {\n T[] destinationArray = new T[newSize];\n Copy(sourceArray, 0, destinationArray, 0, (sourceArray.Length &gt; newSize) ? newSize : sourceArray.Length);\n array = destinationArray;\n }\n}\n</code></pre>\n\n<p>As you can see it creates a new array with the new size, copies the content of the source array and sets the reference to the new array. The hint for this is the <em>ref</em> keyword for the first parameter.</p>\n\n<p>There are lists that can <strong>dynamically allocate new slots</strong> for new items. This is e.g. <em>List&lt;T></em>. These contain immutable arrays and resize them when needed (List&lt;T> is not a linked list implementation!). <em>ArrayList</em> is the same thing without Generics (with <em>Object</em> array).</p>\n\n<p><strong>LinkedList&lt;T></strong> is a real linked list implementation. Unfortunately you can add just LinkListNode&lt;T> elements to the list, so you must wrap your own list elements into this node type. I think its use is uncommon.</p>\n" }, { "answer_id": 2787955, "author": "Dave Blake", "author_id": 335357, "author_profile": "https://Stackoverflow.com/users/335357", "pm_score": 0, "selected": false, "text": "<pre><code>private static string[] GetMergedArray(string[] originalArray, string[] newArray)\n {\n int startIndexForNewArray = originalArray.Length;\n Array.Resize&lt;string&gt;(ref originalArray, originalArray.Length + newArray.Length);\n newArray.CopyTo(originalArray, startIndexForNewArray);\n return originalArray;\n }\n</code></pre>\n" }, { "answer_id": 5780240, "author": "Gia Duong Duc Minh", "author_id": 701950, "author_profile": "https://Stackoverflow.com/users/701950", "pm_score": 2, "selected": false, "text": "<pre><code>string str = \"string \";\nList&lt;string&gt; li_str = new List&lt;string&gt;();\n for (int k = 0; k &lt; 100; i++ )\n li_str.Add(str+k.ToString());\nstring[] arr_str = li_str.ToArray();\n</code></pre>\n" }, { "answer_id": 7116251, "author": "Stephen Chung", "author_id": 650891, "author_profile": "https://Stackoverflow.com/users/650891", "pm_score": 6, "selected": false, "text": "<p>Using LINQ:</p>\n\n<pre><code>arr = (arr ?? Enumerable.Empty&lt;string&gt;()).Concat(new[] { newitem }).ToArray();\n</code></pre>\n\n<p>I like using this as it is a one-liner and very convenient to embed in a switch statement, a simple if-statement, or pass as argument.</p>\n\n<p><strong>EDIT:</strong></p>\n\n<p>Some people don't like <code>new[] { newitem }</code> because it creates a small, one-item, temporary array. Here is a version using <code>Enumerable.Repeat</code> that does not require creating any object (at least not on the surface -- .NET iterators probably create a bunch of state machine objects under the table).</p>\n\n<pre><code>arr = (arr ?? Enumerable.Empty&lt;string&gt;()).Concat(Enumerable.Repeat(newitem,1)).ToArray();\n</code></pre>\n\n<p>And if you are sure that the array is never <code>null</code> to start with, you can simplify it to:</p>\n\n<pre><code>arr.Concat(Enumerable.Repeat(newitem,1)).ToArray();\n</code></pre>\n\n<p>Notice that if you want to add items to a an ordered collection, <code>List</code> is probably the data structure you want, not an array to start with.</p>\n" }, { "answer_id": 7116358, "author": "Gaijinhunter", "author_id": 754233, "author_profile": "https://Stackoverflow.com/users/754233", "pm_score": 0, "selected": false, "text": "<p>Why not try out using the <strong>Stringbuilder</strong> class. It has methods such as .insert and .append. You can read more about it here: <a href=\"http://msdn.microsoft.com/en-us/library/2839d5h5(v=vs.71).aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/2839d5h5(v=vs.71).aspx</a></p>\n" }, { "answer_id": 8616931, "author": "tmania", "author_id": 538280, "author_profile": "https://Stackoverflow.com/users/538280", "pm_score": 5, "selected": false, "text": "<pre><code> Array.Resize(ref youur_array_name, your_array_name.Length + 1);\n your_array_name[your_array_name.Length - 1] = \"new item\";\n</code></pre>\n" }, { "answer_id": 8657340, "author": "JAR", "author_id": 1119354, "author_profile": "https://Stackoverflow.com/users/1119354", "pm_score": 0, "selected": false, "text": "<p>Unfortunately using a list won't work in all situations. A list and an array are actually different and are not 100% interchangeable. It would depend on the circumstances if this would be an acceptable work around.</p>\n" }, { "answer_id": 10799751, "author": "Axxelsian", "author_id": 1398693, "author_profile": "https://Stackoverflow.com/users/1398693", "pm_score": 2, "selected": false, "text": "<p>Using a list would be your best option for memory management.</p>\n" }, { "answer_id": 11035286, "author": "dblood", "author_id": 673545, "author_profile": "https://Stackoverflow.com/users/673545", "pm_score": 3, "selected": false, "text": "<p>You can expand on the answer provided by @Stephen Chung by using his LINQ based logic to create an extension method using a generic type.</p>\n\n<pre><code>public static class CollectionHelper\n{\n public static IEnumerable&lt;T&gt; Add&lt;T&gt;(this IEnumerable&lt;T&gt; sequence, T item)\n {\n return (sequence ?? Enumerable.Empty&lt;T&gt;()).Concat(new[] { item });\n }\n\n public static T[] AddRangeToArray&lt;T&gt;(this T[] sequence, T[] items)\n {\n return (sequence ?? Enumerable.Empty&lt;T&gt;()).Concat(items).ToArray();\n }\n\n public static T[] AddToArray&lt;T&gt;(this T[] sequence, T item)\n {\n return Add(sequence, item).ToArray();\n }\n\n}\n</code></pre>\n\n<p>You can then call it directly on the array like this.</p>\n\n<pre><code> public void AddToArray(string[] options)\n {\n // Add one item\n options = options.AddToArray(\"New Item\");\n\n // Add a \n options = options.AddRangeToArray(new string[] { \"one\", \"two\", \"three\" });\n\n // Do stuff...\n }\n</code></pre>\n\n<p>Admittedly, the AddRangeToArray() method seems a bit overkill since you have the same functionality with Concat() but this way the end code can \"work\" with the array directly\nas opposed to this:</p>\n\n<pre><code>options = options.Concat(new string[] { \"one\", \"two\", \"three\" }).ToArray();\n</code></pre>\n" }, { "answer_id": 26710916, "author": "Suren", "author_id": 428061, "author_profile": "https://Stackoverflow.com/users/428061", "pm_score": 3, "selected": false, "text": "<h2>It's better to keeps Array immutable and fixed size.</h2>\n\n<p>you can simulate <code>Add</code> by <code>Extension Method</code> and <code>IEnumerable.Concat()</code></p>\n\n<pre><code>public static class ArrayExtensions\n {\n public static string[] Add(this string[] array, string item)\n {\n return array.Concat(new[] {item}).ToArray();\n }\n }\n</code></pre>\n" }, { "answer_id": 36759482, "author": "Saif", "author_id": 5362552, "author_profile": "https://Stackoverflow.com/users/5362552", "pm_score": 0, "selected": false, "text": "<p>Since this question not satisfied with provided answer, I would like to add this answer :)</p>\n\n<pre><code>public class CustomArrayList&lt;T&gt; \n { \n private T[] arr; private int count; \n\npublic int Count \n { \n get \n { \n return this.count; \n } \n } \n private const int INITIAL_CAPACITY = 4; \n\n public CustomArrayList(int capacity = INITIAL_CAPACITY) \n { \n this.arr = new T[capacity]; this.count = 0; \n } \n\n public void Add(T item) \n { \n GrowIfArrIsFull(); \n this.arr[this.count] = item; this.count++; \n } \n\npublic void Insert(int index, T item) \n{ \n if (index &gt; this.count || index &lt; 0) \n { \n throw new IndexOutOfRangeException( \"Invalid index: \" + index); \n } \n GrowIfArrIsFull(); \n Array.Copy(this.arr, index, this.arr, index + 1, this.count - index); \n this.arr[index] = item; this.count++; } \n\n private void GrowIfArrIsFull() \n { \n if (this.count + 1 &gt; this.arr.Length) \n { \n T[] extendedArr = new T[this.arr.Length * 2]; \n Array.Copy(this.arr, extendedArr, this.count); \n this.arr = extendedArr; \n } \n }\n }\n}\n</code></pre>\n" }, { "answer_id": 37369110, "author": "stackuser83", "author_id": 832705, "author_profile": "https://Stackoverflow.com/users/832705", "pm_score": 3, "selected": false, "text": "<p>if you are working a lot with arrays and not lists for some reason, this generic typed return generic method <code>Add</code> might help</p>\n\n<pre><code> public static T[] Add&lt;T&gt;(T[] array, T item)\n {\n T[] returnarray = new T[array.Length + 1];\n for (int i = 0; i &lt; array.Length; i++)\n {\n returnarray[i] = array[i];\n }\n returnarray[array.Length] = item;\n return returnarray;\n }\n</code></pre>\n" }, { "answer_id": 37695587, "author": "Grimace of Despair", "author_id": 281084, "author_profile": "https://Stackoverflow.com/users/281084", "pm_score": 5, "selected": false, "text": "<p>Very old question, but still wanted to add this.</p>\n\n<p>If you're looking for a one-liner, you can use the code below. It combines the list constructor that accepts an enumerable and the \"new\" (since question raised) initializer syntax.</p>\n\n<pre><code>myArray = new List&lt;string&gt;(myArray) { \"add this\" }.ToArray();\n</code></pre>\n" }, { "answer_id": 42800892, "author": "William", "author_id": 907734, "author_profile": "https://Stackoverflow.com/users/907734", "pm_score": 2, "selected": false, "text": "<p>What about using an extension method? For instance:</p>\n\n<pre><code>public static IEnumerable&lt;TSource&gt; Union&lt;TSource&gt;(this IEnumerable&lt;TSource&gt; source, TSource item)\n{\n return source.Union(new TSource[] { item });\n}\n</code></pre>\n\n<p>for instance:</p>\n\n<pre><code>string[] sourceArray = new []\n{\n \"foo\",\n \"bar\"\n}\nstring additionalItem = \"foobar\";\nstring result = sourceArray.Union(additionalItem);\n</code></pre>\n\n<p>Note this mimics this behavior of Linq's Uniion extension (used to combine two arrays into a new one), and required the Linq library to function.</p>\n" }, { "answer_id": 46234371, "author": "Adi_Pithwa", "author_id": 2298846, "author_profile": "https://Stackoverflow.com/users/2298846", "pm_score": 3, "selected": false, "text": "<p>So if you have a existing array, my quick fix will be</p>\n\n<pre><code>var tempList = originalArray.ToList();\ntempList.Add(newitem);\n</code></pre>\n\n<p>Now just replace the original array with the new one</p>\n\n<pre><code>originalArray = tempList.ToArray();\n</code></pre>\n" }, { "answer_id": 50772992, "author": "Walter Verhoeven", "author_id": 8000382, "author_profile": "https://Stackoverflow.com/users/8000382", "pm_score": 3, "selected": false, "text": "<p>All proposed answers do the same as what they say they'd like to avoid, creating a new array and adding a new entry in it only with lost more overhead. \nLINQ is not magic, list of T is an array with a buffer space with some extra space as to avoid resizing the inner array when items are added. </p>\n\n<p>All the abstractions have to solve the same issue, create an array with no empty slots that hold all values and return them. </p>\n\n<p>If you need the flexibility an can create a large enough list that you can use to pass then do that. else use an array and share that thread-safe object. Also, the new Span helps to share data without having to copy the lists around. </p>\n\n<p>To answer the question:</p>\n\n<pre><code>Array.Resize(ref myArray, myArray.Length + 1);\ndata[myArray.Length - 1] = Value;\n</code></pre>\n" }, { "answer_id": 60377314, "author": "0xced", "author_id": 21698, "author_profile": "https://Stackoverflow.com/users/21698", "pm_score": 3, "selected": false, "text": "<p>A new <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.append\" rel=\"noreferrer\"><code>Append&lt;TSource&gt;</code></a> method has been added to <code>IEnumerable&lt;TSource&gt;</code> since .NET Framework 4.7.1 and .NET Core 1.0.</p>\n\n<p>Here is how to use it:</p>\n\n<pre><code>var numbers = new [] { \"one\", \"two\", \"three\" };\nnumbers = numbers.Append(\"four\").ToArray();\nConsole.WriteLine(string.Join(\", \", numbers)); // one, two, three, four\n</code></pre>\n\n<p>Note that if you want to add the element at the beginning of the array, you can use the new <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.prepend\" rel=\"noreferrer\"><code>Prepend&lt;TSource&gt;</code></a> method instead.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249452", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
How to add new item in existing string array in C#.net? I need to preserve the existing data.
I would use a List if you need a dynamically sized array: ``` List<string> ls = new List<string>(); ls.Add("Hello"); ```
249,460
<p>On Windows Mobile, I am displaying my output in HTML. This includes lots of user-generated strings. Occasionally there are situations where a really large string is part of the output that has no whitespaces or punctuation. </p> <p>Unfortunately the Windows Mobile's HTML view (htmlview.dll, based on Pocket Internet Explorer) does not break these long words down so they fit on screen. Instead a horizontal scrollbar is added and the user has to scroll sideways to see the whole word. This also affects other output which now also is spread along this larger screen width.</p> <p>Is there any possibility to either make the htmlview behave differently, or to force the word to break? CSS can be used. Regarding the forcing: The &amp;shy; tag is ALWAYS inserting a "-" character and never causes a breaks, the &lt;WBR&gt; tag is not doing anything at all, &amp;8203; is output as &amp;8203:, empty tags like <B></B> also do nothing. Also it should be noted that this code is running on multiple screen sizes and due to other parts of the HTML output I am not 100% sure how much screen width I have left.</p> <p>P.S.: My app is compiled using the WM 5.0 SDK and is written in C++/Win32/MFC.</p>
[ { "answer_id": 249455, "author": "Ed S.", "author_id": 1053, "author_profile": "https://Stackoverflow.com/users/1053", "pm_score": 7, "selected": false, "text": "<p>I would use a List if you need a dynamically sized array:</p>\n\n<pre><code>List&lt;string&gt; ls = new List&lt;string&gt;();\nls.Add(\"Hello\");\n</code></pre>\n" }, { "answer_id": 249465, "author": "harpo", "author_id": 4525, "author_profile": "https://Stackoverflow.com/users/4525", "pm_score": 1, "selected": false, "text": "<p>I agree with Ed. C# does not make this easy the way VB does with ReDim Preserve. Without a collection, you'll have to copy the array into a larger one.</p>\n" }, { "answer_id": 249486, "author": "Ali Ersöz", "author_id": 4215, "author_profile": "https://Stackoverflow.com/users/4215", "pm_score": 7, "selected": false, "text": "<p>That could be a solution;</p>\n\n<pre><code>Array.Resize(ref array, newsize);\narray[newsize - 1] = \"newvalue\"\n</code></pre>\n\n<p>But for dynamic sized array I would prefer list too.</p>\n" }, { "answer_id": 249792, "author": "artur02", "author_id": 13937, "author_profile": "https://Stackoverflow.com/users/13937", "pm_score": 5, "selected": false, "text": "<p><strong>Arrays in C# are immutable</strong>, e.g. <code>string[]</code>, <code>int[]</code>. That means you can't resize them. You need to create a brand new array.</p>\n\n<p>Here is the code for <strong>Array.Resize</strong>:</p>\n\n<pre><code>public static void Resize&lt;T&gt;(ref T[] array, int newSize)\n{\n if (newSize &lt; 0)\n {\n throw new ArgumentOutOfRangeException(\"newSize\", Environment.GetResourceString(\"ArgumentOutOfRange_NeedNonNegNum\"));\n }\n T[] sourceArray = array;\n if (sourceArray == null)\n {\n array = new T[newSize];\n }\n else if (sourceArray.Length != newSize)\n {\n T[] destinationArray = new T[newSize];\n Copy(sourceArray, 0, destinationArray, 0, (sourceArray.Length &gt; newSize) ? newSize : sourceArray.Length);\n array = destinationArray;\n }\n}\n</code></pre>\n\n<p>As you can see it creates a new array with the new size, copies the content of the source array and sets the reference to the new array. The hint for this is the <em>ref</em> keyword for the first parameter.</p>\n\n<p>There are lists that can <strong>dynamically allocate new slots</strong> for new items. This is e.g. <em>List&lt;T></em>. These contain immutable arrays and resize them when needed (List&lt;T> is not a linked list implementation!). <em>ArrayList</em> is the same thing without Generics (with <em>Object</em> array).</p>\n\n<p><strong>LinkedList&lt;T></strong> is a real linked list implementation. Unfortunately you can add just LinkListNode&lt;T> elements to the list, so you must wrap your own list elements into this node type. I think its use is uncommon.</p>\n" }, { "answer_id": 2787955, "author": "Dave Blake", "author_id": 335357, "author_profile": "https://Stackoverflow.com/users/335357", "pm_score": 0, "selected": false, "text": "<pre><code>private static string[] GetMergedArray(string[] originalArray, string[] newArray)\n {\n int startIndexForNewArray = originalArray.Length;\n Array.Resize&lt;string&gt;(ref originalArray, originalArray.Length + newArray.Length);\n newArray.CopyTo(originalArray, startIndexForNewArray);\n return originalArray;\n }\n</code></pre>\n" }, { "answer_id": 5780240, "author": "Gia Duong Duc Minh", "author_id": 701950, "author_profile": "https://Stackoverflow.com/users/701950", "pm_score": 2, "selected": false, "text": "<pre><code>string str = \"string \";\nList&lt;string&gt; li_str = new List&lt;string&gt;();\n for (int k = 0; k &lt; 100; i++ )\n li_str.Add(str+k.ToString());\nstring[] arr_str = li_str.ToArray();\n</code></pre>\n" }, { "answer_id": 7116251, "author": "Stephen Chung", "author_id": 650891, "author_profile": "https://Stackoverflow.com/users/650891", "pm_score": 6, "selected": false, "text": "<p>Using LINQ:</p>\n\n<pre><code>arr = (arr ?? Enumerable.Empty&lt;string&gt;()).Concat(new[] { newitem }).ToArray();\n</code></pre>\n\n<p>I like using this as it is a one-liner and very convenient to embed in a switch statement, a simple if-statement, or pass as argument.</p>\n\n<p><strong>EDIT:</strong></p>\n\n<p>Some people don't like <code>new[] { newitem }</code> because it creates a small, one-item, temporary array. Here is a version using <code>Enumerable.Repeat</code> that does not require creating any object (at least not on the surface -- .NET iterators probably create a bunch of state machine objects under the table).</p>\n\n<pre><code>arr = (arr ?? Enumerable.Empty&lt;string&gt;()).Concat(Enumerable.Repeat(newitem,1)).ToArray();\n</code></pre>\n\n<p>And if you are sure that the array is never <code>null</code> to start with, you can simplify it to:</p>\n\n<pre><code>arr.Concat(Enumerable.Repeat(newitem,1)).ToArray();\n</code></pre>\n\n<p>Notice that if you want to add items to a an ordered collection, <code>List</code> is probably the data structure you want, not an array to start with.</p>\n" }, { "answer_id": 7116358, "author": "Gaijinhunter", "author_id": 754233, "author_profile": "https://Stackoverflow.com/users/754233", "pm_score": 0, "selected": false, "text": "<p>Why not try out using the <strong>Stringbuilder</strong> class. It has methods such as .insert and .append. You can read more about it here: <a href=\"http://msdn.microsoft.com/en-us/library/2839d5h5(v=vs.71).aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/2839d5h5(v=vs.71).aspx</a></p>\n" }, { "answer_id": 8616931, "author": "tmania", "author_id": 538280, "author_profile": "https://Stackoverflow.com/users/538280", "pm_score": 5, "selected": false, "text": "<pre><code> Array.Resize(ref youur_array_name, your_array_name.Length + 1);\n your_array_name[your_array_name.Length - 1] = \"new item\";\n</code></pre>\n" }, { "answer_id": 8657340, "author": "JAR", "author_id": 1119354, "author_profile": "https://Stackoverflow.com/users/1119354", "pm_score": 0, "selected": false, "text": "<p>Unfortunately using a list won't work in all situations. A list and an array are actually different and are not 100% interchangeable. It would depend on the circumstances if this would be an acceptable work around.</p>\n" }, { "answer_id": 10799751, "author": "Axxelsian", "author_id": 1398693, "author_profile": "https://Stackoverflow.com/users/1398693", "pm_score": 2, "selected": false, "text": "<p>Using a list would be your best option for memory management.</p>\n" }, { "answer_id": 11035286, "author": "dblood", "author_id": 673545, "author_profile": "https://Stackoverflow.com/users/673545", "pm_score": 3, "selected": false, "text": "<p>You can expand on the answer provided by @Stephen Chung by using his LINQ based logic to create an extension method using a generic type.</p>\n\n<pre><code>public static class CollectionHelper\n{\n public static IEnumerable&lt;T&gt; Add&lt;T&gt;(this IEnumerable&lt;T&gt; sequence, T item)\n {\n return (sequence ?? Enumerable.Empty&lt;T&gt;()).Concat(new[] { item });\n }\n\n public static T[] AddRangeToArray&lt;T&gt;(this T[] sequence, T[] items)\n {\n return (sequence ?? Enumerable.Empty&lt;T&gt;()).Concat(items).ToArray();\n }\n\n public static T[] AddToArray&lt;T&gt;(this T[] sequence, T item)\n {\n return Add(sequence, item).ToArray();\n }\n\n}\n</code></pre>\n\n<p>You can then call it directly on the array like this.</p>\n\n<pre><code> public void AddToArray(string[] options)\n {\n // Add one item\n options = options.AddToArray(\"New Item\");\n\n // Add a \n options = options.AddRangeToArray(new string[] { \"one\", \"two\", \"three\" });\n\n // Do stuff...\n }\n</code></pre>\n\n<p>Admittedly, the AddRangeToArray() method seems a bit overkill since you have the same functionality with Concat() but this way the end code can \"work\" with the array directly\nas opposed to this:</p>\n\n<pre><code>options = options.Concat(new string[] { \"one\", \"two\", \"three\" }).ToArray();\n</code></pre>\n" }, { "answer_id": 26710916, "author": "Suren", "author_id": 428061, "author_profile": "https://Stackoverflow.com/users/428061", "pm_score": 3, "selected": false, "text": "<h2>It's better to keeps Array immutable and fixed size.</h2>\n\n<p>you can simulate <code>Add</code> by <code>Extension Method</code> and <code>IEnumerable.Concat()</code></p>\n\n<pre><code>public static class ArrayExtensions\n {\n public static string[] Add(this string[] array, string item)\n {\n return array.Concat(new[] {item}).ToArray();\n }\n }\n</code></pre>\n" }, { "answer_id": 36759482, "author": "Saif", "author_id": 5362552, "author_profile": "https://Stackoverflow.com/users/5362552", "pm_score": 0, "selected": false, "text": "<p>Since this question not satisfied with provided answer, I would like to add this answer :)</p>\n\n<pre><code>public class CustomArrayList&lt;T&gt; \n { \n private T[] arr; private int count; \n\npublic int Count \n { \n get \n { \n return this.count; \n } \n } \n private const int INITIAL_CAPACITY = 4; \n\n public CustomArrayList(int capacity = INITIAL_CAPACITY) \n { \n this.arr = new T[capacity]; this.count = 0; \n } \n\n public void Add(T item) \n { \n GrowIfArrIsFull(); \n this.arr[this.count] = item; this.count++; \n } \n\npublic void Insert(int index, T item) \n{ \n if (index &gt; this.count || index &lt; 0) \n { \n throw new IndexOutOfRangeException( \"Invalid index: \" + index); \n } \n GrowIfArrIsFull(); \n Array.Copy(this.arr, index, this.arr, index + 1, this.count - index); \n this.arr[index] = item; this.count++; } \n\n private void GrowIfArrIsFull() \n { \n if (this.count + 1 &gt; this.arr.Length) \n { \n T[] extendedArr = new T[this.arr.Length * 2]; \n Array.Copy(this.arr, extendedArr, this.count); \n this.arr = extendedArr; \n } \n }\n }\n}\n</code></pre>\n" }, { "answer_id": 37369110, "author": "stackuser83", "author_id": 832705, "author_profile": "https://Stackoverflow.com/users/832705", "pm_score": 3, "selected": false, "text": "<p>if you are working a lot with arrays and not lists for some reason, this generic typed return generic method <code>Add</code> might help</p>\n\n<pre><code> public static T[] Add&lt;T&gt;(T[] array, T item)\n {\n T[] returnarray = new T[array.Length + 1];\n for (int i = 0; i &lt; array.Length; i++)\n {\n returnarray[i] = array[i];\n }\n returnarray[array.Length] = item;\n return returnarray;\n }\n</code></pre>\n" }, { "answer_id": 37695587, "author": "Grimace of Despair", "author_id": 281084, "author_profile": "https://Stackoverflow.com/users/281084", "pm_score": 5, "selected": false, "text": "<p>Very old question, but still wanted to add this.</p>\n\n<p>If you're looking for a one-liner, you can use the code below. It combines the list constructor that accepts an enumerable and the \"new\" (since question raised) initializer syntax.</p>\n\n<pre><code>myArray = new List&lt;string&gt;(myArray) { \"add this\" }.ToArray();\n</code></pre>\n" }, { "answer_id": 42800892, "author": "William", "author_id": 907734, "author_profile": "https://Stackoverflow.com/users/907734", "pm_score": 2, "selected": false, "text": "<p>What about using an extension method? For instance:</p>\n\n<pre><code>public static IEnumerable&lt;TSource&gt; Union&lt;TSource&gt;(this IEnumerable&lt;TSource&gt; source, TSource item)\n{\n return source.Union(new TSource[] { item });\n}\n</code></pre>\n\n<p>for instance:</p>\n\n<pre><code>string[] sourceArray = new []\n{\n \"foo\",\n \"bar\"\n}\nstring additionalItem = \"foobar\";\nstring result = sourceArray.Union(additionalItem);\n</code></pre>\n\n<p>Note this mimics this behavior of Linq's Uniion extension (used to combine two arrays into a new one), and required the Linq library to function.</p>\n" }, { "answer_id": 46234371, "author": "Adi_Pithwa", "author_id": 2298846, "author_profile": "https://Stackoverflow.com/users/2298846", "pm_score": 3, "selected": false, "text": "<p>So if you have a existing array, my quick fix will be</p>\n\n<pre><code>var tempList = originalArray.ToList();\ntempList.Add(newitem);\n</code></pre>\n\n<p>Now just replace the original array with the new one</p>\n\n<pre><code>originalArray = tempList.ToArray();\n</code></pre>\n" }, { "answer_id": 50772992, "author": "Walter Verhoeven", "author_id": 8000382, "author_profile": "https://Stackoverflow.com/users/8000382", "pm_score": 3, "selected": false, "text": "<p>All proposed answers do the same as what they say they'd like to avoid, creating a new array and adding a new entry in it only with lost more overhead. \nLINQ is not magic, list of T is an array with a buffer space with some extra space as to avoid resizing the inner array when items are added. </p>\n\n<p>All the abstractions have to solve the same issue, create an array with no empty slots that hold all values and return them. </p>\n\n<p>If you need the flexibility an can create a large enough list that you can use to pass then do that. else use an array and share that thread-safe object. Also, the new Span helps to share data without having to copy the lists around. </p>\n\n<p>To answer the question:</p>\n\n<pre><code>Array.Resize(ref myArray, myArray.Length + 1);\ndata[myArray.Length - 1] = Value;\n</code></pre>\n" }, { "answer_id": 60377314, "author": "0xced", "author_id": 21698, "author_profile": "https://Stackoverflow.com/users/21698", "pm_score": 3, "selected": false, "text": "<p>A new <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.append\" rel=\"noreferrer\"><code>Append&lt;TSource&gt;</code></a> method has been added to <code>IEnumerable&lt;TSource&gt;</code> since .NET Framework 4.7.1 and .NET Core 1.0.</p>\n\n<p>Here is how to use it:</p>\n\n<pre><code>var numbers = new [] { \"one\", \"two\", \"three\" };\nnumbers = numbers.Append(\"four\").ToArray();\nConsole.WriteLine(string.Join(\", \", numbers)); // one, two, three, four\n</code></pre>\n\n<p>Note that if you want to add the element at the beginning of the array, you can use the new <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.prepend\" rel=\"noreferrer\"><code>Prepend&lt;TSource&gt;</code></a> method instead.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27101/" ]
On Windows Mobile, I am displaying my output in HTML. This includes lots of user-generated strings. Occasionally there are situations where a really large string is part of the output that has no whitespaces or punctuation. Unfortunately the Windows Mobile's HTML view (htmlview.dll, based on Pocket Internet Explorer) does not break these long words down so they fit on screen. Instead a horizontal scrollbar is added and the user has to scroll sideways to see the whole word. This also affects other output which now also is spread along this larger screen width. Is there any possibility to either make the htmlview behave differently, or to force the word to break? CSS can be used. Regarding the forcing: The &shy; tag is ALWAYS inserting a "-" character and never causes a breaks, the <WBR> tag is not doing anything at all, &8203; is output as &8203:, empty tags like also do nothing. Also it should be noted that this code is running on multiple screen sizes and due to other parts of the HTML output I am not 100% sure how much screen width I have left. P.S.: My app is compiled using the WM 5.0 SDK and is written in C++/Win32/MFC.
I would use a List if you need a dynamically sized array: ``` List<string> ls = new List<string>(); ls.Add("Hello"); ```
249,467
<p>I've heard of "error" when using floating point variables. Now I'm trying to solve this puzzle and I think I'm getting some rounding/floating point error. So I'm finally going to figure out the basics of floating point error.</p> <p>What is a simple example of floating point/rounding error (preferably in C++) ?</p> <p>Edit: For example say I have an event that has probability p of succeeding. I do this event 10 times (p does not change and all trials are independent). What is the probability of exactly 2 successful trials? I have this coded as:</p> <pre><code>double p_2x_success = pow(1-p, (double)8) * pow(p, (double)2) * (double)choose(8, 2); </code></pre> <p>Is this an opportunity for floating point error?</p>
[ { "answer_id": 249498, "author": "Matthew Schinckel", "author_id": 188, "author_profile": "https://Stackoverflow.com/users/188", "pm_score": 4, "selected": false, "text": "<p>Generally, floating point error refers to when a number that cannot be stored in the IEEE floating point representation.</p>\n\n<p>Integers are stored with the right-most bit being 1, and each bit to the left being double that (2,4,8,...). It's easy to see that this can store any integer up to 2^n, where n is the number of bits.</p>\n\n<p>The mantissa (decimal part) of a floating point number is stored in a similar way, but moving left to right, and each successive bit being half of the value of the previous one. (It's actually a little more complicated than this, but it will do for now).</p>\n\n<p>Thus, numbers like 0.5 (1/2) are easy to store, but not every number &lt;1 can be created by adding a fixed number of fractions of the form 1/2, 1/4, 1/8, ...</p>\n\n<p>A really simple example is 0.1, or 1/10. This can be done with an infinite series (which I can't really be bothered working out), but whenever a computer stores 0.1, it's not exactly this number that is stored.</p>\n\n<p>If you have access to a Unix machine, it's easy to see this:</p>\n\n<pre><code>Python 2.5.1 (r251:54863, Apr 15 2008, 22:57:26) \n[GCC 4.0.1 (Apple Inc. build 5465)] on darwin\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n&gt;&gt;&gt; 0.1\n0.10000000000000001\n&gt;&gt;&gt; \n</code></pre>\n\n<p>You'll want to be really careful with equality tests with floats and doubles, in whatever language you are in.</p>\n\n<p>(As for your example, 0.2 is another one of those pesky numbers that cannot be stored in IEEE binary, but as long as you are testing inequalities, rather than equalities, like p &lt;= 0.2, then you'll be okay.)</p>\n" }, { "answer_id": 249526, "author": "SmacL", "author_id": 22564, "author_profile": "https://Stackoverflow.com/users/22564", "pm_score": 3, "selected": false, "text": "<p>A simple example in C that caught me a while back :</p>\n<pre><code>double d = 0;\nsscanf(&quot;90.1000&quot;, &quot;%lf&quot;, &amp;d);\nprintf(&quot;%0.4f&quot;, d);\n</code></pre>\n<p>This prints <code>90.0999</code></p>\n<p>This was in a function that converted angles in DMS to radians.</p>\n<p>Why does it not work in the above case?</p>\n" }, { "answer_id": 249777, "author": "Motti", "author_id": 3848, "author_profile": "https://Stackoverflow.com/users/3848", "pm_score": 5, "selected": false, "text": "<pre><code> for(double d = 0; d != 0.3; d += 0.1); // never terminates \n</code></pre>\n" }, { "answer_id": 5694505, "author": "Agnius Vasiliauskas", "author_id": 380331, "author_profile": "https://Stackoverflow.com/users/380331", "pm_score": 6, "selected": false, "text": "<p>Picture is worth a thousand words - try to draw equation <code>f(k)</code> :<br> <img src=\"https://i.stack.imgur.com/bZcxI.gif\" alt=\"enter image description here\"> <br>and you will get such XY graph (X and Y are in logarithmic scale).<br>\n<img src=\"https://i.stack.imgur.com/UVWuE.png\" alt=\"enter image description here\">\n<br>If computer could represent 32-bit floats without rounding error then for every <code>k</code> we should get zero. But instead error increases with bigger values of k because of floating point error accumulation.</p>\n\n<p>hth!</p>\n" }, { "answer_id": 27529238, "author": "Rory O'Bryan", "author_id": 1347502, "author_profile": "https://Stackoverflow.com/users/1347502", "pm_score": 3, "selected": false, "text": "<p>Here's one that caught me :</p>\n\n<pre><code> round(256.49999) == 256\nroundf(256.49999) == 257\n</code></pre>\n\n<p>doubles and floats have different precision, so the first will be represented as <code>256.49999000000003</code>, and the second one as <code>256.5</code>, and will thus be rounded differently</p>\n" }, { "answer_id": 53177677, "author": "Samuel Li", "author_id": 2108824, "author_profile": "https://Stackoverflow.com/users/2108824", "pm_score": 3, "selected": false, "text": "<p>I like this one from a Python interpreter: </p>\n\n<pre><code>Python 2.7.10 (default, Oct 6 2017, 22:29:07) \n[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.31)] on darwin\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n&gt;&gt;&gt; 0.1+0.2\n0.30000000000000004\n&gt;&gt;&gt;\n</code></pre>\n" }, { "answer_id": 57495203, "author": "formiaczek", "author_id": 1266432, "author_profile": "https://Stackoverflow.com/users/1266432", "pm_score": 2, "selected": false, "text": "<p>super simple (Python):</p>\n<pre><code>a = 10000000.1\nb = 1/10\nprint(a - b == 10000000)\nprint ('a:{0:.20f}\\nb:{1:.20f}'.format(a, b))\n</code></pre>\n<p>prints (depending on the platform) something like:</p>\n<pre><code>False \na:10000000.09999999962747097015 \nb:0.10000000000000000555 \n</code></pre>\n" }, { "answer_id": 61917303, "author": "Danilo Pianini", "author_id": 1916413, "author_profile": "https://Stackoverflow.com/users/1916413", "pm_score": 3, "selected": false, "text": "<p>This is the simplest that comes to my mind, that should work with many languages is simply:</p>\n\n<pre class=\"lang-kotlin prettyprint-override\"><code>0.2 + 0.1\n</code></pre>\n\n<p>Here are some examples with the REPLs that come into my mind, but should return this result on any IEEE754-compliant language.</p>\n\n<p>Python</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>&gt;&gt;&gt; 0.2 + 0.1\n0.30000000000000004\n</code></pre>\n\n<p>Kotlin</p>\n\n<pre class=\"lang-kotlin prettyprint-override\"><code>0.2 + 0.1\nres0: kotlin.Double = 0.30000000000000004\n</code></pre>\n\n<p>Scala</p>\n\n<pre><code>scala&gt; 0.2 + 0.1\nval res0: Double = 0.30000000000000004\n</code></pre>\n\n<p>Java</p>\n\n<pre><code>jshell&gt; 0.2 + 0.1\n$1 ==&gt; 0.30000000000000004\n</code></pre>\n\n<p>Ruby</p>\n\n<pre class=\"lang-rb prettyprint-override\"><code>irb(main):001:0&gt; 0.2 + 0.1\n=&gt; 0.30000000000000004\n</code></pre>\n" }, { "answer_id": 67477450, "author": "x-yuri", "author_id": 52499, "author_profile": "https://Stackoverflow.com/users/52499", "pm_score": 0, "selected": false, "text": "<p>I think Ruby has a good example in <a href=\"https://ruby-doc.org/stdlib-2.5.1/libdoc/bigdecimal/rdoc/BigDecimal.html\" rel=\"nofollow noreferrer\">its documentation</a>:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>sum = 0\n10_000.times do\n sum = sum + 0.0001\nend\nprint sum #=&gt; 0.9999999999999062\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249467", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22471/" ]
I've heard of "error" when using floating point variables. Now I'm trying to solve this puzzle and I think I'm getting some rounding/floating point error. So I'm finally going to figure out the basics of floating point error. What is a simple example of floating point/rounding error (preferably in C++) ? Edit: For example say I have an event that has probability p of succeeding. I do this event 10 times (p does not change and all trials are independent). What is the probability of exactly 2 successful trials? I have this coded as: ``` double p_2x_success = pow(1-p, (double)8) * pow(p, (double)2) * (double)choose(8, 2); ``` Is this an opportunity for floating point error?
Picture is worth a thousand words - try to draw equation `f(k)` : ![enter image description here](https://i.stack.imgur.com/bZcxI.gif) and you will get such XY graph (X and Y are in logarithmic scale). ![enter image description here](https://i.stack.imgur.com/UVWuE.png) If computer could represent 32-bit floats without rounding error then for every `k` we should get zero. But instead error increases with bigger values of k because of floating point error accumulation. hth!
249,470
<p>What would be a simple implementation of a method to convert a String like "Hello there everyone" to "helloThereEveryone". In JavaME support for String and StringBuffer utility operations are quite limited.</p>
[ { "answer_id": 249510, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 0, "selected": false, "text": "<p>Suggestion:</p>\n\n<p>May be if you can <a href=\"https://stackoverflow.com/questions/121988/how-can-i-add-a-regex-match-to-my-j2me-project\">port one regexp library on J2ME</a>, you could use it to strip spaces in your String...</p>\n" }, { "answer_id": 249512, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 3, "selected": true, "text": "<p>Quick primitive implementation. I have no idea of restrictions of J2ME, so I hope it fits or it gives some ideas...</p>\n\n<pre><code>String str = \"Hello, there, everyone?\";\n\nStringBuffer result = new StringBuffer(str.length());\nString strl = str.toLowerCase();\nboolean bMustCapitalize = false;\nfor (int i = 0; i &lt; strl.length(); i++)\n{\n char c = strl.charAt(i);\n if (c &gt;= 'a' &amp;&amp; c &lt;= 'z')\n {\n if (bMustCapitalize)\n {\n result.append(strl.substring(i, i+1).toUpperCase());\n bMustCapitalize = false;\n }\n else\n {\n result.append(c);\n }\n }\n else\n {\n bMustCapitalize = true;\n }\n}\nSystem.out.println(result);\n</code></pre>\n\n<p>You can replace the convoluted uppercase append with:</p>\n\n<pre><code>result.append((char) (c - 0x20));\n</code></pre>\n\n<p>although it might seem more hackish.</p>\n" }, { "answer_id": 249513, "author": "michelemarcon", "author_id": 15173, "author_profile": "https://Stackoverflow.com/users/15173", "pm_score": 1, "selected": false, "text": "<p>With CDC, you have:</p>\n\n<p>String.getBytes();//to convert the string to an array of bytes\nString.indexOf(int ch); //for locating the beginning of the words\nString.trim();//to remove spaces</p>\n\n<p>For lower/uppercase you need to add(subtract) 32.</p>\n\n<p>With these elements, you can build your own method.</p>\n" }, { "answer_id": 10498249, "author": "RURANGIRWA Bailly", "author_id": 1381989, "author_profile": "https://Stackoverflow.com/users/1381989", "pm_score": -1, "selected": false, "text": "<p>I would do it like this: </p>\n\n<pre><code>private String toCamelCase(String s) {\n StringBuffer sb = new StringBuffer();\n String[] x = s.replaceAll(\"[^A-Za-z]\", \" \").replaceAll(\"\\\\s+\", \" \")\n .trim().split(\" \");\n\n for (int i = 0; i &lt; x.length; i++) {\n if (i == 0) {\n x[i] = x[i].toLowerCase();\n } else {\n String r = x[i].substring(1);\n x[i] = String.valueOf(x[i].charAt(0)).toUpperCase() + r;\n\n }\n sb.append(x[i]);\n }\n return sb.toString();\n}\n</code></pre>\n" }, { "answer_id": 11089164, "author": "Tibi", "author_id": 1464565, "author_profile": "https://Stackoverflow.com/users/1464565", "pm_score": -1, "selected": false, "text": "<p>check this</p>\n\n<pre><code>import org.apache.commons.lang.WordUtils;\n\nString camel = WordUtils.capitalizeFully('I WANT TO BE A CAMEL', new char[]{' '});\n\nreturn camel.replaceAll(\" \", \"\");\n</code></pre>\n" }, { "answer_id": 11433313, "author": "qoss", "author_id": 1517835, "author_profile": "https://Stackoverflow.com/users/1517835", "pm_score": -1, "selected": false, "text": "<p>I would suggest the following simple code:</p>\n\n<pre><code> String camelCased = \"\";\n String[] tokens = inputString.split(\"\\\\s\");\n for (int i = 0; i &lt; tokens.length; i++) {\n String token = tokens[i];\n camelCased = camelCased + token.substring(0, 1).toUpperCase() + token.substring(1, token.length());\n }\n return camelCased;\n</code></pre>\n" }, { "answer_id": 16310578, "author": "Cheeso", "author_id": 48082, "author_profile": "https://Stackoverflow.com/users/48082", "pm_score": 1, "selected": false, "text": "<pre><code>private static String toCamelCase(String s) {\n String result = \"\";\n String[] tokens = s.split(\"_\"); // or whatever the divider is\n for (int i = 0, L = tokens.length; i&lt;L; i++) {\n String token = tokens[i];\n if (i==0) result = token.toLowerCase();\n else\n result += token.substring(0, 1).toUpperCase() +\n token.substring(1, token.length()).toLowerCase();\n }\n return result;\n}\n</code></pre>\n" }, { "answer_id": 33007028, "author": "HS Shin", "author_id": 4853250, "author_profile": "https://Stackoverflow.com/users/4853250", "pm_score": 0, "selected": false, "text": "<p>Try following code</p>\n\n<pre><code>public static String toCamel(String str) {\n String rtn = str;\n rtn = rtn.toLowerCase();\n Matcher m = Pattern.compile(\"_([a-z]{1})\").matcher(rtn);\n StringBuffer sb = new StringBuffer();\n while (m.find()) {\n m.appendReplacement(sb, m.group(1).toUpperCase());\n }\n m.appendTail(sb);\n rtn = sb.toString();\n return rtn;\n}\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249470", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22012/" ]
What would be a simple implementation of a method to convert a String like "Hello there everyone" to "helloThereEveryone". In JavaME support for String and StringBuffer utility operations are quite limited.
Quick primitive implementation. I have no idea of restrictions of J2ME, so I hope it fits or it gives some ideas... ``` String str = "Hello, there, everyone?"; StringBuffer result = new StringBuffer(str.length()); String strl = str.toLowerCase(); boolean bMustCapitalize = false; for (int i = 0; i < strl.length(); i++) { char c = strl.charAt(i); if (c >= 'a' && c <= 'z') { if (bMustCapitalize) { result.append(strl.substring(i, i+1).toUpperCase()); bMustCapitalize = false; } else { result.append(c); } } else { bMustCapitalize = true; } } System.out.println(result); ``` You can replace the convoluted uppercase append with: ``` result.append((char) (c - 0x20)); ``` although it might seem more hackish.
249,499
<p>Evaluate:</p> <pre><code>((((lambda (x) (lambda (y) (lambda (x) (+ x y)))) 3) 4) 5) </code></pre> <p>This is what I did:</p> <ul> <li><p>evaluate <code>((((lambda (x) (lambda (y) (lambda (x) (+ x y)))) 3) 4) 5)</code></p> <ul> <li>evaluate <code>5 -&gt; 5</code></li> </ul></li> <li><p>evaluate <code>(((lambda (x) (lambda (y) (lambda (x) (+ x y)))) 3) 4)</code></p> <ul> <li>evaluate <code>4 -&gt; 4</code></li> </ul></li> <li><p>evaluate <code>((lambda (x) (lambda (y) (lambda (x) (+ x y)))) 3)</code></p> <ul> <li>evaluate <code>3 -&gt; 3</code></li> </ul></li> <li><p><code>(lambda (x) (lambda (y) (lambda (x) (+ x y))))</code> -> <code>(lambda (x) (lambda (y) (lambda (x) (+ x y))))</code></p></li> <li><p>apply <code>(lambda (x) (lambda (y) (lambda (x) (+ x y))))</code> to <code>3</code></p> <ul> <li><p>substitute <code>3</code> -> <code>x</code> in <code>(lambda (y) (lambda (x) (+ x y))</code></p></li> <li><p><code>(lambda (y) (lambda (x) (+ 3 y))</code></p></li> <li><p>evaluate <code>(lambda (y) (lambda (x) (+ 3 y)) -&gt; (lambda (y) (lambda (x) (+ 3 y))</code></p></li> <li><p><code>apply (lambda (y) (lambda (x) (+ 3 y))</code> to <code>4</code></p></li> <li><p>subsitute <code>4 -&gt; y</code> in <code>(lambda (y) (lambda (x) (+ 3 y))</code></p></li> <li><p><code>(lambda (y) (+ 3 4))</code></p></li> <li><p>evaluate <code>(lambda (y) (+ 3 4)) -&gt; (lambda (y) (7))</code></p> <ul> <li>subsitute <code>5</code> -> ?</li> </ul></li> </ul></li> </ul> <p>And then I'm stuck.</p>
[ { "answer_id": 249520, "author": "leppie", "author_id": 15541, "author_profile": "https://Stackoverflow.com/users/15541", "pm_score": 2, "selected": false, "text": "<p>I suggest you break this down into individual 'defined' procedures.</p>\n\n<pre><code>(define part1 (lambda (y) (lambda (x) (+ x y)))) ; basically an adder\n(define part2 (lambda (x) part1)) ; just return part1, x has no effect\n</code></pre>\n\n<p>Now call <code>(((part2 3) 4) 5) =&gt; 9</code></p>\n" }, { "answer_id": 249537, "author": "Matthias Benkard", "author_id": 15517, "author_profile": "https://Stackoverflow.com/users/15517", "pm_score": 1, "selected": false, "text": "<pre><code>-substitute 3 -&gt; x in (lambda (y) (lambda (x) (+ x y))\n-(lambda (y) (lambda (x) (+ 3 y))\n</code></pre>\n\n<p>First, this is wrong. You don't substitute <code>3</code> for all occurrences of <code>x</code>, only for the free ones. The <code>x</code> you're replacing here is bound by the inner lambda expression and therefore not free.</p>\n\n<p>Second, there's nothing wrong with substituting a value for a variable that's never used, so substituting <code>5</code> for <code>y</code> in <code>(+ 3 4)</code> is fine and yields <code>(+ 3 4)</code>.</p>\n" }, { "answer_id": 249539, "author": "mweerden", "author_id": 4285, "author_profile": "https://Stackoverflow.com/users/4285", "pm_score": 1, "selected": false, "text": "<p>Your first substitution is wrong; the <code>x</code> in <code>(+ x y)</code> is bound by the innermost <code>lambda</code>, not the outermost. This means the result of that substitution is just <code>(lambda (y) (lambda (x) (+ x y)))</code>. The <code>3</code> is \"lost\". (Perhaps you should look up the substitution rules and apply them step by step to getter a better grasp of it.)</p>\n\n<p>Regardless of this, to finish you can still apply <code>(lambda (y) (7))</code> (or <code>(lambda (y) (+ 4 x))</code> if you fix the above) to <code>5</code> to get <code>7</code> (or <code>(+ 4 5)</code> which evaluates to <code>9</code>).</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249499", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30622/" ]
Evaluate: ``` ((((lambda (x) (lambda (y) (lambda (x) (+ x y)))) 3) 4) 5) ``` This is what I did: * evaluate `((((lambda (x) (lambda (y) (lambda (x) (+ x y)))) 3) 4) 5)` + evaluate `5 -> 5` * evaluate `(((lambda (x) (lambda (y) (lambda (x) (+ x y)))) 3) 4)` + evaluate `4 -> 4` * evaluate `((lambda (x) (lambda (y) (lambda (x) (+ x y)))) 3)` + evaluate `3 -> 3` * `(lambda (x) (lambda (y) (lambda (x) (+ x y))))` -> `(lambda (x) (lambda (y) (lambda (x) (+ x y))))` * apply `(lambda (x) (lambda (y) (lambda (x) (+ x y))))` to `3` + substitute `3` -> `x` in `(lambda (y) (lambda (x) (+ x y))` + `(lambda (y) (lambda (x) (+ 3 y))` + evaluate `(lambda (y) (lambda (x) (+ 3 y)) -> (lambda (y) (lambda (x) (+ 3 y))` + `apply (lambda (y) (lambda (x) (+ 3 y))` to `4` + subsitute `4 -> y` in `(lambda (y) (lambda (x) (+ 3 y))` + `(lambda (y) (+ 3 4))` + evaluate `(lambda (y) (+ 3 4)) -> (lambda (y) (7))` - subsitute `5` -> ? And then I'm stuck.
I suggest you break this down into individual 'defined' procedures. ``` (define part1 (lambda (y) (lambda (x) (+ x y)))) ; basically an adder (define part2 (lambda (x) part1)) ; just return part1, x has no effect ``` Now call `(((part2 3) 4) 5) => 9`
249,500
<p>OK, I have a somewhat complicated system in C++. In a nutshell, I need to add a method to a third party abstract base class. The third party also provides a ton of derived classes that also need the new functionality.</p> <p>I'm using a library that provides a standard Shape interface, as well as some common shapes.</p> <pre><code>class Shape { public: Shape(position); virtual ~Shape(); virtual position GetPosition() const; virtual void SetPosition(position); virtual double GetPerimeter() const = 0; private: ... }; class Square : public Shape { public: Square(position, side_length); ... }; class Circle, Rectangle, Hexagon, etc </code></pre> <p>Now, here's my problem. I want the Shape class to also include a GetArea() function. So it seems like I should just do a:</p> <pre><code>class ImprovedShape : public virtual Shape { virtual double GetArea() const = 0; }; class ImprovedSquare : public Square, public ImprovedShape { ... } </code></pre> <p>And then I go and make an ImprovedSquare that inherits from ImprovedShape and Square. Well, as you can see, I have now created the dreaded <a href="http://en.wikipedia.org/wiki/Diamond_problem" rel="nofollow noreferrer">diamond inheritance problem</a>. This would easily be fixed if the third party library used <a href="http://en.wikipedia.org/wiki/Virtual_inheritance" rel="nofollow noreferrer">virtual inheritance</a> for their Square, Circle, etc. However, getting them to do that isn't a reasonable option.</p> <p>So, what do you do when you need to add a little functionality to an interface defined in a library? Is there a good answer?</p> <p>Thanks!</p>
[ { "answer_id": 249515, "author": "andreas buykx", "author_id": 19863, "author_profile": "https://Stackoverflow.com/users/19863", "pm_score": 2, "selected": false, "text": "<p>I suppose the <a href=\"http://en.wikipedia.org/wiki/Facade_pattern\" rel=\"nofollow noreferrer\">facade</a> pattern should do the trick.</p>\n\n<p>Wrap the 3rd party interface into an interface of your own, and your application's code works with the wrapper interface rather than the 3rd party interface. That way you've nicely insulated changes in the uncontrolled 3rd party interface as well.</p>\n" }, { "answer_id": 249525, "author": "Gorpik", "author_id": 25824, "author_profile": "https://Stackoverflow.com/users/25824", "pm_score": 3, "selected": true, "text": "<p>We had a very similar problem in a project and we solved it by just NOT deriving ImprovedShape from Shape. If you need Shape functionality in ImprovedShape you can dynamic_cast, knowing that your cast will always work. And the rest is just like in your example.</p>\n" }, { "answer_id": 249666, "author": "Dave Hillier", "author_id": 1575281, "author_profile": "https://Stackoverflow.com/users/1575281", "pm_score": 3, "selected": false, "text": "<p>Why does this class need to derive from shape?</p>\n\n<pre><code>class ImprovedShape : public virtual Shape\n{\n virtual double GetArea() const = 0;\n};\n</code></pre>\n\n<p>Why not just have</p>\n\n<pre><code>class ThingWithArea \n{\n virtual double GetArea() const = 0;\n};\n</code></pre>\n\n<p>ImprovedSquare is a Shape and is a ThingWithArea</p>\n" }, { "answer_id": 249696, "author": "Dave Van den Eynde", "author_id": 455874, "author_profile": "https://Stackoverflow.com/users/455874", "pm_score": 2, "selected": false, "text": "<p>Perhaps you should read up on <a href=\"http://www.parashift.com/c++-faq-lite/proper-inheritance.html\" rel=\"nofollow noreferrer\">proper inheritance</a>, and conclude that ImprovedShape does not need to inherit from Shape but instead can use Shape for its drawing functionality, similar to the discussion in point 21.12 on that FAQ on how a SortedList doesn't have to inherit from List even if it wants to provide the same functionality, it can simply <em>use</em> a List.</p>\n\n<p>In a similar fashion, ImprovedShape can <em>use</em> a Shape to do it's Shape things.</p>\n" }, { "answer_id": 249712, "author": "Binary Worrier", "author_id": 18797, "author_profile": "https://Stackoverflow.com/users/18797", "pm_score": 2, "selected": false, "text": "<p>Possibly a use for the decorator pattern? [<a href=\"http://en.wikipedia.org/wiki/Decorator_pattern][1]\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Decorator_pattern][1]</a></p>\n" }, { "answer_id": 250443, "author": "twokats", "author_id": 24263, "author_profile": "https://Stackoverflow.com/users/24263", "pm_score": 1, "selected": false, "text": "<p>Is it possible to do a completely different approach - using templates and meta-programming techniques? If you're not constrained to not using templates, this could provide an elegant solution. Only <code>ImprovedShape</code> and <code>ImprovedSquare</code> change:</p>\n\n<pre><code>template &lt;typename ShapePolicy&gt;\nclass ImprovedShape : public ShapePolicy\n{\npublic:\n virtual double GetArea();\n ImprovedShape(void);\n virtual ~ImprovedShape(void);\n\nprotected:\n ShapePolicy shape;\n //...\n};\n</code></pre>\n\n<p>and the <code>ImprovedSquare</code> becomes:</p>\n\n<pre><code>class ImprovedSquare : public ImprovedShape&lt;Square&gt;\n{\npublic:\n ImprovedSquare(void);\n ~ImprovedSquare(void);\n\n // ...\n\n};\n</code></pre>\n\n<p>You'll avoid the diamond inheritance, getting both the inheritance from your original Shape (through the policy class) as well as the added functionality you want.</p>\n" }, { "answer_id": 256783, "author": "fizzer", "author_id": 18167, "author_profile": "https://Stackoverflow.com/users/18167", "pm_score": 1, "selected": false, "text": "<p>Dave Hillier's approach is the right one. Separate <code>GetArea()</code> into its own interface:</p>\n\n<pre><code>class ThingWithArea\n{\npublic:\n virtual double GetArea() const = 0;\n};\n</code></pre>\n\n<p>If the designers of Shape had done the right thing and made it a pure interface, \nand the public interfaces of the concrete classes were powerful enough, you could \nhave instances of concrete classes as members. This is how you get <code>SquareWithArea</code>\n(<code>ImprovedSquare</code> is a poor name) being a <code>Shape</code> and a <code>ThingWithArea</code>:</p>\n\n<pre><code>class SquareWithArea : public Shape, public ThingWithArea\n{\npublic:\n double GetPerimeter() const { return square.GetPerimeter(); }\n double GetArea() const { /* do stuff with square */ }\n\nprivate:\n Square square;\n};\n</code></pre>\n\n<p>Unfortunately, the <code>Shape</code> designers put some implementation into <code>Shape</code>, and you \nwould end up carrying two copies of it per <code>SquareWithArea</code>, just like in\nthe diamond you originally proposed.</p>\n\n<p>This pretty much forces you into the most tightly coupled, and therefore least \ndesirable, solution:</p>\n\n<pre><code>class SquareWithArea : public Square, public ThingWithArea\n{\n};\n</code></pre>\n\n<p>These days, it's considered bad form to derive from concrete classes in C++.\nIt's hard to find a really good explanation why you shouldn't. Usually, people \ncite Meyers's More Effective C++ Item 33, which points out the impossibility\nof writing a decent <code>operator=()</code> among other things. Probably, then, you should\nnever do it for classes with value semantics. Another pitfall is where the \nconcrete class doesn't have a virtual destructor (this is why you should \nnever publicly derive from STL containers). Neither applies here. The poster\nwho condescendingly sent you to the C++ faq to learn about inheritance is\nwrong - adding <code>GetArea()</code> does not violate Liskov substitutability. About \nthe only risk I can see comes from overriding virtual functions in the \nconcrete classes, when the implementer later changes the name and silently breaks\nyour code.</p>\n\n<p>In summary, I think you can derive from Square with a clear conscience.\n(As a consolation, you won't have to write all the forwarding functions for\nthe Shape interface).</p>\n\n<p>Now for the problem of functions which need both interfaces. I don't like \nunnecessary <code>dynamic_cast</code>s. Instead, make the function take references to \nboth interfaces and pass references to the same object for both at the call site:</p>\n\n<pre><code>void PrintPerimeterAndArea(const Shape&amp; s, const ThingWithArea&amp; a)\n{\n cout &lt;&lt; s.GetPerimeter() &lt;&lt; endl;\n cout &lt;&lt; a.GetArea() &lt;&lt; endl;\n}\n\n// ...\n\nSquareWithArea swa;\nPrintPerimeterAndArea(swa, swa);\n</code></pre>\n\n<p>All <code>PrintPerimeterAndArea()</code> needs to do its job is a source of perimeter and a \nsource of area. It is not its concern that these happen to be implemented\nas member functions on the same object instance. Conceivably, the area could\nbe supplied by some numerical integration engine between it and the <code>Shape</code>. </p>\n\n<p>This gets us to the only case where I would consider passing in one reference\nand getting the other by <code>dynamic_cast</code> - where it's important that the two\nreferences are to the same object instance. Here's a very contrived example:</p>\n\n<pre><code>void hardcopy(const Shape&amp; s, const ThingWithArea&amp; a)\n{\n Printer p;\n if (p.HasEnoughInk(a.GetArea()))\n {\n s.print(p);\n }\n}\n</code></pre>\n\n<p>Even then, I would probably prefer to send in two references rather than\n<code>dynamic_cast</code>. I would rely on a sane overall system design to eliminate the \npossibility of bits of two different instances being fed to functions like this. </p>\n" }, { "answer_id": 256863, "author": "Pete Kirkham", "author_id": 1527, "author_profile": "https://Stackoverflow.com/users/1527", "pm_score": 1, "selected": false, "text": "<p>Another take on meta-programming/mixin, this time a bit influenced by traits. \nIt assumes that calculating area is something you want to add based on exposed properties; you could do something which kept with encapsulation, it that is a goal, rather than modularisation. But then you have to write a GetArea for every sub-type, rather than using a polymorphic one where possible. Whether that's worthwhile depends on how committed you are to encapsulation, and whether there are base classes in your library you could exploit common behaviour of, like <em>RectangularShape</em> below</p>\n\n<pre><code>#import &lt;iostream&gt;\n\nusing namespace std;\n\n// base types\nclass Shape {\n public:\n Shape () {}\n virtual ~Shape () { }\n virtual void DoShapyStuff () const = 0;\n};\n\nclass RectangularShape : public Shape {\n public:\n RectangularShape () { }\n\n virtual double GetHeight () const = 0 ;\n virtual double GetWidth () const = 0 ;\n};\n\nclass Square : public RectangularShape {\n public:\n Square () { }\n\n virtual void DoShapyStuff () const\n {\n cout &lt;&lt; \"I\\'m a square.\" &lt;&lt; endl;\n }\n\n virtual double GetHeight () const { return 10.0; }\n virtual double GetWidth () const { return 10.0; }\n};\n\nclass Rect : public RectangularShape {\n public:\n Rect () { }\n\n virtual void DoShapyStuff () const\n {\n cout &lt;&lt; \"I\\'m a rectangle.\" &lt;&lt; endl;\n }\n\n virtual double GetHeight () const { return 9.0; }\n virtual double GetWidth () const { return 16.0; }\n};\n\n// extension has a cast to Shape rather than extending Shape\nclass HasArea {\n public:\n virtual double GetArea () const = 0;\n virtual Shape&amp; AsShape () = 0;\n virtual const Shape&amp; AsShape () const = 0;\n\n operator Shape&amp; ()\n {\n return AsShape();\n }\n\n operator const Shape&amp; () const\n {\n return AsShape();\n }\n};\n\ntemplate&lt;class S&gt; struct AreaOf { };\n\n// you have to have the declaration before the ShapeWithArea \n// template if you want to use polymorphic behaviour, which \n// is a bit clunky\nstatic double GetArea (const RectangularShape&amp; shape)\n{\n return shape.GetWidth() * shape.GetHeight();\n}\n\ntemplate &lt;class S&gt;\nclass ShapeWithArea : public S, public HasArea {\n public:\n virtual double GetArea () const\n {\n return ::GetArea(*this);\n }\n virtual Shape&amp; AsShape () { return *this; }\n virtual const Shape&amp; AsShape () const { return *this; }\n};\n\n// don't have to write two implementations of GetArea\n// as we use the GetArea for the super type\ntypedef ShapeWithArea&lt;Square&gt; ImprovedSquare;\ntypedef ShapeWithArea&lt;Rect&gt; ImprovedRect;\n\nvoid Demo (const HasArea&amp; hasArea)\n{\n const Shape&amp; shape(hasArea);\n shape.DoShapyStuff();\n cout &lt;&lt; \"Area = \" &lt;&lt; hasArea.GetArea() &lt;&lt; endl;\n}\n\nint main ()\n{\n ImprovedSquare square;\n ImprovedRect rect;\n\n Demo(square);\n Demo(rect);\n\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 301731, "author": "mstrobl", "author_id": 25965, "author_profile": "https://Stackoverflow.com/users/25965", "pm_score": 0, "selected": false, "text": "<p>There exists a solution to your problem, as I understood the question. Use the <a href=\"http://en.wikipedia.org/wiki/Adapter_pattern\" rel=\"nofollow noreferrer\">addapter-pattern</a>. The adapter pattern is used to <strong>add functionality to a specific class or to exchange particular behaviour</strong> (i.e. methods). Considering the scenario you painted:</p>\n\n<pre><code>class ShapeWithArea : public Shape\n{\n protected:\n Shape* shape_;\n\n public:\n virtual ~ShapeWithArea();\n\n virtual position GetPosition() const { return shape_-&gt;GetPosition(); }\n virtual void SetPosition(position) { shape_-&gt;SetPosition(); }\n virtual double GetPerimeter() const { return shape_-&gt;GetPerimeter(); }\n\n ShapeWithArea (Shape* shape) : shape_(shape) {}\n\n virtual double getArea (void) const = 0;\n};\n</code></pre>\n\n<p>The Adapter-Pattern is meant to adapt the behaviour or functionality of a class. You can use it to</p>\n\n<ul>\n<li><strong>change the behaviour of a class, by not forwarding but reimplementing methods.</strong></li>\n<li><strong>add behaviour to a class, by adding methods.</strong></li>\n</ul>\n\n<p>How does it change behaviour? When you supply an object of type base to a method, you can also supply the adapted class. The object will behave as you instructed it to, the actor on the object will only care about the interface of the base class. <strong>You can apply this adaptor to any derivate of Shape.</strong></p>\n" }, { "answer_id": 3823817, "author": "yasouser", "author_id": 338913, "author_profile": "https://Stackoverflow.com/users/338913", "pm_score": 1, "selected": false, "text": "<p>GetArea() need not be a member. It could be templated function, so that you can invoke it for any Shape.</p>\n\n<p>Something like:</p>\n\n<pre><code>template &lt;class ShapeType, class AreaFunctor&gt; \nint GetArea(const ShapeType&amp; shape, AreaFunctor func);\n</code></pre>\n\n<p>The STL <a href=\"http://www.cplusplus.com/reference/algorithm/min/\" rel=\"nofollow\">min</a>, <a href=\"http://www.cplusplus.com/reference/algorithm/max/\" rel=\"nofollow\">max</a> functions can be thought of as an analogy for your case. You can find a min and max for an array/vector of objects given a comparator function. Like wise, you can derive the area of any given shape provided the function to compute the area.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249500", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3175/" ]
OK, I have a somewhat complicated system in C++. In a nutshell, I need to add a method to a third party abstract base class. The third party also provides a ton of derived classes that also need the new functionality. I'm using a library that provides a standard Shape interface, as well as some common shapes. ``` class Shape { public: Shape(position); virtual ~Shape(); virtual position GetPosition() const; virtual void SetPosition(position); virtual double GetPerimeter() const = 0; private: ... }; class Square : public Shape { public: Square(position, side_length); ... }; class Circle, Rectangle, Hexagon, etc ``` Now, here's my problem. I want the Shape class to also include a GetArea() function. So it seems like I should just do a: ``` class ImprovedShape : public virtual Shape { virtual double GetArea() const = 0; }; class ImprovedSquare : public Square, public ImprovedShape { ... } ``` And then I go and make an ImprovedSquare that inherits from ImprovedShape and Square. Well, as you can see, I have now created the dreaded [diamond inheritance problem](http://en.wikipedia.org/wiki/Diamond_problem). This would easily be fixed if the third party library used [virtual inheritance](http://en.wikipedia.org/wiki/Virtual_inheritance) for their Square, Circle, etc. However, getting them to do that isn't a reasonable option. So, what do you do when you need to add a little functionality to an interface defined in a library? Is there a good answer? Thanks!
We had a very similar problem in a project and we solved it by just NOT deriving ImprovedShape from Shape. If you need Shape functionality in ImprovedShape you can dynamic\_cast, knowing that your cast will always work. And the rest is just like in your example.
249,536
<p>FindBugs has found a potential bug in my code. But it is not a bug.</p> <p>Is it possible to mark this occurrence as 'not a bug' AND have it removed from the bug list?</p> <p>I have documented quite clearly why for each case it is not a bug.</p> <p>For example. A class implements the comparable interface. it has the compareTo method. I have however not overridden the equals method.</p> <p>FindBugs does not like this as the JavaDocs state that it is recommended that</p> <pre><code>(x.compareTo(y)==0) == (x.equals(y)) </code></pre> <p>Although in my case the above condition is and always will be true.</p>
[ { "answer_id": 249543, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 3, "selected": false, "text": "<p>Probably by adding a <a href=\"http://findbugs.sourceforge.net/manual/filter.html\" rel=\"noreferrer\">filter</a> as parameter of findbugs</p>\n\n<blockquote>\n <p>Match clauses can only match information that is actually contained in the bug instances</p>\n</blockquote>\n\n<pre><code>&lt;Match&gt;\n &lt;Class name=\"com.foobar.MyClass\" /&gt;\n &lt;Method name=\"myMethod\" /&gt;\n &lt;Bug pattern=\"EQ_COMPARETO_USE_OBJECT_EQUALS\" /&gt;\n&lt;/Match&gt;\n</code></pre>\n" }, { "answer_id": 249556, "author": "WMR", "author_id": 2844, "author_profile": "https://Stackoverflow.com/users/2844", "pm_score": 6, "selected": true, "text": "<p>Instead of using filters, you can also use the <a href=\"http://findbugs.sourceforge.net/api/edu/umd/cs/findbugs/annotations/SuppressWarnings.html\" rel=\"noreferrer\" title=\"SuppressWarnings\">SuppressWarnings</a> annotation. You must use the annotation out of the findbugs package, meaning you either need an import or use the fully qualified name of it. This is because other than the <a href=\"http://java.sun.com/javase/6/docs/api/java/lang/SuppressWarnings.html\" rel=\"noreferrer\">SuppressWarnings</a> from the JDK it has retention \"Class\", which is needed because findbugs operates on the compiled bytecode instead of source code.</p>\n\n<p>Example:</p>\n\n<pre><code>@edu.umd.cs.findbugs.annotations.SuppressWarnings(\n value=\"EQ_COMPARETO_USE_OBJECT_EQUALS\", \n justification=\"because I know better\")\n</code></pre>\n\n<p>There's one corner case where you probably should not be using the annotation: If your code is library code that ends up in a jar, that could be used by other projects <strong>and</strong> you're still on Java5. The reason for this is a <a href=\"http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6365854\" rel=\"noreferrer\">bug</a> in the JDK which crashes javac if the annotation is not in the classpath.</p>\n" }, { "answer_id": 249622, "author": "miceuz", "author_id": 24443, "author_profile": "https://Stackoverflow.com/users/24443", "pm_score": 0, "selected": false, "text": "<p>on another hand - if you are using such automated code review tool that highlights potential problems according to widely known recommendations, maybe you should adhere to it's recommendations? think of people who will be maintaining code after you. </p>\n\n<p>what if the code changes after time?</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249536", "https://Stackoverflow.com", "https://Stackoverflow.com/users/939/" ]
FindBugs has found a potential bug in my code. But it is not a bug. Is it possible to mark this occurrence as 'not a bug' AND have it removed from the bug list? I have documented quite clearly why for each case it is not a bug. For example. A class implements the comparable interface. it has the compareTo method. I have however not overridden the equals method. FindBugs does not like this as the JavaDocs state that it is recommended that ``` (x.compareTo(y)==0) == (x.equals(y)) ``` Although in my case the above condition is and always will be true.
Instead of using filters, you can also use the [SuppressWarnings](http://findbugs.sourceforge.net/api/edu/umd/cs/findbugs/annotations/SuppressWarnings.html "SuppressWarnings") annotation. You must use the annotation out of the findbugs package, meaning you either need an import or use the fully qualified name of it. This is because other than the [SuppressWarnings](http://java.sun.com/javase/6/docs/api/java/lang/SuppressWarnings.html) from the JDK it has retention "Class", which is needed because findbugs operates on the compiled bytecode instead of source code. Example: ``` @edu.umd.cs.findbugs.annotations.SuppressWarnings( value="EQ_COMPARETO_USE_OBJECT_EQUALS", justification="because I know better") ``` There's one corner case where you probably should not be using the annotation: If your code is library code that ends up in a jar, that could be used by other projects **and** you're still on Java5. The reason for this is a [bug](http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6365854) in the JDK which crashes javac if the annotation is not in the classpath.
249,540
<p>How do I specify the username and password in order for my program to open a file for reading? The program that needs to access the file is running from an account that does not have read access to the folder the file is in. Program is written in C# and .NET 2, running under XP and file is on a Windows Server 2003 machine.</p>
[ { "answer_id": 249559, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 0, "selected": false, "text": "<p>You can impersonate a user who has the necessary rights. There is an <a href=\"http://msdn.microsoft.com/en-us/library/b80a7e92.aspx\" rel=\"nofollow noreferrer\">article on MSDN</a> that describes how to do this.</p>\n" }, { "answer_id": 249594, "author": "James Newton-King", "author_id": 11829, "author_profile": "https://Stackoverflow.com/users/11829", "pm_score": 4, "selected": false, "text": "<p>You want to impersonate a user who does have the rights to access the file.</p>\n\n<p>I recommend using a class like this - <a href=\"http://www.codeproject.com/KB/cs/zetaimpersonator.aspx\" rel=\"noreferrer\">http://www.codeproject.com/KB/cs/zetaimpersonator.aspx</a>. It hides all the nasty implementation of doing impersonation.</p>\n\n<pre><code>using (new Impersonator(\"myUsername\", \"myDomainname\", \"myPassword\"))\n{\n string fileText = File.ReadAllText(\"c:\\test.txt\");\n Console.WriteLine(fileText);\n}\n</code></pre>\n" }, { "answer_id": 35492964, "author": "ΩmegaMan", "author_id": 285795, "author_profile": "https://Stackoverflow.com/users/285795", "pm_score": 3, "selected": false, "text": "<p>I have used the Nuget package <a href=\"https://www.nuget.org/packages/SimpleImpersonation\" rel=\"nofollow\">NuGet Gallery | Simple Impersonation Library 1.1.0</a> but there are others; search on Impersonation for the others.</p>\n\n<p>Example usage using the interactive login to work with file structures:</p>\n\n<pre><code>using (Impersonation.LogonUser(\"{domain}\",\n \"{UserName}\", \n \"{Password}\", \n LogonType.Interactive))\n{\n var directory = @\"\\\\MyCorpServer.net\\alpha\\cars\";\n\n Assert.IsTrue(Directory.Exists(directory));\n}\n</code></pre>\n\n<hr>\n\n<p><em>James' answer below was before Nuget and before he would later have the most downloaded package on Nuget. Ironic eh?</em></p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249540", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
How do I specify the username and password in order for my program to open a file for reading? The program that needs to access the file is running from an account that does not have read access to the folder the file is in. Program is written in C# and .NET 2, running under XP and file is on a Windows Server 2003 machine.
You want to impersonate a user who does have the rights to access the file. I recommend using a class like this - <http://www.codeproject.com/KB/cs/zetaimpersonator.aspx>. It hides all the nasty implementation of doing impersonation. ``` using (new Impersonator("myUsername", "myDomainname", "myPassword")) { string fileText = File.ReadAllText("c:\test.txt"); Console.WriteLine(fileText); } ```
249,557
<blockquote> <p>If f is a numerical function and n is a positive integer, then we can form the nth repeated application of f, which is defined to be the function whose value at x is f(f(...(f(x))...)). For example, if f is the function x + 1, then the nth repeated application of f is the function x + n. If f is the operation of squaring a number, then the nth repeated application of f is the function that raises its argument to the 2^nth power. Write a procedure that takes as inputs a procedure that computes f and a positive integer n and returns the procedure that computes the nth repeated application of f. Your procedure should be able to be used as follows:</p> <pre><code>((repeated square 2) 5) 625 </code></pre> <p>You can use this to simplify the answer:</p> <pre><code> (define (compose f g) (lambda (x) (f (g x)))) </code></pre> </blockquote>
[ { "answer_id": 249564, "author": "Matthias Benkard", "author_id": 15517, "author_profile": "https://Stackoverflow.com/users/15517", "pm_score": 1, "selected": false, "text": "<p>Did you just delete and reask this question? I'm copying my former answer here (thankfully, my browser had cached it):</p>\n\n<p>Well, you probably want something like this, right?</p>\n\n<pre><code>((repeated square 3) 5)\n-&gt; (square ((repeated square 2) 5))\n-&gt; (square (square ((repeated square 1) 5)))\n-&gt; (square (square (square ((repeated square 0) 5))))\n-&gt; (square (square (square (identity 5))))\n</code></pre>\n\n<p>(I don't know whether identity is predefined in Scheme. If not, it's easy to write.)</p>\n\n<p>Now, this is not directly reproducible because you can't magically enclose code outside of the call to repeated with arbitrary stuff. However, what do these reduction steps look like when rewritten using compose? Can you make out a pattern in the resulting list of steps and reproduce it?</p>\n" }, { "answer_id": 824363, "author": "Maxim", "author_id": 11587, "author_profile": "https://Stackoverflow.com/users/11587", "pm_score": 2, "selected": false, "text": "<pre><code>(define (repeated f n)\n (if (= n 1)\n f\n (compose f (repeated f (- n 1)))))\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30622/" ]
> > If f is a numerical function and n is a positive integer, then we can form the nth repeated application of f, which is defined to be the function whose value at x is f(f(...(f(x))...)). For example, if f is the function x + 1, then the nth repeated application of f is the function x + n. If f is the operation of squaring a number, then the nth repeated application of f is the function that raises its argument to the 2^nth power. Write a procedure that takes as inputs a procedure that computes f and a positive integer n and returns the procedure that computes the nth repeated application of f. Your procedure should be able to be used as follows: > > > > ``` > ((repeated square 2) 5) > 625 > > ``` > > You can use this to simplify the answer: > > > > ``` > (define (compose f g) (lambda (x) (f (g x)))) > > ``` > >
``` (define (repeated f n) (if (= n 1) f (compose f (repeated f (- n 1))))) ```
249,570
<p>On a particular Debian server, iostat (and similar) report an unexpectedly high volume (in bytes) of disk writes going on. I am having trouble working out which process is doing these writes.</p> <p>Two interesting points:</p> <ol> <li><p>Tried turning off system services one at a time to no avail. Disk activity remains fairly constant and unexpectedly high.</p></li> <li><p>Despite the writing, do not seem to be consuming more overall space on the disk.</p></li> </ol> <p>Both of those make me think that the writing may be something that the kernel is doing, but I'm not swapping, so it's not clear to me what Linux might try to write.</p> <p>Could try out atop:</p> <p><a href="http://www.atcomputing.nl/Tools/atop/" rel="noreferrer">http://www.atcomputing.nl/Tools/atop/</a></p> <p>but would like to avoid patching my kernel.</p> <p>Any ideas on how to track this down?</p>
[ { "answer_id": 249574, "author": "Geo", "author_id": 31610, "author_profile": "https://Stackoverflow.com/users/31610", "pm_score": 0, "selected": false, "text": "<p>You could try to use <a href=\"http://sourceware.org/systemtap/\" rel=\"nofollow noreferrer\">SystemTap</a> , it has a lot of examples , and if I'm not mistaken , it shows how to do this sort of thing .</p>\n" }, { "answer_id": 249596, "author": "Mnementh", "author_id": 21005, "author_profile": "https://Stackoverflow.com/users/21005", "pm_score": 1, "selected": false, "text": "<p>You can use the UNIX-command <strong>lsof</strong> (list open files). That prints out the process, process-id, user for any open file.</p>\n" }, { "answer_id": 250029, "author": "Paweł Hajdan", "author_id": 9403, "author_profile": "https://Stackoverflow.com/users/9403", "pm_score": 2, "selected": false, "text": "<p>You may want to investigate <strong>iotop for Linux</strong>. There are some Solaris versions floating around, but there is a Debian package for example.</p>\n" }, { "answer_id": 395362, "author": "Igor Pozgaj", "author_id": 19777, "author_profile": "https://Stackoverflow.com/users/19777", "pm_score": 2, "selected": false, "text": "<p>If you are using a kernel newer than 2.6.20 that is very easy, as that is the first version of Linux kernel that includes I/O accounting. If you are compiling your own kernel, be sure to include:</p>\n\n<pre><code>CONFIG_TASKSTATS=y\nCONFIG_TASK_IO_ACCOUNTING=y\n</code></pre>\n\n<p>Kernels from Debian packages already include these flags, so there is no need for recompiling your kernel. Standard utility for accessing I/O accounting data in real time is iotop(1). It gives you a complete list of processes managed by I/O scheduler, and displays per process statistics for read, write and total I/O bandwidth used.</p>\n" }, { "answer_id": 423562, "author": "Mikeage", "author_id": 41308, "author_profile": "https://Stackoverflow.com/users/41308", "pm_score": 4, "selected": false, "text": "<p>iotop is good (great, actually). </p>\n\n<p>If you have a kernel from before 2.6.20, you can't use most of these tools.</p>\n\n<p>Instead, you can try the following (which should work for almost any 2.6 kernel IIRC):</p>\n\n<pre> \nsudo -s\ndmesg -c\n/etc/init.d/klogd stop\necho 1 > /proc/sys/vm/block_dump\nrm /tmp/disklog\nwatch \"dmesg -c >> /tmp/disklog\"\n CTRL-C when you're done collecting data\necho 0 > /proc/sys/vm/block_dump\n/etc/init.d/klogd start\nexit (quit root shell)\n\ncat /tmp/disklog | awk -F\"[() \\t]\" '/(READ|WRITE|dirtied)/ {activity[$1]++} END {for (x in activity) print x, activity[x]}'| sort -nr -k2\n</pre>\n\n<p>The dmesg -c lines clear your kernel log . The logger is then shut off, manually (using watch) dumped to a disk (the memory buffer is small, which is why we need to do this). Let it run for about five minutes or so, and then CTRL-c the watch process. After shutting off the logging and restarting klogd, analyze the results using the little bit of awk at the end.</p>\n" }, { "answer_id": 1023571, "author": "Tomek Paczkowski", "author_id": 585768, "author_profile": "https://Stackoverflow.com/users/585768", "pm_score": 1, "selected": false, "text": "<p>You could also use <strong>htop</strong>, enabling IO_RATR column. Htop is an exelent top replacement.</p>\n" }, { "answer_id": 2277623, "author": "blueyed", "author_id": 15690, "author_profile": "https://Stackoverflow.com/users/15690", "pm_score": 0, "selected": false, "text": "<p>I've recently heard about Mortadelo, a Filemon clone, but have not checked it out myself yet:</p>\n\n<p><a href=\"http://gitorious.org/mortadelo\" rel=\"nofollow noreferrer\">http://gitorious.org/mortadelo</a></p>\n" }, { "answer_id": 25102755, "author": "Anon", "author_id": 3903518, "author_profile": "https://Stackoverflow.com/users/3903518", "pm_score": 1, "selected": false, "text": "<p><a href=\"https://github.com/brendangregg/perf-tools/blob/master/iosnoop\" rel=\"nofollow\">Brendan Gregg's iosnoop</a> script can (heuristically) tell you about currently using the disk on recent kernels (<a href=\"http://www.brendangregg.com/blog/2014-07-16/iosnoop-for-linux.html\" rel=\"nofollow\">example iosnoop output</a>).</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249570", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
On a particular Debian server, iostat (and similar) report an unexpectedly high volume (in bytes) of disk writes going on. I am having trouble working out which process is doing these writes. Two interesting points: 1. Tried turning off system services one at a time to no avail. Disk activity remains fairly constant and unexpectedly high. 2. Despite the writing, do not seem to be consuming more overall space on the disk. Both of those make me think that the writing may be something that the kernel is doing, but I'm not swapping, so it's not clear to me what Linux might try to write. Could try out atop: <http://www.atcomputing.nl/Tools/atop/> but would like to avoid patching my kernel. Any ideas on how to track this down?
iotop is good (great, actually). If you have a kernel from before 2.6.20, you can't use most of these tools. Instead, you can try the following (which should work for almost any 2.6 kernel IIRC): ``` sudo -s dmesg -c /etc/init.d/klogd stop echo 1 > /proc/sys/vm/block_dump rm /tmp/disklog watch "dmesg -c >> /tmp/disklog" CTRL-C when you're done collecting data echo 0 > /proc/sys/vm/block_dump /etc/init.d/klogd start exit (quit root shell) cat /tmp/disklog | awk -F"[() \t]" '/(READ|WRITE|dirtied)/ {activity[$1]++} END {for (x in activity) print x, activity[x]}'| sort -nr -k2 ``` The dmesg -c lines clear your kernel log . The logger is then shut off, manually (using watch) dumped to a disk (the memory buffer is small, which is why we need to do this). Let it run for about five minutes or so, and then CTRL-c the watch process. After shutting off the logging and restarting klogd, analyze the results using the little bit of awk at the end.
249,573
<p>There is small system, where a database table as queue on MSSQL 2005. Several applications are writing to this table, and one application is reading and processing in a FIFO manner.</p> <p>I have to make it a little bit more advanced to be able to create a distributed system, where several processing application can run. The result should be that 2-10 processing application should be able to run and they should not interfere each other during work.</p> <p>My idea is to extend the queue table with a row showing that a process is already working on it. The processing application will first update the table with it's idetifyer, and then asks for the updated records.</p> <p>So something like this:</p> <pre><code>start transaction update top(10) queue set processing = 'myid' where processing is null select * from processing where processing = 'myid' end transaction </code></pre> <p>After processing, it sets the processing column of the table to something else, like 'done', or whatever.</p> <p>I have three questions about this approach.</p> <p>First: can this work in this form?</p> <p>Second: if it is working, is it effective? Do you have any other ideas to create such a distribution?</p> <p>Third: In MSSQL the locking is row based, but after an amount of rows are locked, the lock is extended to the whole table. So the second application cannot access it, until the first application does not release the transaction. How big can be the selection (top x) in order to not lock the whole table, only create row locks?</p>
[ { "answer_id": 249611, "author": "philsquared", "author_id": 32136, "author_profile": "https://Stackoverflow.com/users/32136", "pm_score": 1, "selected": false, "text": "<p>This approach looks reasonable to me, and is similar to one I have used in the past - successfully.</p>\n\n<p>Also, the row/ table will only be locked while the update and select operations take place, so I doubt the row vs table question is really a major consideration.</p>\n\n<p>Unless the processing overhead of your app is so low as to be negligible, I'd keep the \"top\" value low - perhaps just 1. Of course that entirely depends on the details of your app.</p>\n\n<p>Having said all that, I'm not a DBA, and so will also be interested in any more expert answers</p>\n" }, { "answer_id": 249623, "author": "Greg Beech", "author_id": 13552, "author_profile": "https://Stackoverflow.com/users/13552", "pm_score": 4, "selected": true, "text": "<p>This will work, but you'll probably find you'll run into blocking or deadlocks where multiple processes try and read/update the same data. I wrote a procedure to do exactly this for one of our systems which uses some interesting locking semantics to ensure this type of thing runs with no blocking or deadlocks, <a href=\"http://gregbeech.com/blog/retrieving-a-row-exactly-once-with-multiple-polling-processes-in-sql-server\" rel=\"nofollow noreferrer\">described here</a>.</p>\n" }, { "answer_id": 249688, "author": "mjallday", "author_id": 6084, "author_profile": "https://Stackoverflow.com/users/6084", "pm_score": 1, "selected": false, "text": "<p>In regards to your question about locking. You can use a locking hint to force it to lock only rows</p>\n\n<pre><code>update mytable with (rowlock) set x=y where a=b\n</code></pre>\n" }, { "answer_id": 584700, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Biggest problem with this approach is that you increase the number of 'updates' to the table. Try this with just one process consuming (update + delete) and others inserting data in the table and you will find that at around a million records, it starts to crumble.</p>\n\n<p>I would rather have one consumer for the DB and use message queues to deliver processing data to other consumers.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/968/" ]
There is small system, where a database table as queue on MSSQL 2005. Several applications are writing to this table, and one application is reading and processing in a FIFO manner. I have to make it a little bit more advanced to be able to create a distributed system, where several processing application can run. The result should be that 2-10 processing application should be able to run and they should not interfere each other during work. My idea is to extend the queue table with a row showing that a process is already working on it. The processing application will first update the table with it's idetifyer, and then asks for the updated records. So something like this: ``` start transaction update top(10) queue set processing = 'myid' where processing is null select * from processing where processing = 'myid' end transaction ``` After processing, it sets the processing column of the table to something else, like 'done', or whatever. I have three questions about this approach. First: can this work in this form? Second: if it is working, is it effective? Do you have any other ideas to create such a distribution? Third: In MSSQL the locking is row based, but after an amount of rows are locked, the lock is extended to the whole table. So the second application cannot access it, until the first application does not release the transaction. How big can be the selection (top x) in order to not lock the whole table, only create row locks?
This will work, but you'll probably find you'll run into blocking or deadlocks where multiple processes try and read/update the same data. I wrote a procedure to do exactly this for one of our systems which uses some interesting locking semantics to ensure this type of thing runs with no blocking or deadlocks, [described here](http://gregbeech.com/blog/retrieving-a-row-exactly-once-with-multiple-polling-processes-in-sql-server).
249,578
<p>I'm writing a bash script that needs to delete old files.</p> <p>It's currently implemented using :</p> <pre><code>find $LOCATION -name $REQUIRED_FILES -type f -mtime +1 -delete </code></pre> <p>This will delete of the files older than 1 day.</p> <p>However, what if I need a finer resolution that 1 day, say like 6 hours old? Is there a nice clean way to do it, like there is using find and -mtime?</p>
[ { "answer_id": 249584, "author": "GavinCattell", "author_id": 21644, "author_profile": "https://Stackoverflow.com/users/21644", "pm_score": 2, "selected": false, "text": "<p>-mmin is for minutes.</p>\n\n<p>Try looking at the man page.</p>\n\n<pre><code>man find\n</code></pre>\n\n<p>for more types.</p>\n" }, { "answer_id": 249591, "author": "Paul Dixon", "author_id": 6521, "author_profile": "https://Stackoverflow.com/users/6521", "pm_score": 10, "selected": true, "text": "<p>Does your <a href=\"http://man7.org/linux/man-pages/man1/find.1.html\" rel=\"noreferrer\"><code>find</code></a> have the <code>-mmin</code> option? That can let you test the number of mins since last modification:</p>\n\n<pre><code>find $LOCATION -name $REQUIRED_FILES -type f -mmin +360 -delete\n</code></pre>\n\n<p>Or maybe look at using <a href=\"http://linux.about.com/library/cmd/blcmdl8_tmpwatch.htm\" rel=\"noreferrer\"><code>tmpwatch</code></a> to do the same job. phjr also recommended <a href=\"http://linux.about.com/cs/linux101/g/tmpreaper.htm\" rel=\"noreferrer\"><code>tmpreaper</code></a> in the comments.</p>\n" }, { "answer_id": 249608, "author": "xtofl", "author_id": 6610, "author_profile": "https://Stackoverflow.com/users/6610", "pm_score": 4, "selected": false, "text": "<p>You could to this trick: create a file 1 hour ago, and use the <code>-newer file</code> argument.</p>\n\n<p>(Or use <code>touch -t</code> to create such a file).</p>\n" }, { "answer_id": 2957262, "author": "Rajeev Rumale", "author_id": 356377, "author_profile": "https://Stackoverflow.com/users/356377", "pm_score": 1, "selected": false, "text": "<p>For SunOS 5.10 </p>\n\n<pre><code> Example 6 Selecting a File Using 24-hour Mode\n\n\n The descriptions of -atime, -ctime, and -mtime use the ter-\n minology n ``24-hour periods''. For example, a file accessed\n at 23:59 is selected by:\n\n\n example% find . -atime -1 -print\n\n\n\n\n at 00:01 the next day (less than 24 hours later, not more\n than one day ago). The midnight boundary between days has no\n effect on the 24-hour calculation.\n</code></pre>\n" }, { "answer_id": 40351544, "author": "Eragonz91", "author_id": 2690656, "author_profile": "https://Stackoverflow.com/users/2690656", "pm_score": 0, "selected": false, "text": "<p><code>find $PATH -name $log_prefix\"*\"$log_ext -mmin +$num_mins -exec rm -f {} \\;</code></p>\n" }, { "answer_id": 44522525, "author": "satyr0909", "author_id": 8154766, "author_profile": "https://Stackoverflow.com/users/8154766", "pm_score": 0, "selected": false, "text": "<p>Here is what one can do for going on the way @iconoclast was wondering about in their <a href=\"https://stackoverflow.com/questions/249578/how-to-delete-files-older-than-x-hours#comment6865608_249608\">comment</a> on another answer.</p>\n\n<p>use crontab for user or an <code>/etc/crontab</code> to create file <code>/tmp/hour</code>:</p>\n\n<pre><code># m h dom mon dow user command\n0 * * * * root /usr/bin/touch /tmp/hour &gt; /dev/null 2&gt;&amp;1\n</code></pre>\n\n<p>and then use this to run your command:</p>\n\n<pre><code>find /tmp/ -daystart -maxdepth 1 -not -newer /tmp/hour -type f -name \"for_one_hour_files*\" -exec do_something {} \\;\n</code></pre>\n" }, { "answer_id": 44837673, "author": "Malcolm Boekhoff", "author_id": 1388639, "author_profile": "https://Stackoverflow.com/users/1388639", "pm_score": 1, "selected": false, "text": "<p>If you do not have \"-mmin\" in your version of \"find\", then \"-mtime -0.041667\" gets pretty close to \"within the last hour\", so in your case, use:</p>\n\n<pre><code>-mtime +(X * 0.041667)\n</code></pre>\n\n<p>so, if X means 6 hours, then:</p>\n\n<pre><code>find . -mtime +0.25 -ls\n</code></pre>\n\n<p>works because 24 hours * 0.25 = 6 hours</p>\n" }, { "answer_id": 48887660, "author": "Axel Ronsin", "author_id": 4213669, "author_profile": "https://Stackoverflow.com/users/4213669", "pm_score": 5, "selected": false, "text": "<p>Here is the approach that worked for me (and I don't see it being used above)</p>\n<pre><code>$ find /path/to/the/folder -name '*.*' -mmin +59 -delete &gt; /dev/null\n</code></pre>\n<p>deleting all the files older than 59 minutes while leaving the folders intact.</p>\n" }, { "answer_id": 61247632, "author": "kbulgrien", "author_id": 856172, "author_profile": "https://Stackoverflow.com/users/856172", "pm_score": 1, "selected": false, "text": "<p>If one's <code>find</code> does not have <code>-mmin</code> and if one also is stuck with a <code>find</code> that accepts only integer values for <code>-mtime</code>, then all is not necessarily lost if one considers that &quot;older than&quot; is similar to &quot;not newer than&quot;.</p>\n<p>If we were able to create a file that that has an <em>mtime</em> of our cut-off time, we can ask <code>find</code> to locate the files that are &quot;not newer than&quot; our reference file.</p>\n<p>To create a file that has the correct time stamp is a bit involved because a system that doesn't have an adequate <code>find</code> probably also has a less-than-capable <code>date</code> command that could do things like: <code>date +%Y%m%d%H%M%S -d &quot;6 hours ago&quot;</code>.</p>\n<p>Fortunately, other old tools can manage this, albeit in a more unwieldy way.</p>\n<p>To begin finding a way to delete files that are over six hours old, we first have to find the time that is six hours ago. Consider that six hours is 21600 seconds:</p>\n<pre><code>$ date &amp;&amp; perl -e '@d=localtime time()-21600; \\\n printf &quot;%4d%02d%02d%02d%02d.%02d\\n&quot;, $d[5]+1900,$d[4]+1,$d[3],$d[2],$d[1],$d[0]'\n&gt; Thu Apr 16 04:50:57 CDT 2020\n202004152250.57\n</code></pre>\n<p>Since the <code>perl</code> statement produces the date/time information we need, use it to create a reference file that is exactly six hours old:</p>\n<pre><code>$ date &amp;&amp; touch -t `perl -e '@d=localtime time()-21600; \\\n printf &quot;%4d%02d%02d%02d%02d.%02d\\n&quot;, \\\n $d[5]+1900,$d[4]+1,$d[3],$d[2],$d[1],$d[0]'` ref_file &amp;&amp; ls -l ref_file\nThu Apr 16 04:53:54 CDT 2020\n-rw-rw-rw- 1 root sys 0 Apr 15 22:53 ref_file\n</code></pre>\n<p>Now that we have a reference file exactly six hours old, the &quot;old UNIX&quot; solution for &quot;delete all files older than six hours&quot; becomes something along the lines of:</p>\n<pre><code>$ find . -type f ! -newer ref_file -a ! -name ref_file -exec rm -f &quot;{}&quot; \\;\n</code></pre>\n<p>It might also be a good idea to clean up our reference file...</p>\n<pre><code>$ rm -f ref_file\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13523/" ]
I'm writing a bash script that needs to delete old files. It's currently implemented using : ``` find $LOCATION -name $REQUIRED_FILES -type f -mtime +1 -delete ``` This will delete of the files older than 1 day. However, what if I need a finer resolution that 1 day, say like 6 hours old? Is there a nice clean way to do it, like there is using find and -mtime?
Does your [`find`](http://man7.org/linux/man-pages/man1/find.1.html) have the `-mmin` option? That can let you test the number of mins since last modification: ``` find $LOCATION -name $REQUIRED_FILES -type f -mmin +360 -delete ``` Or maybe look at using [`tmpwatch`](http://linux.about.com/library/cmd/blcmdl8_tmpwatch.htm) to do the same job. phjr also recommended [`tmpreaper`](http://linux.about.com/cs/linux101/g/tmpreaper.htm) in the comments.
249,580
<p>What is the recommended practice? Should I add the my sub-folder under the fitnesse folder to version control? </p> <p><em>Context: working on a single developer rails pet project. I've my rails project under version-control (Subversion) however my fitnesse wiki pages lie under the fitnesse program folder.</em></p> <p>Fitnesse seems to have its own version-control... (I see numbered zips along with each of my wiki pages) Is it reliable? Where does it store the revisions?</p>
[ { "answer_id": 249621, "author": "Aur Saraf", "author_id": 19993, "author_profile": "https://Stackoverflow.com/users/19993", "pm_score": 2, "selected": false, "text": "<p>FitNesse stores old revisions of every page in a zip file in the same directory as the page's files. The zip filename marks the timestamp of the revision. It works similar to wikipedia - history, but not full-fledged version control.</p>\n\n<p>In our company we wanted a setup where whenever we checkout a (possibly old) revision of the source, we also check out FitNesse tests that pass for that specific version.</p>\n\n<p>Therefore, we installed FitNesse (the fitnesse directory, including the FitNesse executable and the FitNesseRoot directory) inside our source tree in version control, setting a rule to not import *.zip within the FitNesseRoot directory (as we have version control to keep history for us and don't need them).</p>\n\n<p>This works excellent with sane SCMs (I used svn w/ svn-tortoise).</p>\n\n<p>When we moved to Microsoft Foundation Server source control we had many issues with the checkout-edit-checkin workflow. Then again, this workflow is simply a bad idea in general, and should only be used by insane control-freaks.</p>\n\n<p>(edit: answered commenter's question)</p>\n" }, { "answer_id": 446230, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": 6, "selected": true, "text": "<p>Use the <code>-d</code> switch (<em>which is surprisingly low profile on a google search</em>)</p>\n\n<pre><code>Fitnesse20081201&gt;run -p 8080 -d c:/projects/MyProjectNeedsAcceptanceTests\n</code></pre>\n\n<p>This will create a subfolder in the specified folder called FitnesseRoot if it doesn't already exist, with all the stuff it needs to run.</p>\n\n<p>Fitnesse should be up. Switch to your browser. Go ahead and create your pages.</p>\n\n<ul>\n<li>You will have a subfolder for every Fitnesse page you create. </li>\n<li>Each folder would have a <code>content.txt</code> (which is the wiki content) and a <code>properties.xml</code> (which are the Fitnesse Properties for that page). </li>\n<li>All subpages would be subfolders under the folder for the parent page. </li>\n</ul>\n\n<p>Directories and Files...You're all setup for your first check-in to version control.\nAlso set up your version control to ignore certain types of files</p>\n\n<ul>\n<li>FitnesseRoot/files</li>\n<li>FitnesseRoot/ErrorLog</li>\n<li>*.zip</li>\n</ul>\n\n<p><em>(The .zip files are how Fitnesse keeps track of edits to wiki pages.. a short term local version control. VCS like svn, git, cvs, etc.. should take care of this for us. So we don't need to check in the zip files)</em></p>\n\n<p>Hope that made sense.. If not I suggest you take 15 mins off to listen to the following screencast from UncleBob himself<br>\n<strong>Source:</strong>\n<a href=\"http://vimeo.com/2765514\" rel=\"noreferrer\">Robert Martin - Version Control and Development Environment for Fitnesse</a></p>\n" }, { "answer_id": 584104, "author": "Joseph Anderson", "author_id": 18102, "author_profile": "https://Stackoverflow.com/users/18102", "pm_score": 5, "selected": false, "text": "<p>If you're using version control with Fitnesse, you won't need the zip archive for every revision. Use the -e 0 option to prevent the zip archives from being created:</p>\n\n<p>java -jar fitnesse.jar -p 8001 <strong>-e 0</strong></p>\n" }, { "answer_id": 1163100, "author": "Lee", "author_id": 6035, "author_profile": "https://Stackoverflow.com/users/6035", "pm_score": 2, "selected": false, "text": "<p>Since the 20090214 release of Fitnesse, CM integration is included, see user guide for details.\n<a href=\"http://fitnesse.org/FitNesse.UserGuide.SourceCodeControl\" rel=\"nofollow noreferrer\">http://fitnesse.org/FitNesse.UserGuide.SourceCodeControl</a></p>\n\n<p>The git hub plugin is included with the fitnesse distribution.</p>\n\n<p>I see a plug in for perforce at <a href=\"http://code.google.com/p/perforcecmsystem/\" rel=\"nofollow noreferrer\">http://code.google.com/p/perforcecmsystem/</a>, but I haven't got this setup for my team yet.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249580", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1695/" ]
What is the recommended practice? Should I add the my sub-folder under the fitnesse folder to version control? *Context: working on a single developer rails pet project. I've my rails project under version-control (Subversion) however my fitnesse wiki pages lie under the fitnesse program folder.* Fitnesse seems to have its own version-control... (I see numbered zips along with each of my wiki pages) Is it reliable? Where does it store the revisions?
Use the `-d` switch (*which is surprisingly low profile on a google search*) ``` Fitnesse20081201>run -p 8080 -d c:/projects/MyProjectNeedsAcceptanceTests ``` This will create a subfolder in the specified folder called FitnesseRoot if it doesn't already exist, with all the stuff it needs to run. Fitnesse should be up. Switch to your browser. Go ahead and create your pages. * You will have a subfolder for every Fitnesse page you create. * Each folder would have a `content.txt` (which is the wiki content) and a `properties.xml` (which are the Fitnesse Properties for that page). * All subpages would be subfolders under the folder for the parent page. Directories and Files...You're all setup for your first check-in to version control. Also set up your version control to ignore certain types of files * FitnesseRoot/files * FitnesseRoot/ErrorLog * \*.zip *(The .zip files are how Fitnesse keeps track of edits to wiki pages.. a short term local version control. VCS like svn, git, cvs, etc.. should take care of this for us. So we don't need to check in the zip files)* Hope that made sense.. If not I suggest you take 15 mins off to listen to the following screencast from UncleBob himself **Source:** [Robert Martin - Version Control and Development Environment for Fitnesse](http://vimeo.com/2765514)
249,581
<p>I have checked with the <a href="http://en.wikipedia.org/wiki/Facade_pattern" rel="noreferrer">wikipedia article</a>, and it seems like it is missing the c++ version of a code example. I am not able to fully appreciate the Facade pattern without this, can you please help explain it to me using C++?</p>
[ { "answer_id": 249656, "author": "Dave Hillier", "author_id": 1575281, "author_profile": "https://Stackoverflow.com/users/1575281", "pm_score": 3, "selected": false, "text": "<p>I've done a search and replace on the C# example. This might not help you, because if you understand C++ then you should be able to understand the C# as it uses the same constructs and keywords (classes, functions, namespaces, public, etc) </p>\n\n<pre><code>// \"Subsystem ClassA\" \n#include &lt;iostream&gt;\nclass SubSystemOne\n{\npublic:\n void MethodOne()\n {\n std::cout &lt;&lt; \" SubSystemOne Method\" &lt;&lt; std::endl;\n }\n}\n\n// Subsystem ClassB\" \n\nclass SubSystemTwo\n{\npublic:\n void MethodTwo()\n {\n std::cout &lt;&lt; \" SubSystemTwo Method\" &lt;&lt; std::endl;\n }\n}\n\n// Subsystem ClassC\" \n\nclass SubSystemThree\n{\npublic:\n void MethodThree()\n {\n std::cout &lt;&lt; \" SubSystemThree Method\" &lt;&lt; std::endl;\n }\n}\n\n// Subsystem ClassD\" \n\nclass SubSystemFour\n{\npublic:\n void MethodFour()\n {\n std::cout &lt;&lt; \" SubSystemFour Method\" &lt;&lt; std::endl;\n }\n}\n\n// \"Facade\" \n\nclass Facade\n{\n SubSystemOne one;\n SubSystemTwo two;\n SubSystemThree three;\n SubSystemFour four;\n\npublic:\n Facade()\n {\n }\n\n void MethodA()\n {\n std::cout &lt;&lt; \"\\nMethodA() ---- \" &lt;&lt; std::endl;\n one.MethodOne();\n two.MethodTwo();\n four.MethodFour();\n }\n void MethodB()\n {\n std::cout &lt;&lt; \"\\nMethodB() ---- \" &lt;&lt; std::endl;\n two.MethodTwo();\n three.MethodThree();\n }\n}\n\nint Main()\n{\n Facade facade = new Facade();\n\n facade.MethodA();\n facade.MethodB();\n\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 249889, "author": "Johann Gerell", "author_id": 6345, "author_profile": "https://Stackoverflow.com/users/6345", "pm_score": 2, "selected": false, "text": "<p>In one sense, a Facade is just an API for clients that wants to interact with something hidden.</p>\n\n<p>The Facade is useful when exposing a simple C API for something that's implemented in C++ or simply more complex than the API. Or to get a fixed barrier between a client and a library when the library needs to go through numerous iterative updates and you want to affect the client as little as possible. For instance, if a C based library needs to be updated internally to C++ or something else, or just swapped for something completely different, then the Facade is a good middle-layer for the client.</p>\n" }, { "answer_id": 249925, "author": "jamesh", "author_id": 4737, "author_profile": "https://Stackoverflow.com/users/4737", "pm_score": 2, "selected": false, "text": "<p>There are <a href=\"http://www.vincehuston.org/dp/FacadeDemosCpp\" rel=\"nofollow noreferrer\">C++ examples</a> for <a href=\"http://www.vincehuston.org/dp/facade.html\" rel=\"nofollow noreferrer\">Facade</a> at this excellent site on design patterns.</p>\n" }, { "answer_id": 249981, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": 6, "selected": true, "text": "<p><strong>Facade pattern: provides a unified - simplified interface to a complex subsystem or set of interfaces. It provides a higher level interface simultaneously decoupling the client from the complex subsystem.</strong></p>\n\n<p>An example to help you understand .. a cab driver. You tell the cab driver 'Take me to PointX' (unified simplified high-level interface) who then begins on a sequence of actions (turns the key, changes gears, presses the accelerator, etc...) to perform the task. He abstracts away the complexity of underlying subsystems (gearbox, engine, etc.) so that you don't have to worry about them. \nThe driver also decouples you from the actual vehicle used... you do not directly interface with the car. You could potentially give him a Merc but your interface to the Driver would still be TakeMeTo( X ).. you're not tied down to any specific model/make of the car.</p>\n\n<p>In a real world example, you'll find facades where you interface with third party components or libraries. You don't want your code to depend on a specific vendor, so you introduce a facade interface to decouple. Also you'll simplify this interface, e.g. your facade interface would have a method called SendData( string ) but internally the implementation may call n methods on m sub-packages in a specific order to get the task done. This is what the diagram on the wikipedia page shows.</p>\n\n<p>e.g. Translating <a href=\"http://www.theperlreview.com/Articles/v0i4/facade.pdf\" rel=\"noreferrer\">an example</a> to C++ and keeping it tiny</p>\n\n<pre><code>sResource = LWCPPSimple::get(\"http://www.perl.org\")\n</code></pre>\n\n<p>Here the fictitious Library For WWW in C++ is a facade that unifies protocol, network and parsing aspects of the problem so that I can concentrate on my primary focus of fetching the resource. The get method hides/encapsulates/keeps-in-one-place the complexity (and in some cases ugliness) of HTTP, FTP and other varied protocols, request-response, connection management, etc. Also if tomorrow the creators of LWCPPSimple find a way to make get() to be twice as fast, I get the performance benefits for free. My client code doesn't have to change.</p>\n" }, { "answer_id": 249995, "author": "wasker", "author_id": 21952, "author_profile": "https://Stackoverflow.com/users/21952", "pm_score": 4, "selected": false, "text": "<pre><code>class Engine\n{\n\npublic:\n void Start() { }\n\n};\n\nclass Headlights\n{\n\npublic:\n void TurnOn() { }\n\n};\n\n// That's your facade.\nclass Car\n{\n\nprivate:\n Engine engine;\n Headlights headlights;\n\npublic:\n void TurnIgnitionKeyOn()\n {\n headlights.TurnOn();\n engine.Start();\n }\n\n};\n\nint Main(int argc, char *argv[])\n{\n // Consuming facade.\n Car car;\n car.TurnIgnitionKeyOn();\n\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 2457357, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<pre><code>class A {\n private B b; // Class A uses Class B, the \"interface\"\n public int f() { return b.g(); }\n};\n\nclass B {\n private C c; // class B uses class C, a \"subsystem\"\n private ... ...; // other subsystems can be added\n public int g() { c.h(); return c.i(); }\n};\n\nclass C { // a subsystem\n public void h() { ... }\n public int i() { return x; }\n};\n</code></pre>\n\n<p>Class A will not directly use any methods or directly affect the state of class C or any other subsystem that class B contains. Only one subsystem is shown here because it doesn't matter how many subsystems there are.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249581", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22076/" ]
I have checked with the [wikipedia article](http://en.wikipedia.org/wiki/Facade_pattern), and it seems like it is missing the c++ version of a code example. I am not able to fully appreciate the Facade pattern without this, can you please help explain it to me using C++?
**Facade pattern: provides a unified - simplified interface to a complex subsystem or set of interfaces. It provides a higher level interface simultaneously decoupling the client from the complex subsystem.** An example to help you understand .. a cab driver. You tell the cab driver 'Take me to PointX' (unified simplified high-level interface) who then begins on a sequence of actions (turns the key, changes gears, presses the accelerator, etc...) to perform the task. He abstracts away the complexity of underlying subsystems (gearbox, engine, etc.) so that you don't have to worry about them. The driver also decouples you from the actual vehicle used... you do not directly interface with the car. You could potentially give him a Merc but your interface to the Driver would still be TakeMeTo( X ).. you're not tied down to any specific model/make of the car. In a real world example, you'll find facades where you interface with third party components or libraries. You don't want your code to depend on a specific vendor, so you introduce a facade interface to decouple. Also you'll simplify this interface, e.g. your facade interface would have a method called SendData( string ) but internally the implementation may call n methods on m sub-packages in a specific order to get the task done. This is what the diagram on the wikipedia page shows. e.g. Translating [an example](http://www.theperlreview.com/Articles/v0i4/facade.pdf) to C++ and keeping it tiny ``` sResource = LWCPPSimple::get("http://www.perl.org") ``` Here the fictitious Library For WWW in C++ is a facade that unifies protocol, network and parsing aspects of the problem so that I can concentrate on my primary focus of fetching the resource. The get method hides/encapsulates/keeps-in-one-place the complexity (and in some cases ugliness) of HTTP, FTP and other varied protocols, request-response, connection management, etc. Also if tomorrow the creators of LWCPPSimple find a way to make get() to be twice as fast, I get the performance benefits for free. My client code doesn't have to change.
249,587
<p>I want to scale an image in C# with quality level as good as Photoshop does. Is there any C# image processing library available to do this thing?</p>
[ { "answer_id": 249601, "author": "Hallgrim", "author_id": 15454, "author_profile": "https://Stackoverflow.com/users/15454", "pm_score": 4, "selected": false, "text": "<p>When you draw the image using GDI+ it scales quite well in my opinion. You can use this to create a scaled image.</p>\n\n<p>If you want to scale your image with GDI+ you can do something like this:</p>\n\n<pre><code>Bitmap original = ...\nBitmap scaled = new Bitmap(new Size(original.Width * 4, original.Height * 4));\nusing (Graphics graphics = Graphics.FromImage(scaled)) {\n graphics.DrawImage(original, new Rectangle(0, 0, scaled.Width, scaled.Height));\n}\n</code></pre>\n" }, { "answer_id": 249605, "author": "kitsune", "author_id": 13466, "author_profile": "https://Stackoverflow.com/users/13466", "pm_score": 3, "selected": false, "text": "<p>Tested libraries like <a href=\"http://www.imagemagick.org/\" rel=\"nofollow noreferrer\">Imagemagick</a> and <a href=\"http://gd-sharp.sourceforge.net/\" rel=\"nofollow noreferrer\">GD</a> are available for .NET</p>\n\n<p>You could also read up on things like bicubic interpolation and write your own.</p>\n" }, { "answer_id": 249700, "author": "OregonGhost", "author_id": 20363, "author_profile": "https://Stackoverflow.com/users/20363", "pm_score": 2, "selected": false, "text": "<p>Try the different values for Graphics.InterpolationMode. There are several typical scaling algorithms available in GDI+. If one of these is sufficient for your need, you can go this route instead of relying on an external library.</p>\n" }, { "answer_id": 304668, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>There's an <a href=\"http://www.codeproject.com/KB/GDI-plus/imageresize.aspx\" rel=\"nofollow noreferrer\">article on Code Project</a> about using GDI+ for .NET to do photo resizing using, say, Bicubic interpolation.</p>\n\n<p>There was also another article about this topic on another blog (MS employee, I think), but I can't find the link anywhere. :( Perhaps someone else can find it?</p>\n" }, { "answer_id": 353155, "author": "Robin Rodricks", "author_id": 41021, "author_profile": "https://Stackoverflow.com/users/41021", "pm_score": 3, "selected": false, "text": "<p>CodeProject articles discussing and sharing source code for <strong>scaling images:</strong></p>\n\n<ul>\n<li><a href=\"http://www.codeproject.com/KB/graphics/2_pass_scaling.aspx\" rel=\"noreferrer\">Two Pass Scaling using <strong>Filters</strong></a></li>\n<li><a href=\"http://www.codeproject.com/KB/GDI-plus/matrix_transformation.aspx\" rel=\"noreferrer\">Matrix Transformation of Images in C#, using <strong>.NET GDI+</strong></a></li>\n<li><a href=\"http://www.codeproject.com/KB/GDI-plus/imageresize.aspx\" rel=\"noreferrer\">Resizing a Photographic image with <strong>GDI+ for .NET</strong></a></li>\n<li><a href=\"http://www.codeproject.com/KB/graphics/Dyadic_down_sampling.aspx\" rel=\"noreferrer\">Fast Dyadic Image Scaling with <strong>Haar Transform</strong></a></li>\n</ul>\n" }, { "answer_id": 353193, "author": "plinth", "author_id": 20481, "author_profile": "https://Stackoverflow.com/users/20481", "pm_score": 2, "selected": false, "text": "<p>You can try <a href=\"http://www.atalasoft.com/products/dotimage/\" rel=\"nofollow noreferrer\">dotImage</a>, one of my company's products, which includes an <a href=\"http://www.atalasoft.com/products/dotimage/docs/Atalasoft.dotImage~Atalasoft.Imaging.ImageProcessing.ResampleCommand_members.html\" rel=\"nofollow noreferrer\">object for resampling</a> images that has <a href=\"http://www.atalasoft.com/products/dotimage/docs/Atalasoft.dotImage~Atalasoft.Imaging.ImageProcessing.ResampleMethod.html\" rel=\"nofollow noreferrer\">18 filter types</a> for various levels of quality.</p>\n\n<p>Typical usage is:</p>\n\n<pre><code>// BiCubic is one technique available in PhotoShop\nResampleCommand resampler = new ResampleCommand(newSize, ResampleMethod.BiCubic);\nAtalaImage newImage = resampler.Apply(oldImage).Image;\n</code></pre>\n\n<p>in addition, dotImage includes 140 some odd image processing commands including many filters similar to those in PhotoShop, if that's what you're looking for.</p>\n" }, { "answer_id": 353222, "author": "Doctor Jones", "author_id": 39277, "author_profile": "https://Stackoverflow.com/users/39277", "pm_score": 9, "selected": true, "text": "<p>Here's a nicely commented Image Manipulation helper class that you can look at and use. I wrote it as an example of how to perform certain image manipulation tasks in C#. You'll be interested in the <strong>ResizeImage</strong> function that takes a System.Drawing.Image, the width and the height as the arguments.</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Drawing;\nusing System.Drawing.Imaging;\n\nnamespace DoctaJonez.Drawing.Imaging\n{\n /// &lt;summary&gt;\n /// Provides various image untilities, such as high quality resizing and the ability to save a JPEG.\n /// &lt;/summary&gt;\n public static class ImageUtilities\n { \n /// &lt;summary&gt;\n /// A quick lookup for getting image encoders\n /// &lt;/summary&gt;\n private static Dictionary&lt;string, ImageCodecInfo&gt; encoders = null;\n\n /// &lt;summary&gt;\n /// A lock to prevent concurrency issues loading the encoders.\n /// &lt;/summary&gt;\n private static object encodersLock = new object();\n\n /// &lt;summary&gt;\n /// A quick lookup for getting image encoders\n /// &lt;/summary&gt;\n public static Dictionary&lt;string, ImageCodecInfo&gt; Encoders\n {\n //get accessor that creates the dictionary on demand\n get\n {\n //if the quick lookup isn't initialised, initialise it\n if (encoders == null)\n {\n //protect against concurrency issues\n lock (encodersLock)\n {\n //check again, we might not have been the first person to acquire the lock (see the double checked lock pattern)\n if (encoders == null)\n {\n encoders = new Dictionary&lt;string, ImageCodecInfo&gt;();\n\n //get all the codecs\n foreach (ImageCodecInfo codec in ImageCodecInfo.GetImageEncoders())\n {\n //add each codec to the quick lookup\n encoders.Add(codec.MimeType.ToLower(), codec);\n }\n }\n }\n }\n\n //return the lookup\n return encoders;\n }\n }\n\n /// &lt;summary&gt;\n /// Resize the image to the specified width and height.\n /// &lt;/summary&gt;\n /// &lt;param name=\"image\"&gt;The image to resize.&lt;/param&gt;\n /// &lt;param name=\"width\"&gt;The width to resize to.&lt;/param&gt;\n /// &lt;param name=\"height\"&gt;The height to resize to.&lt;/param&gt;\n /// &lt;returns&gt;The resized image.&lt;/returns&gt;\n public static System.Drawing.Bitmap ResizeImage(System.Drawing.Image image, int width, int height)\n {\n //a holder for the result\n Bitmap result = new Bitmap(width, height);\n //set the resolutions the same to avoid cropping due to resolution differences\n result.SetResolution(image.HorizontalResolution, image.VerticalResolution);\n\n //use a graphics object to draw the resized image into the bitmap\n using (Graphics graphics = Graphics.FromImage(result))\n {\n //set the resize quality modes to high quality\n graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;\n graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;\n graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;\n //draw the image into the target bitmap\n graphics.DrawImage(image, 0, 0, result.Width, result.Height);\n }\n\n //return the resulting bitmap\n return result;\n }\n\n /// &lt;summary&gt; \n /// Saves an image as a jpeg image, with the given quality \n /// &lt;/summary&gt; \n /// &lt;param name=\"path\"&gt;Path to which the image would be saved.&lt;/param&gt; \n /// &lt;param name=\"quality\"&gt;An integer from 0 to 100, with 100 being the \n /// highest quality&lt;/param&gt; \n /// &lt;exception cref=\"ArgumentOutOfRangeException\"&gt;\n /// An invalid value was entered for image quality.\n /// &lt;/exception&gt;\n public static void SaveJpeg(string path, Image image, int quality)\n {\n //ensure the quality is within the correct range\n if ((quality &lt; 0) || (quality &gt; 100))\n {\n //create the error message\n string error = string.Format(\"Jpeg image quality must be between 0 and 100, with 100 being the highest quality. A value of {0} was specified.\", quality);\n //throw a helpful exception\n throw new ArgumentOutOfRangeException(error);\n }\n\n //create an encoder parameter for the image quality\n EncoderParameter qualityParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);\n //get the jpeg codec\n ImageCodecInfo jpegCodec = GetEncoderInfo(\"image/jpeg\");\n\n //create a collection of all parameters that we will pass to the encoder\n EncoderParameters encoderParams = new EncoderParameters(1);\n //set the quality parameter for the codec\n encoderParams.Param[0] = qualityParam;\n //save the image using the codec and the parameters\n image.Save(path, jpegCodec, encoderParams);\n }\n\n /// &lt;summary&gt; \n /// Returns the image codec with the given mime type \n /// &lt;/summary&gt; \n public static ImageCodecInfo GetEncoderInfo(string mimeType)\n {\n //do a case insensitive search for the mime type\n string lookupKey = mimeType.ToLower();\n\n //the codec to return, default to null\n ImageCodecInfo foundCodec = null;\n\n //if we have the encoder, get it to return\n if (Encoders.ContainsKey(lookupKey))\n {\n //pull the codec from the lookup\n foundCodec = Encoders[lookupKey];\n }\n\n return foundCodec;\n } \n }\n}\n</code></pre>\n\n<hr>\n\n<h1>Update</h1>\n\n<p>A few people have been asking in the comments for samples of how to consume the ImageUtilities class, so here you go.</p>\n\n<pre><code>//resize the image to the specified height and width\nusing (var resized = ImageUtilities.ResizeImage(image, 50, 100))\n{\n //save the resized image as a jpeg with a quality of 90\n ImageUtilities.SaveJpeg(@\"C:\\myimage.jpeg\", resized, 90);\n}\n</code></pre>\n\n<h2>Note</h2>\n\n<p>Remember that images are disposable, so you need to assign the result of your resize to a using declaration (or you could use a try finally and make sure you call dispose in your finally).</p>\n" }, { "answer_id": 1339221, "author": "Igor Brejc", "author_id": 55408, "author_profile": "https://Stackoverflow.com/users/55408", "pm_score": 0, "selected": false, "text": "<p>This is an article I spotted being referenced in Paint.NET's code for image resampling: <a href=\"http://paulbourke.net/texture_colour/imageprocess/\" rel=\"nofollow noreferrer\">Various Simple Image Processing Techniques</a> by Paul Bourke.</p>\n" }, { "answer_id": 2919656, "author": "Cryx", "author_id": 351751, "author_profile": "https://Stackoverflow.com/users/351751", "pm_score": 0, "selected": false, "text": "<p>you could try this one if it's a lowres cgi\n<a href=\"http://code.google.com/p/2dimagefilter/\" rel=\"nofollow noreferrer\">2D Image Filter</a></p>\n" }, { "answer_id": 8646234, "author": "Leslie Marshall", "author_id": 1113505, "author_profile": "https://Stackoverflow.com/users/1113505", "pm_score": 2, "selected": false, "text": "<p>This might help</p>\n\n<pre><code> public Image ResizeImage(Image source, RectangleF destinationBounds)\n {\n RectangleF sourceBounds = new RectangleF(0.0f,0.0f,(float)source.Width, (float)source.Height);\n RectangleF scaleBounds = new RectangleF();\n\n Image destinationImage = new Bitmap((int)destinationBounds.Width, (int)destinationBounds.Height);\n Graphics graph = Graphics.FromImage(destinationImage);\n graph.InterpolationMode =\n System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;\n\n // Fill with background color\n graph.FillRectangle(new SolidBrush(System.Drawing.Color.White), destinationBounds);\n\n float resizeRatio, sourceRatio;\n float scaleWidth, scaleHeight;\n\n sourceRatio = (float)source.Width / (float)source.Height;\n\n if (sourceRatio &gt;= 1.0f)\n {\n //landscape\n resizeRatio = destinationBounds.Width / sourceBounds.Width;\n scaleWidth = destinationBounds.Width;\n scaleHeight = sourceBounds.Height * resizeRatio;\n float trimValue = destinationBounds.Height - scaleHeight;\n graph.DrawImage(source, 0, (trimValue / 2), destinationBounds.Width, scaleHeight);\n }\n else\n {\n //portrait\n resizeRatio = destinationBounds.Height/sourceBounds.Height;\n scaleWidth = sourceBounds.Width * resizeRatio;\n scaleHeight = destinationBounds.Height;\n float trimValue = destinationBounds.Width - scaleWidth;\n graph.DrawImage(source, (trimValue / 2), 0, scaleWidth, destinationBounds.Height);\n }\n\n return destinationImage;\n\n }\n</code></pre>\n\n<p>Note the <code>InterpolationMode.HighQualityBicubic</code> -> this is generally a good tradeoff between performance and results.</p>\n" }, { "answer_id": 11344550, "author": "superlogical", "author_id": 52360, "author_profile": "https://Stackoverflow.com/users/52360", "pm_score": 3, "selected": false, "text": "<p>Use this library: <a href=\"http://imageresizing.net\" rel=\"noreferrer\">http://imageresizing.net</a></p>\n\n<p>Have a read of this article by the library author: <a href=\"http://nathanaeljones.com/163/20-image-resizing-pitfalls/\" rel=\"noreferrer\">20 Image Sizing Pitfalls with .NET</a></p>\n" }, { "answer_id": 13887911, "author": "rold2007", "author_id": 263228, "author_profile": "https://Stackoverflow.com/users/263228", "pm_score": 0, "selected": false, "text": "<p>You could try <a href=\"http://johncostella.webs.com/magic/\" rel=\"nofollow\">the magic kernel</a>. It produces less pixelation artifacts than bicubic resample when upscaling and it also gives very good results when downscaling.\nThe source code is available in c# from the web site.</p>\n" }, { "answer_id": 14278580, "author": "DareDevil", "author_id": 1147352, "author_profile": "https://Stackoverflow.com/users/1147352", "pm_score": 1, "selected": false, "text": "<p>Try This basic code snippet:</p>\n\n<pre><code>private static Bitmap ResizeBitmap(Bitmap srcbmp, int width, int height )\n{\n Bitmap newimage = new Bitmap(width, height);\n using (Graphics g = Graphics.FromImage(newimage))\n g.DrawImage(srcbmp, 0, 0, width, height);\n return newimage;\n}\n</code></pre>\n" }, { "answer_id": 25343437, "author": "bafsar", "author_id": 2374053, "author_profile": "https://Stackoverflow.com/users/2374053", "pm_score": 0, "selected": false, "text": "<p>I have some improve for Doctor Jones's answer.</p>\n\n<p>It works for who wanted to how to proportional resize the image. It tested and worked for me.</p>\n\n<p>The methods of class I added:</p>\n\n<pre><code>public static System.Drawing.Bitmap ResizeImage(System.Drawing.Image image, Size size)\n{\n return ResizeImage(image, size.Width, size.Height);\n}\n\n\npublic static Size GetProportionedSize(Image image, int maxWidth, int maxHeight, bool withProportion)\n{\n if (withProportion)\n {\n double sourceWidth = image.Width;\n double sourceHeight = image.Height;\n\n if (sourceWidth &lt; maxWidth &amp;&amp; sourceHeight &lt; maxHeight)\n {\n maxWidth = (int)sourceWidth;\n maxHeight = (int)sourceHeight;\n }\n else\n {\n double aspect = sourceHeight / sourceWidth;\n\n if (sourceWidth &lt; sourceHeight)\n {\n maxWidth = Convert.ToInt32(Math.Round((maxHeight / aspect), 0));\n }\n else\n {\n maxHeight = Convert.ToInt32(Math.Round((maxWidth * aspect), 0));\n }\n }\n }\n\n return new Size(maxWidth, maxHeight);\n}\n</code></pre>\n\n<p>and new available using according to this codes:</p>\n\n<pre><code>using (var resized = ImageUtilities.ResizeImage(image, ImageUtilities.GetProportionedSize(image, 50, 100)))\n{\n ImageUtilities.SaveJpeg(@\"C:\\myimage.jpeg\", resized, 90);\n}\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249587", "https://Stackoverflow.com", "https://Stackoverflow.com/users/191/" ]
I want to scale an image in C# with quality level as good as Photoshop does. Is there any C# image processing library available to do this thing?
Here's a nicely commented Image Manipulation helper class that you can look at and use. I wrote it as an example of how to perform certain image manipulation tasks in C#. You'll be interested in the **ResizeImage** function that takes a System.Drawing.Image, the width and the height as the arguments. ``` using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; namespace DoctaJonez.Drawing.Imaging { /// <summary> /// Provides various image untilities, such as high quality resizing and the ability to save a JPEG. /// </summary> public static class ImageUtilities { /// <summary> /// A quick lookup for getting image encoders /// </summary> private static Dictionary<string, ImageCodecInfo> encoders = null; /// <summary> /// A lock to prevent concurrency issues loading the encoders. /// </summary> private static object encodersLock = new object(); /// <summary> /// A quick lookup for getting image encoders /// </summary> public static Dictionary<string, ImageCodecInfo> Encoders { //get accessor that creates the dictionary on demand get { //if the quick lookup isn't initialised, initialise it if (encoders == null) { //protect against concurrency issues lock (encodersLock) { //check again, we might not have been the first person to acquire the lock (see the double checked lock pattern) if (encoders == null) { encoders = new Dictionary<string, ImageCodecInfo>(); //get all the codecs foreach (ImageCodecInfo codec in ImageCodecInfo.GetImageEncoders()) { //add each codec to the quick lookup encoders.Add(codec.MimeType.ToLower(), codec); } } } } //return the lookup return encoders; } } /// <summary> /// Resize the image to the specified width and height. /// </summary> /// <param name="image">The image to resize.</param> /// <param name="width">The width to resize to.</param> /// <param name="height">The height to resize to.</param> /// <returns>The resized image.</returns> public static System.Drawing.Bitmap ResizeImage(System.Drawing.Image image, int width, int height) { //a holder for the result Bitmap result = new Bitmap(width, height); //set the resolutions the same to avoid cropping due to resolution differences result.SetResolution(image.HorizontalResolution, image.VerticalResolution); //use a graphics object to draw the resized image into the bitmap using (Graphics graphics = Graphics.FromImage(result)) { //set the resize quality modes to high quality graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; //draw the image into the target bitmap graphics.DrawImage(image, 0, 0, result.Width, result.Height); } //return the resulting bitmap return result; } /// <summary> /// Saves an image as a jpeg image, with the given quality /// </summary> /// <param name="path">Path to which the image would be saved.</param> /// <param name="quality">An integer from 0 to 100, with 100 being the /// highest quality</param> /// <exception cref="ArgumentOutOfRangeException"> /// An invalid value was entered for image quality. /// </exception> public static void SaveJpeg(string path, Image image, int quality) { //ensure the quality is within the correct range if ((quality < 0) || (quality > 100)) { //create the error message string error = string.Format("Jpeg image quality must be between 0 and 100, with 100 being the highest quality. A value of {0} was specified.", quality); //throw a helpful exception throw new ArgumentOutOfRangeException(error); } //create an encoder parameter for the image quality EncoderParameter qualityParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality); //get the jpeg codec ImageCodecInfo jpegCodec = GetEncoderInfo("image/jpeg"); //create a collection of all parameters that we will pass to the encoder EncoderParameters encoderParams = new EncoderParameters(1); //set the quality parameter for the codec encoderParams.Param[0] = qualityParam; //save the image using the codec and the parameters image.Save(path, jpegCodec, encoderParams); } /// <summary> /// Returns the image codec with the given mime type /// </summary> public static ImageCodecInfo GetEncoderInfo(string mimeType) { //do a case insensitive search for the mime type string lookupKey = mimeType.ToLower(); //the codec to return, default to null ImageCodecInfo foundCodec = null; //if we have the encoder, get it to return if (Encoders.ContainsKey(lookupKey)) { //pull the codec from the lookup foundCodec = Encoders[lookupKey]; } return foundCodec; } } } ``` --- Update ====== A few people have been asking in the comments for samples of how to consume the ImageUtilities class, so here you go. ``` //resize the image to the specified height and width using (var resized = ImageUtilities.ResizeImage(image, 50, 100)) { //save the resized image as a jpeg with a quality of 90 ImageUtilities.SaveJpeg(@"C:\myimage.jpeg", resized, 90); } ``` Note ---- Remember that images are disposable, so you need to assign the result of your resize to a using declaration (or you could use a try finally and make sure you call dispose in your finally).
249,607
<p>I am using Visual C++ 2005 Express Edition and get the following linker errors:</p> <pre><code>19&gt;mylib1.lib(mylibsource1.obj) : error LNK2019: unresolved external symbol "__declspec(dllimport) public: void __thiscall std::exception::_Raise(void)const " (__imp_?_Raise@exception@std@@QBEXXZ) referenced in function "protected: static void __cdecl std::vector&lt;class mytype,class std::allocator&lt;class mytype&gt; &gt;::_Xlen(void)" (?_Xlen@?$vector@Vmytype@@V?$allocator@Vmytype@@@std@@@std@@KAXXZ) 19&gt;mylib2.lib(mylibsource2.obj) : error LNK2001: unresolved external symbol "__declspec(dllimport) public: void __thiscall std::exception::_Raise(void)const " (__imp_?_Raise@exception@std@@QBEXXZ) 19&gt;mylib1.lib(mylibsource1.obj) : error LNK2019: unresolved external symbol "__declspec(dllimport) public: __thiscall std::exception::exception(char const *,int)" (__imp_??0exception@std@@QAE@PBDH@Z) referenced in function "public: __thiscall std::logic_error::logic_error(class std::basic_string&lt;char,struct std::char_traits&lt;char&gt;,class std::allocator&lt;char&gt; &gt; const &amp;)" (??0logic_error@std@@QAE@ABV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@1@@Z) 19&gt;mylib2.lib(mylibsource2.obj) : error LNK2001: unresolved external symbol "__declspec(dllimport) public: __thiscall std::exception::exception(char const *,int)" (__imp_??0exception@std@@QAE@PBDH@Z) </code></pre> <p>I turned off exceptions in generated code, and I am using before including the vector header file:</p> <pre><code>#define _HAS_EXCEPTIONS 0 </code></pre> <p>A few Google results turned up some stuff, but no "aha!" solutions that worked for me.</p> <p>EDIT:</p> <p>As noted "_HAS_EXCEPTIONS 0" doesn't turn off exceptions, per se. What it does is, at least in the vector header file, is call _Raise on an exception object instead of calling the C++ "throw". In my case, it can't link to the exception object's _Raise function since I am not including the correct library. What that library is, though, is not obvious.</p>
[ { "answer_id": 249685, "author": "MSalters", "author_id": 15416, "author_profile": "https://Stackoverflow.com/users/15416", "pm_score": 0, "selected": false, "text": "<p>The third error makes it clear that <code>#define the _HAS_EXCEPTIONS 0</code> does not affect . Now, might include (makes sense, sharing code might reduce the size of your executable). That would explain why you still have errors if you define it before <em>your</em> inclusion of . This kind of defines should be done in your project settings.</p>\n\n<p>Note that _HAS_EXCEPTIONS is an unsupported feature in Visual Studio. It does not turn off exceptions as such.</p>\n" }, { "answer_id": 254069, "author": "Jim Buck", "author_id": 2666, "author_profile": "https://Stackoverflow.com/users/2666", "pm_score": 2, "selected": true, "text": "<p>Adding this line:</p>\n\n<pre><code>#define _STATIC_CPPLIB\n</code></pre>\n\n<p>before including the vector header seems to do the trick.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2666/" ]
I am using Visual C++ 2005 Express Edition and get the following linker errors: ``` 19>mylib1.lib(mylibsource1.obj) : error LNK2019: unresolved external symbol "__declspec(dllimport) public: void __thiscall std::exception::_Raise(void)const " (__imp_?_Raise@exception@std@@QBEXXZ) referenced in function "protected: static void __cdecl std::vector<class mytype,class std::allocator<class mytype> >::_Xlen(void)" (?_Xlen@?$vector@Vmytype@@V?$allocator@Vmytype@@@std@@@std@@KAXXZ) 19>mylib2.lib(mylibsource2.obj) : error LNK2001: unresolved external symbol "__declspec(dllimport) public: void __thiscall std::exception::_Raise(void)const " (__imp_?_Raise@exception@std@@QBEXXZ) 19>mylib1.lib(mylibsource1.obj) : error LNK2019: unresolved external symbol "__declspec(dllimport) public: __thiscall std::exception::exception(char const *,int)" (__imp_??0exception@std@@QAE@PBDH@Z) referenced in function "public: __thiscall std::logic_error::logic_error(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &)" (??0logic_error@std@@QAE@ABV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@1@@Z) 19>mylib2.lib(mylibsource2.obj) : error LNK2001: unresolved external symbol "__declspec(dllimport) public: __thiscall std::exception::exception(char const *,int)" (__imp_??0exception@std@@QAE@PBDH@Z) ``` I turned off exceptions in generated code, and I am using before including the vector header file: ``` #define _HAS_EXCEPTIONS 0 ``` A few Google results turned up some stuff, but no "aha!" solutions that worked for me. EDIT: As noted "\_HAS\_EXCEPTIONS 0" doesn't turn off exceptions, per se. What it does is, at least in the vector header file, is call \_Raise on an exception object instead of calling the C++ "throw". In my case, it can't link to the exception object's \_Raise function since I am not including the correct library. What that library is, though, is not obvious.
Adding this line: ``` #define _STATIC_CPPLIB ``` before including the vector header seems to do the trick.
249,632
<p>What is the time complexity? Why?</p> <pre><code>(define (mult a b) (define (internal a accum) (if (= a 1) accum (internal (- a 1) (+ accum b)))) (internal a b)) (define (to-the-power-of m n) (define (internal x accum) (if (= x 0) accum (internal (- x 1) (mult accum m)))) (internal n 1)) </code></pre>
[ { "answer_id": 249652, "author": "Pramod", "author_id": 1386292, "author_profile": "https://Stackoverflow.com/users/1386292", "pm_score": 0, "selected": false, "text": "<p>Assuming addition and multiplication are both counted as a single operation, this function performs O(m^n) operations. </p>\n\n<p>First consider the mult function. It (mult a b) will perform exactly a-1 additions. Since, the asymptotic growth is the same, lets approximate this by a, for mathematical simplicity.</p>\n\n<p>Now for the to-the-power-of function, this performs n calls to the mult function. These calls are to (mult 1 m), yield m, then to (mult m m), yielding m^2, then to (mult m^2 m), yielding m^3 and so on upto m^n. So the total number of operations performed here is the sum m^0 + m^1 + ... + m^n. This is (m^n - 1) / (m-1) which grows as m^n.</p>\n" }, { "answer_id": 249654, "author": "sven", "author_id": 46, "author_profile": "https://Stackoverflow.com/users/46", "pm_score": 2, "selected": false, "text": "<p>the time complexity for the mult part can be found like this:</p>\n\n<p>to calculate (mult a b), (internal a accum) is called until a = 1\nso we have some kind of tail recursion (loop) that iterates over a.</p>\n\n<p>we thus know that the time complexity of (mult a b) is <strong>O(a)</strong> (= linear time complexity)</p>\n\n<p>(to-the-power-of m n) also has an (internal x accum) definition, that also loops (until x = 0)</p>\n\n<p>so again we have <strong>O(x)</strong> (= linear time complexity)</p>\n\n<p><em>But</em>: we didn't take into account the time needed for the function calls of internal...<br>\nIn internal, we use the (mult a b) definition which is linear in time complexity so we have the following case:\nin the first iteration mult is called with: (mult 1 m) --> O(1)<br>\nsecond iteration this becomes: (mult m m) --> O(m)<br>\nthird iteration: (mult m² m) --> O(m*m)\nand so on\nIt is clear that this grows until n = 0 (or in internal this becomes x = 0)</p>\n\n<p>thus we can say that the time complexity will depend on m and n: <strong>O(m^n)</strong></p>\n\n<p>[edit:] you can also take a look at a related question I asked earlier: <a href=\"https://stackoverflow.com/questions/3255/big-o-how-do-you-calculateapproximate-it\">Big O, how do you calculate/approximate it?</a> which may give you a clue how you can handle the approximation more generally</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249632", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
What is the time complexity? Why? ``` (define (mult a b) (define (internal a accum) (if (= a 1) accum (internal (- a 1) (+ accum b)))) (internal a b)) (define (to-the-power-of m n) (define (internal x accum) (if (= x 0) accum (internal (- x 1) (mult accum m)))) (internal n 1)) ```
the time complexity for the mult part can be found like this: to calculate (mult a b), (internal a accum) is called until a = 1 so we have some kind of tail recursion (loop) that iterates over a. we thus know that the time complexity of (mult a b) is **O(a)** (= linear time complexity) (to-the-power-of m n) also has an (internal x accum) definition, that also loops (until x = 0) so again we have **O(x)** (= linear time complexity) *But*: we didn't take into account the time needed for the function calls of internal... In internal, we use the (mult a b) definition which is linear in time complexity so we have the following case: in the first iteration mult is called with: (mult 1 m) --> O(1) second iteration this becomes: (mult m m) --> O(m) third iteration: (mult m² m) --> O(m\*m) and so on It is clear that this grows until n = 0 (or in internal this becomes x = 0) thus we can say that the time complexity will depend on m and n: **O(m^n)** [edit:] you can also take a look at a related question I asked earlier: [Big O, how do you calculate/approximate it?](https://stackoverflow.com/questions/3255/big-o-how-do-you-calculateapproximate-it) which may give you a clue how you can handle the approximation more generally
249,637
<p>Let's suppose I have an applet running within a page in a browser. What happens when the browser is closed by the user?</p> <p>Is the applet notified so that it can perform some kind of close action on its side (closing connections opened to a server, cleaning static variables, ...)?</p> <p>Also, I assume the same behavior would apply for a page refresh or page navigation (instead of browser close). The browser remains opened but the applet is gone. Although when you close the browser you also close the JVM so I'm unsure at this point.</p> <p>Thanks, JB</p>
[ { "answer_id": 249643, "author": "keparo", "author_id": 19468, "author_profile": "https://Stackoverflow.com/users/19468", "pm_score": 3, "selected": true, "text": "<p>Yes, the <strong>destroy() method</strong> should be called before the <strong>browser unloads the object</strong>.</p>\n\n<p><strong>destroy()</strong> is the last of four \"<strong>life-cycle methods</strong>\" of the Java applet (the others are <strong>init()</strong>, <strong>start()</strong>, and <strong>stop()</strong> ). They're actually called at different times depending on your <strong>browser</strong> and <strong>virtual machine</strong>. If you'd like to know exactly when each is called, implement each method within your applet, and System.out some feedback.</p>\n\n<p>Ideally, destroy() should be <strong>called by the environment</strong>, and should only be called once. If it seems like destroy() is not being called, you might declare a public finalize() method, which calls destroy. You could also try to call destroy() from javascript as the window object unloads, but again, be sure that you're not calling destroy() unnecessarily.</p>\n\n<pre><code>public void finalize () {\n destroy();\n}\n</code></pre>\n" }, { "answer_id": 298802, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Most Of the times destroy will be called , but it dont get enough time to do required tasks in case of closing the window.</p>\n\n<p>It gets enough time when refreshing , navigating with Backword &lt;- and Forward -></p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249637", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7218/" ]
Let's suppose I have an applet running within a page in a browser. What happens when the browser is closed by the user? Is the applet notified so that it can perform some kind of close action on its side (closing connections opened to a server, cleaning static variables, ...)? Also, I assume the same behavior would apply for a page refresh or page navigation (instead of browser close). The browser remains opened but the applet is gone. Although when you close the browser you also close the JVM so I'm unsure at this point. Thanks, JB
Yes, the **destroy() method** should be called before the **browser unloads the object**. **destroy()** is the last of four "**life-cycle methods**" of the Java applet (the others are **init()**, **start()**, and **stop()** ). They're actually called at different times depending on your **browser** and **virtual machine**. If you'd like to know exactly when each is called, implement each method within your applet, and System.out some feedback. Ideally, destroy() should be **called by the environment**, and should only be called once. If it seems like destroy() is not being called, you might declare a public finalize() method, which calls destroy. You could also try to call destroy() from javascript as the window object unloads, but again, be sure that you're not calling destroy() unnecessarily. ``` public void finalize () { destroy(); } ```
249,655
<p>I work on a large project in Delphi 5. Today, after merging two branches of the app together, one of the hundreds of units, UnitMain (the main form's unit, would you guess) stopped recognizing the Application global.</p> <p>This is a rather bizarre problem - I could get the program to compile by defining Application: TApplication in UnitMain, and setting that to the Application from our .dpr project file, but that leads to an access violation, which isn't much of a surprise with Application being the special thing it is.</p> <p>I'm hoping someone has faced the same problem before, or knows enough of Delphi VCL's inner workings to help me out here.</p> <pre><code>unit UnitMain; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Menus, ComCtrls, StdCtrls, cxButtons, ExtCtrls, IniFiles, ShellAPI, LMDControl, LMDBaseControl, LMDBaseGraphicControl, LMDGraphicControl, LMDScrollText, cxControls, cxContainer, cxListBox, Psock, NMFtp, db, DBTables, FileCtrl, Configs, cxHint, DSetFunc, OleCtrls, DsInformation, InterAppComm, ActnList, ADODB, OleServer, CRAXDRT_TLB; </code></pre> <p>The exact error is that the compiler does not recognize Application in this unit. For example, for a Application.ProcessMessages; call, the error is "Object or class type required". None of the other units has this problem.</p>
[ { "answer_id": 249669, "author": "Re0sless", "author_id": 2098, "author_profile": "https://Stackoverflow.com/users/2098", "pm_score": 2, "selected": false, "text": "<p>What units are in the uses clause at the top of the file? Application comes from the \"Forms\" unit.</p>\n\n<p>eg.</p>\n\n<pre><code>unit MyUnit;\n\ninterface\n\nuses\n Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms;\n</code></pre>\n" }, { "answer_id": 249710, "author": "Barry Kelly", "author_id": 3712, "author_profile": "https://Stackoverflow.com/users/3712", "pm_score": 5, "selected": true, "text": "<p>I think it is most likely that you have two symbols called \"Application\" in scope, and the one from the Forms unit isn't the active one. Make sure the Forms unit in the uses list comes after any prior unit that contains a symbol called Application.</p>\n\n<p>But, you need to provide more information. The exact error messages, etc.</p>\n" }, { "answer_id": 249930, "author": "Mike Sutton", "author_id": 23008, "author_profile": "https://Stackoverflow.com/users/23008", "pm_score": 3, "selected": false, "text": "<p>I'm pleased to see everythings working now, but I'll add that another way to solve such problems, especially if you don't want to rearrange your uses clauses is to prefix the unit name to whatever you want to use, eg.</p>\n\n<pre><code>Forms.Application.ProcessMessages;\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249655", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15477/" ]
I work on a large project in Delphi 5. Today, after merging two branches of the app together, one of the hundreds of units, UnitMain (the main form's unit, would you guess) stopped recognizing the Application global. This is a rather bizarre problem - I could get the program to compile by defining Application: TApplication in UnitMain, and setting that to the Application from our .dpr project file, but that leads to an access violation, which isn't much of a surprise with Application being the special thing it is. I'm hoping someone has faced the same problem before, or knows enough of Delphi VCL's inner workings to help me out here. ``` unit UnitMain; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Menus, ComCtrls, StdCtrls, cxButtons, ExtCtrls, IniFiles, ShellAPI, LMDControl, LMDBaseControl, LMDBaseGraphicControl, LMDGraphicControl, LMDScrollText, cxControls, cxContainer, cxListBox, Psock, NMFtp, db, DBTables, FileCtrl, Configs, cxHint, DSetFunc, OleCtrls, DsInformation, InterAppComm, ActnList, ADODB, OleServer, CRAXDRT_TLB; ``` The exact error is that the compiler does not recognize Application in this unit. For example, for a Application.ProcessMessages; call, the error is "Object or class type required". None of the other units has this problem.
I think it is most likely that you have two symbols called "Application" in scope, and the one from the Forms unit isn't the active one. Make sure the Forms unit in the uses list comes after any prior unit that contains a symbol called Application. But, you need to provide more information. The exact error messages, etc.
249,657
<p>could someone provide working example (full maven plugin configuration) how to copy built jar file to a specific server(s) at the time of deploy phase?</p> <p>I have tried to look at wagon plugin, but it is hugely undocumented and I was not able to set it up. The build produces standard jar that is being deployed to Nexus, but I need to put the jar also to the test server automatically over local network (\someserver\testapp\bin).</p> <p>I will be grateful for any hints.</p> <p>Thank you</p>
[ { "answer_id": 249911, "author": "Roland Schneider", "author_id": 16515, "author_profile": "https://Stackoverflow.com/users/16515", "pm_score": 1, "selected": false, "text": "<p>I don't have a working example but the <a href=\"http://maven.apache.org/plugins/maven-assembly-plugin/assembly.html\" rel=\"nofollow noreferrer\">\"Maven Assembly Plugin\"</a> should do the job. You can configure it to run automatically in the deploy phase.<br>\nWhen you write your own assembly descriptor you can specify a path where the assembly should be written to. I think maven shouldn't care about whether it's a local or remote path.</p>\n" }, { "answer_id": 250021, "author": "Petr Macek", "author_id": 15045, "author_profile": "https://Stackoverflow.com/users/15045", "pm_score": 3, "selected": false, "text": "<p>Actually I have found a different way:\nDependency plugin!</p>\n\n<pre><code>&lt;plugin&gt;\n &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;\n &lt;artifactId&gt;maven-dependency-plugin&lt;/artifactId&gt;\n &lt;executions&gt;\n &lt;execution&gt;\n &lt;id&gt;copy-to-ebs&lt;/id&gt;\n &lt;phase&gt;deploy&lt;/phase&gt;\n &lt;goals&gt;\n &lt;goal&gt;copy&lt;/goal&gt;\n &lt;/goals&gt;\n &lt;configuration&gt;\n &lt;artifactItems&gt;\n &lt;artifactItem&gt;\n &lt;groupId&gt;${project.groupId}&lt;/groupId&gt;\n &lt;artifactId&gt;${project.artifactId}&lt;/artifactId&gt;\n &lt;version&gt;${project.version}&lt;/version&gt;\n &lt;type&gt;${project.packaging}&lt;/type&gt;\n &lt;/artifactItem&gt;\n &lt;/artifactItems&gt;\n &lt;outputDirectory&gt;\\\\someserver\\somedirectory&lt;/outputDirectory&gt;\n &lt;stripVersion&gt;true&lt;/stripVersion&gt; \n &lt;/configuration&gt;\n &lt;/execution&gt; \n &lt;/executions&gt;\n&lt;/plugin&gt;\n</code></pre>\n\n<p>It also takes windows path like \\\\resource.</p>\n\n<p>Note that \\\\someserver\\somedirectory works from windows client only.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15045/" ]
could someone provide working example (full maven plugin configuration) how to copy built jar file to a specific server(s) at the time of deploy phase? I have tried to look at wagon plugin, but it is hugely undocumented and I was not able to set it up. The build produces standard jar that is being deployed to Nexus, but I need to put the jar also to the test server automatically over local network (\someserver\testapp\bin). I will be grateful for any hints. Thank you
Actually I have found a different way: Dependency plugin! ``` <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-dependency-plugin</artifactId> <executions> <execution> <id>copy-to-ebs</id> <phase>deploy</phase> <goals> <goal>copy</goal> </goals> <configuration> <artifactItems> <artifactItem> <groupId>${project.groupId}</groupId> <artifactId>${project.artifactId}</artifactId> <version>${project.version}</version> <type>${project.packaging}</type> </artifactItem> </artifactItems> <outputDirectory>\\someserver\somedirectory</outputDirectory> <stripVersion>true</stripVersion> </configuration> </execution> </executions> </plugin> ``` It also takes windows path like \\resource. Note that \\someserver\somedirectory works from windows client only.
249,664
<p>I found the discussion on <a href="https://stackoverflow.com/questions/105007/do-you-test-private-method">Do you test private method</a> informative.</p> <p>I have decided, that in some classes, I want to have protected methods, but test them. Some of these methods are static and short. Because most of the public methods make use of them, I will probably be able to safely remove the tests later. But for starting with a TDD approach and avoid debugging, I really want to test them.</p> <p>I thought of the following:</p> <ul> <li><a href="http://www.refactoring.com/catalog/replaceMethodWithMethodObject.html" rel="noreferrer">Method Object</a> as adviced in <a href="https://stackoverflow.com/questions/105007/do-you-test-private-method#105021">an answer</a> seems to be overkill for this.</li> <li>Start with public methods and when code coverage is given by higher level tests, turn them protected and remove the tests.</li> <li>Inherit a class with a testable interface making protected methods public</li> </ul> <p>Which is best practice? Is there anything else?</p> <p>It seems, that JUnit automatically changes protected methods to be public, but I did not have a deeper look at it. PHP does not allow this via <a href="http://php.net/language.oop5.reflection" rel="noreferrer">reflection</a>.</p>
[ { "answer_id": 249776, "author": "troelskn", "author_id": 18180, "author_profile": "https://Stackoverflow.com/users/18180", "pm_score": 6, "selected": false, "text": "<p>You seem to be aware already, but I'll just restate it anyway; It's a bad sign, if you need to test protected methods. The aim of a unit test, is to test the interface of a class, and protected methods are implementation details. That said, there are cases where it makes sense. If you use inheritance, you can see a superclass as providing an interface for the subclass. So here, you would have to test the protected method (But never a <em>private</em> one). The solution to this, is to create a subclass for testing purpose, and use this to expose the methods. Eg.:</p>\n\n<pre><code>class Foo {\n protected function stuff() {\n // secret stuff, you want to test\n }\n}\n\nclass SubFoo extends Foo {\n public function exposedStuff() {\n return $this-&gt;stuff();\n }\n}\n</code></pre>\n\n<p>Note that you can always replace inheritance with composition. When testing code, it's usually a lot easier to deal with code that uses this pattern, so you may want to consider that option.</p>\n" }, { "answer_id": 254468, "author": "Michael Johnson", "author_id": 17688, "author_profile": "https://Stackoverflow.com/users/17688", "pm_score": 4, "selected": false, "text": "<p>I think troelskn is close. I would do this instead:</p>\n\n<pre><code>class ClassToTest\n{\n protected function testThisMethod()\n {\n // Implement stuff here\n }\n}\n</code></pre>\n\n<p>Then, implement something like this:</p>\n\n<pre><code>class TestClassToTest extends ClassToTest\n{\n public function testThisMethod()\n {\n return parent::testThisMethod();\n }\n}\n</code></pre>\n\n<p>You then run your tests against TestClassToTest.</p>\n\n<p>It should be possible to automatically generate such extension classes by parsing the code. I wouldn't be surprised if PHPUnit already offers such a mechanism (though I haven't checked).</p>\n" }, { "answer_id": 1398842, "author": "Anirudh Zala", "author_id": 170743, "author_profile": "https://Stackoverflow.com/users/170743", "pm_score": 2, "selected": false, "text": "<p>I suggest following workaround for \"Henrik Paul\"'s workaround/idea :)</p>\n\n<p>You know names of private methods of your class. For example they are like _add(), _edit(), _delete() etc.</p>\n\n<p>Hence when you want to test it from aspect of unit-testing, just call private methods by prefixing and/or suffixing some <em>common</em> word (for example _addPhpunit) so that when __call() method is called (since method _addPhpunit() doesn't exist) of owner class, you just put necessary code in __call() method to remove prefixed/suffixed word/s (Phpunit) and then to call that deduced private method from there. This is another good use of magic methods.</p>\n\n<p>Try it out.</p>\n" }, { "answer_id": 2790847, "author": "David Harkness", "author_id": 285873, "author_profile": "https://Stackoverflow.com/users/285873", "pm_score": 3, "selected": false, "text": "<p>You can indeed use __call() in a generic fashion to access protected methods. To be able to test this class</p>\n\n<pre><code>class Example {\n protected function getMessage() {\n return 'hello';\n }\n}\n</code></pre>\n\n<p>you create a subclass in ExampleTest.php:</p>\n\n<pre><code>class ExampleExposed extends Example {\n public function __call($method, array $args = array()) {\n if (!method_exists($this, $method))\n throw new BadMethodCallException(\"method '$method' does not exist\");\n return call_user_func_array(array($this, $method), $args);\n }\n}\n</code></pre>\n\n<p>Note that the __call() method does not reference the class in any way so you can copy the above for each class with protected methods you want to test and just change the class declaration. You may be able to place this function in a common base class, but I haven't tried it.</p>\n\n<p>Now the test case itself only differs in where you construct the object to be tested, swapping in ExampleExposed for Example.</p>\n\n<pre><code>class ExampleTest extends PHPUnit_Framework_TestCase {\n function testGetMessage() {\n $fixture = new ExampleExposed();\n self::assertEquals('hello', $fixture-&gt;getMessage());\n }\n}\n</code></pre>\n\n<p>I believe PHP 5.3 allows you to use reflection to change the accessibility of methods directly, but I assume you'd have to do so for each method individually.</p>\n" }, { "answer_id": 2798203, "author": "uckelman", "author_id": 181106, "author_profile": "https://Stackoverflow.com/users/181106", "pm_score": 10, "selected": true, "text": "<p>If you're using PHP5 (>= 5.3.2) with PHPUnit, you can test your private and protected methods by using reflection to set them to be public prior to running your tests:</p>\n\n<pre><code>protected static function getMethod($name) {\n $class = new ReflectionClass('MyClass');\n $method = $class-&gt;getMethod($name);\n $method-&gt;setAccessible(true);\n return $method;\n}\n\npublic function testFoo() {\n $foo = self::getMethod('foo');\n $obj = new MyClass();\n $foo-&gt;invokeArgs($obj, array(...));\n ...\n}\n</code></pre>\n" }, { "answer_id": 3576958, "author": "sunwukung", "author_id": 124192, "author_profile": "https://Stackoverflow.com/users/124192", "pm_score": 3, "selected": false, "text": "<p>I'm going to throw my hat into the ring here:</p>\n\n<p>I've used the __call hack with mixed degrees of success. \nThe alternative I came up with was to use the Visitor pattern:</p>\n\n<p>1: generate a stdClass or custom class (to enforce type)</p>\n\n<p>2: prime that with the required method and arguments</p>\n\n<p>3: ensure that your SUT has an acceptVisitor method which will execute the method with the arguments specified in the visiting class</p>\n\n<p>4: inject it into the class you wish to test</p>\n\n<p>5: SUT injects the result of operation into the visitor</p>\n\n<p>6: apply your test conditions to the Visitor's result attribute</p>\n" }, { "answer_id": 5671560, "author": "teastburn", "author_id": 224221, "author_profile": "https://Stackoverflow.com/users/224221", "pm_score": 5, "selected": false, "text": "<p>I'd like to propose a slight variation to getMethod() defined in <a href=\"https://stackoverflow.com/questions/249664/best-practices-to-test-protected-methods-with-phpunit/2798203#2798203\">uckelman's answer</a>.</p>\n<p>This version changes getMethod() by removing hard-coded values and simplifying usage a little. I recommend adding it to your PHPUnitUtil class as in the example below or to your PHPUnit_Framework_TestCase-extending class (or, I suppose, globally to your PHPUnitUtil file).</p>\n<p>Since MyClass is being instantiated anyways and ReflectionClass can take a string or an object...</p>\n<pre><code>class PHPUnitUtil {\n /**\n * Get a private or protected method for testing/documentation purposes.\n * How to use for MyClass-&gt;foo():\n * $cls = new MyClass();\n * $foo = PHPUnitUtil::getPrivateMethod($cls, 'foo');\n * $foo-&gt;invoke($cls, $...);\n * @param object $obj The instantiated instance of your class\n * @param string $name The name of your private/protected method\n * @return ReflectionMethod The method you asked for\n */\n public static function getPrivateMethod($obj, $name) {\n $class = new ReflectionClass($obj);\n $method = $class-&gt;getMethod($name);\n $method-&gt;setAccessible(true);\n return $method;\n }\n // ... some other functions\n}\n</code></pre>\n<p>I also created an alias function getProtectedMethod() to be explicit what is expected, but that one's up to you.</p>\n" }, { "answer_id": 8702347, "author": "robert.egginton", "author_id": 987484, "author_profile": "https://Stackoverflow.com/users/987484", "pm_score": 6, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/questions/249664/best-practices-to-test-protected-methods-with-phpunit/8702347#answer-5671560\">teastburn</a> has the right approach. Even simpler is to call the method directly and return the answer:</p>\n\n<pre><code>class PHPUnitUtil\n{\n public static function callMethod($obj, $name, array $args) {\n $class = new \\ReflectionClass($obj);\n $method = $class-&gt;getMethod($name);\n $method-&gt;setAccessible(true);\n return $method-&gt;invokeArgs($obj, $args);\n }\n}\n</code></pre>\n\n<p>You can call this simply in your tests by:</p>\n\n<pre><code>$returnVal = PHPUnitUtil::callMethod(\n $this-&gt;object,\n '_nameOfProtectedMethod', \n array($arg1, $arg2)\n );\n</code></pre>\n" }, { "answer_id": 70153700, "author": "AlexeyP0708", "author_id": 11903519, "author_profile": "https://Stackoverflow.com/users/11903519", "pm_score": 0, "selected": false, "text": "<p>Alternative.The code below is provided as an example.\nIts implementation can be much broader.\nIts implementation that will help you test private methods and replacing a private property .</p>\n<pre class=\"lang-php prettyprint-override\"><code> &lt;?php\n class Helper{\n public static function sandbox(\\Closure $call,$target,?string $slaveClass=null,...$args)\n {\n $slaveClass=!empty($slaveClass)?$slaveClass:(is_string($target)?$target:get_class($target));\n $target=!is_string($target)?$target:null;\n $call=$call-&gt;bindTo($target,$slaveClass);\n return $call(...$args);\n }\n }\n class A{\n private $prop='bay';\n public function get()\n {\n return $this-&gt;prop; \n }\n \n }\n class B extends A{}\n $b=new B;\n $priv_prop=Helper::sandbox(function(...$args){\n return $this-&gt;prop;\n },$b,A::class);\n \n var_dump($priv_prop);// bay\n \n Helper::sandbox(function(...$args){\n $this-&gt;prop=$args[0];\n },$b,A::class,'hello');\n var_dump($b-&gt;get());// hello\n</code></pre>\n" }, { "answer_id": 70911711, "author": "Артем Вирский", "author_id": 13363316, "author_profile": "https://Stackoverflow.com/users/13363316", "pm_score": 0, "selected": false, "text": "<p>You can use <a href=\"https://www.php.net/manual/class.closure.php\" rel=\"nofollow noreferrer\">Closure</a> as in the code below</p>\n<pre><code>&lt;?php\n\nclass A\n{\n private string $value = 'Kolobol';\n private string $otherPrivateValue = 'I\\'m very private, like a some kind of password!';\n\n public function setValue(string $value): void\n {\n $this-&gt;value = $value;\n }\n\n private function getValue(): string\n {\n return $this-&gt;value . ': ' . $this-&gt;getVeryPrivate();\n }\n\n private function getVeryPrivate()\n {\n return $this-&gt;otherPrivateValue;\n }\n}\n\n$getPrivateProperty = function &amp;(string $propName) {\n return $this-&gt;$propName;\n};\n\n$getPrivateMethod = function (string $methodName) {\n return Closure::fromCallable([$this, $methodName]);\n};\n\n$objA = new A;\n$getPrivateProperty = Closure::bind($getPrivateProperty, $objA, $objA);\n$getPrivateMethod = Closure::bind($getPrivateMethod, $objA, $objA);\n$privateByLink = &amp;$getPrivateProperty('value');\n$privateMethod = $getPrivateMethod('getValue');\n\necho $privateByLink, PHP_EOL; // Kolobok\n\n$objA-&gt;setValue('Zmey-Gorynich');\necho $privateByLink, PHP_EOL; // Zmey-Gorynich\n\n$privateByLink = 'Alyonushka';\necho $privateMethod(); // Alyonushka: I'm very private, like a some kind of password!\n</code></pre>\n" }, { "answer_id": 71605134, "author": "Dan", "author_id": 6394404, "author_profile": "https://Stackoverflow.com/users/6394404", "pm_score": 0, "selected": false, "text": "<p>I made a class for invoking easily private methods (static and non-static) for unit-testing purposes:</p>\n<pre class=\"lang-php prettyprint-override\"><code>class MethodInvoker\n{\n public function invoke($object, string $methodName, array $args=[]) {\n $privateMethod = $this-&gt;getMethod(get_class($object), $methodName);\n\n return $privateMethod-&gt;invokeArgs($object, $args);\n }\n\n private function getMethod(string $className, string $methodName) {\n $class = new \\ReflectionClass($className);\n \n $method = $class-&gt;getMethod($methodName);\n $method-&gt;setAccessible(true);\n \n return $method;\n }\n}\n</code></pre>\n<h3>Example of usage:</h3>\n<pre class=\"lang-php prettyprint-override\"><code>class TestClass {\n private function privateMethod(string $txt) {\n print_r('invoked privateMethod: ' . $txt);\n }\n}\n\n(new MethodInvoker)-&gt;invoke(new TestClass, 'privateMethod', ['argument_1']);\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249664", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32679/" ]
I found the discussion on [Do you test private method](https://stackoverflow.com/questions/105007/do-you-test-private-method) informative. I have decided, that in some classes, I want to have protected methods, but test them. Some of these methods are static and short. Because most of the public methods make use of them, I will probably be able to safely remove the tests later. But for starting with a TDD approach and avoid debugging, I really want to test them. I thought of the following: * [Method Object](http://www.refactoring.com/catalog/replaceMethodWithMethodObject.html) as adviced in [an answer](https://stackoverflow.com/questions/105007/do-you-test-private-method#105021) seems to be overkill for this. * Start with public methods and when code coverage is given by higher level tests, turn them protected and remove the tests. * Inherit a class with a testable interface making protected methods public Which is best practice? Is there anything else? It seems, that JUnit automatically changes protected methods to be public, but I did not have a deeper look at it. PHP does not allow this via [reflection](http://php.net/language.oop5.reflection).
If you're using PHP5 (>= 5.3.2) with PHPUnit, you can test your private and protected methods by using reflection to set them to be public prior to running your tests: ``` protected static function getMethod($name) { $class = new ReflectionClass('MyClass'); $method = $class->getMethod($name); $method->setAccessible(true); return $method; } public function testFoo() { $foo = self::getMethod('foo'); $obj = new MyClass(); $foo->invokeArgs($obj, array(...)); ... } ```
249,667
<p>Say you get a recordset like the following:</p> <pre><code>| ID | Foo | Bar | Red | |-----|------|------|------| | 1 | 100 | NULL | NULL | | 1 | NULL | 200 | NULL | | 1 | NULL | NULL | 300 | | 2 | 400 | NULL | NULL | | ... | ... | ... | ... | -- etc. </code></pre> <p>And you want:</p> <pre><code>| ID | Foo | Bar | Red | |-----|-----|-----|-----| | 1 | 100 | 200 | 300 | | 2 | 400 | ... | ... | | ... | ... | ... | ... | -- etc. </code></pre> <p>You could use something like:</p> <pre><code>SELECT ID, MAX(Foo) AS Foo, MAX(Bar) AS Bar, MAX(Red) AS Red FROM foobarred GROUP BY ID </code></pre> <hr> <p>Now, how might you accomplish similar when Foo, Bar, and Red are VARCHAR?</p> <pre><code>| ID | Foo | Bar | Red | |-----|----------|---------|---------| | 1 | 'Text1' | NULL | NULL | | 1 | NULL | 'Text2' | NULL | | 1 | NULL | NULL | 'Text3' | | 2 | 'Test4' | NULL | NULL | | ... | ... | ... | ... | -- etc. </code></pre> <p>To:</p> <pre><code>| ID | Foo | Bar | Red | |-----|----------|---------|---------| | 1 | 'Text1' | 'Text2' | 'Text3' | | 2 | 'Text4' | ... | ... | | ... | ... | ... | ... | -- etc. </code></pre> <hr> <p>Currently working primarily with SQL Server 2000; but have access to 2005 servers.</p>
[ { "answer_id": 249717, "author": "Timothy Khouri", "author_id": 11917, "author_profile": "https://Stackoverflow.com/users/11917", "pm_score": 1, "selected": false, "text": "<p>The query you had above works just fine for VARCHAR fields as it did for INT fields. The problem with your query though is that if you have two rows with the same ID, and both of those rows had something in the \"Foo\" column, then only the one with the highest value (both for INT and VARCHAR) will be displayed.</p>\n" }, { "answer_id": 249719, "author": "Eoin Campbell", "author_id": 30155, "author_profile": "https://Stackoverflow.com/users/30155", "pm_score": 1, "selected": true, "text": "<p>I don't have access to a SQL2K box at the minute but select max(column) will work on nvarchars in 2005. The only problem will be if you have multiple text values under each column for each id in your original table...</p>\n\n<pre><code>CREATE TABLE Flatten (\n id int not null,\n foo Nvarchar(10) null,\n bar Nvarchar(10) null,\n red Nvarchar(10) null)\n\nINSERT INTO Flatten (ID, foo, bar, red) VALUES (1, 'Text1', null, null)\nINSERT INTO Flatten (ID, foo, bar, red) VALUES (1, null, 'Text2', null)\nINSERT INTO Flatten (ID, foo, bar, red) VALUES (1, null, null, 'Text3')\nINSERT INTO Flatten (ID, foo, bar, red) VALUES (2, 'Text4', null, null)\n\n\n\nSELECT \n ID, \n max(foo),\n max(bar),\n max(red)\nFROM\nFlatten\nGROUP BY ID\n</code></pre>\n\n<p>returns </p>\n\n<pre><code>ID Foo Bar Red\n----------- ---------- ---------- ----------\n1 Text1 Text2 Text3\n2 Text4 NULL NULL\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15031/" ]
Say you get a recordset like the following: ``` | ID | Foo | Bar | Red | |-----|------|------|------| | 1 | 100 | NULL | NULL | | 1 | NULL | 200 | NULL | | 1 | NULL | NULL | 300 | | 2 | 400 | NULL | NULL | | ... | ... | ... | ... | -- etc. ``` And you want: ``` | ID | Foo | Bar | Red | |-----|-----|-----|-----| | 1 | 100 | 200 | 300 | | 2 | 400 | ... | ... | | ... | ... | ... | ... | -- etc. ``` You could use something like: ``` SELECT ID, MAX(Foo) AS Foo, MAX(Bar) AS Bar, MAX(Red) AS Red FROM foobarred GROUP BY ID ``` --- Now, how might you accomplish similar when Foo, Bar, and Red are VARCHAR? ``` | ID | Foo | Bar | Red | |-----|----------|---------|---------| | 1 | 'Text1' | NULL | NULL | | 1 | NULL | 'Text2' | NULL | | 1 | NULL | NULL | 'Text3' | | 2 | 'Test4' | NULL | NULL | | ... | ... | ... | ... | -- etc. ``` To: ``` | ID | Foo | Bar | Red | |-----|----------|---------|---------| | 1 | 'Text1' | 'Text2' | 'Text3' | | 2 | 'Text4' | ... | ... | | ... | ... | ... | ... | -- etc. ``` --- Currently working primarily with SQL Server 2000; but have access to 2005 servers.
I don't have access to a SQL2K box at the minute but select max(column) will work on nvarchars in 2005. The only problem will be if you have multiple text values under each column for each id in your original table... ``` CREATE TABLE Flatten ( id int not null, foo Nvarchar(10) null, bar Nvarchar(10) null, red Nvarchar(10) null) INSERT INTO Flatten (ID, foo, bar, red) VALUES (1, 'Text1', null, null) INSERT INTO Flatten (ID, foo, bar, red) VALUES (1, null, 'Text2', null) INSERT INTO Flatten (ID, foo, bar, red) VALUES (1, null, null, 'Text3') INSERT INTO Flatten (ID, foo, bar, red) VALUES (2, 'Text4', null, null) SELECT ID, max(foo), max(bar), max(red) FROM Flatten GROUP BY ID ``` returns ``` ID Foo Bar Red ----------- ---------- ---------- ---------- 1 Text1 Text2 Text3 2 Text4 NULL NULL ```
249,671
<p>I have created the following style for a listbox that will have an image displayed next to some text:</p> <pre><code>&lt;Style x:Key="ImageListBoxStyle" TargetType="{x:Type ListBox}"&gt; &lt;Setter Property="SnapsToDevicePixels" Value="true"/&gt; &lt;Setter Property="BorderThickness" Value="1"/&gt; &lt;Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Auto"/&gt; &lt;Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Auto"/&gt; &lt;Setter Property="ScrollViewer.CanContentScroll" Value="True"/&gt; &lt;Setter Property="ItemContainerStyle"&gt; &lt;Setter.Value&gt; &lt;!-- Simple ListBoxItem - This is used for each Item in a ListBox. The item's content is placed in the ContentPresenter --&gt; &lt;Style TargetType="{x:Type ListBoxItem}"&gt; &lt;Setter Property="SnapsToDevicePixels" Value="true"/&gt; &lt;Setter Property="OverridesDefaultStyle" Value="true"/&gt; &lt;Setter Property="VerticalContentAlignment" Value="Center"/&gt; &lt;Setter Property="Template"&gt; &lt;Setter.Value&gt; &lt;ControlTemplate TargetType="{x:Type ListBoxItem}"&gt; &lt;Grid SnapsToDevicePixels="true"&gt; &lt;Border x:Name="Border"&gt; &lt;Grid Height="40"&gt; &lt;Grid.ColumnDefinitions&gt; &lt;ColumnDefinition Width="Auto"/&gt; &lt;ColumnDefinition Width="*"/&gt; &lt;/Grid.ColumnDefinitions&gt; &lt;Image x:Name="DisplayImage" Source="{Binding Path=ThumbnailImage}" Height="30" Width="30" Grid.Column="0"/&gt; &lt;ContentPresenter x:Name="DisplayText" HorizontalAlignment="Stretch" VerticalAlignment="Center" Grid.Column="1"/&gt; &lt;!--&lt;ContentPresenter.Resources&gt; &lt;Style TargetType="{x:Type TextBlock}"&gt; &lt;Setter Property="Foreground" Value="Black"/&gt; &lt;/Style&gt; &lt;/ContentPresenter.Resources&gt;--&gt; &lt;!--Content="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=ListBox}, Path=DisplayMemberPath, Converter={StaticResource myDisplayMemberConverter}}"--&gt; &lt;!--&lt;Label x:Name="Text" Content="{Binding Path=FullNameAndTitle}" Foreground="Black" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" VerticalContentAlignment="Center" HorizontalAlignment="Stretch" Grid.Column="1" Height="40"/&gt;--&gt; &lt;/Grid&gt; &lt;/Border&gt; &lt;/Grid&gt; &lt;ControlTemplate.Triggers&gt; &lt;Trigger Property="IsSelected" Value="true"&gt; &lt;!--&lt;Setter Property="FontWeight" Value="Bold" TargetName="DisplayText"/&gt;--&gt; &lt;!--&lt;Setter Property="Style" Value="{StaticResource SelectedTextStyle}" TargetName="DisplayText"/&gt;--&gt; &lt;Setter Property="Background" Value="DarkBlue" TargetName="Border"/&gt; &lt;Setter Property="Width" Value="40" TargetName="DisplayImage"/&gt; &lt;Setter Property="Height" Value="40" TargetName="DisplayImage"/&gt; &lt;/Trigger&gt; &lt;/ControlTemplate.Triggers&gt; &lt;/ControlTemplate&gt; &lt;/Setter.Value&gt; &lt;/Setter&gt; &lt;/Style&gt; &lt;/Setter.Value&gt; &lt;/Setter&gt; &lt;Setter Property="Template"&gt; &lt;Setter.Value&gt; &lt;ControlTemplate TargetType="{x:Type ListBox}"&gt; &lt;Grid&gt; &lt;Border x:Name="Border" Background="{TemplateBinding Background}" BorderBrush="Black" BorderThickness="{TemplateBinding BorderThickness}"&gt; &lt;Grid&gt; &lt;ScrollViewer Margin="1,1,1,1" Focusable="false" Background="{TemplateBinding Background}" SnapsToDevicePixels="True"&gt; &lt;StackPanel IsItemsHost="true"/&gt; &lt;/ScrollViewer&gt; &lt;/Grid&gt; &lt;/Border&gt; &lt;/Grid&gt; &lt;ControlTemplate.Triggers&gt; &lt;Trigger Property="IsGrouping" Value="true"&gt; &lt;Setter Property="ScrollViewer.CanContentScroll" Value="false"/&gt; &lt;/Trigger&gt; &lt;/ControlTemplate.Triggers&gt; &lt;/ControlTemplate&gt; &lt;/Setter.Value&gt; &lt;/Setter&gt; &lt;/Style&gt; </code></pre> <p>I have to use the contentpresenter as I am filtering what is displayed (text wise) using the DisplayMemberPath of the ListBox itself.</p> <p>All I want to do is set the FontWeight to Bold and the Foreground to White when an item is selected in the ListBox.</p> <p>Has anyone encountered a problem like this? I have looked at some related questions but people have been able to use a TextBlock to get around their issues I can't unfortunately.</p> <p>Any info ppl can give will be appreciated.</p> <p>Cheers</p>
[ { "answer_id": 258612, "author": "Bijington", "author_id": 32348, "author_profile": "https://Stackoverflow.com/users/32348", "pm_score": 5, "selected": false, "text": "<p>It's all ok, I have managed to answer this question myself, I was trying to modify the foreground/fontweight of the contentpresenter which doesn't contain a definition for foreground/fontweight all i simply needed to do was this:</p>\n\n<pre><code>&lt;Setter Property=\"FontWeight\" Value=\"Bold\"/&gt;\n&lt;Setter Property=\"Foreground\" Value=\"White\"/&gt;\n</code></pre>\n\n<p>i.e. remove the:</p>\n\n<pre><code>TargetName=\"DisplayText\"\n</code></pre>\n" }, { "answer_id": 8247884, "author": "BrightShadow", "author_id": 1062610, "author_profile": "https://Stackoverflow.com/users/1062610", "pm_score": 7, "selected": true, "text": "<p>There is also another way. You can add in your <code>ContentPresenter</code> this attribute</p>\n\n<pre><code>TextBlock.Foreground=\"YourColour\"\n</code></pre>\n\n<p>In this case you can also use animations over that property.</p>\n" }, { "answer_id": 8288929, "author": "Factor Mystic", "author_id": 1569, "author_profile": "https://Stackoverflow.com/users/1569", "pm_score": 4, "selected": false, "text": "<p>Based on <a href=\"https://stackoverflow.com/questions/401600/how-do-i-change-the-fontfamily-on-a-contentpresenter\">this related answer</a>, I was able to solve a similar issue with the following:</p>\n\n<pre><code>&lt;Setter TargetName=\"ctContentPresenter\" Property=\"TextBlock.Foreground\" Value=\"{StaticResource StyleForeColorBrush}\" /&gt;\n</code></pre>\n" }, { "answer_id": 22372284, "author": "Anatoly Ruchka", "author_id": 880709, "author_profile": "https://Stackoverflow.com/users/880709", "pm_score": 2, "selected": false, "text": "<pre><code> &lt;Storyboard x:Key=\"Storyboard1\"&gt; \n &lt;ColorAnimationUsingKeyFrames Storyboard.TargetProperty=\"(TextBlock.Foreground).(SolidColorBrush.Color)\" Storyboard.TargetName=\"myContentPresenter\"&gt;\n &lt;EasingColorKeyFrame KeyTime=\"0\" Value=\"Black\"/&gt;\n &lt;EasingColorKeyFrame KeyTime=\"0:0:0.2\" Value=\"White\"/&gt;\n &lt;/ColorAnimationUsingKeyFrames&gt; \n &lt;/Storyboard&gt;\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249671", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32348/" ]
I have created the following style for a listbox that will have an image displayed next to some text: ``` <Style x:Key="ImageListBoxStyle" TargetType="{x:Type ListBox}"> <Setter Property="SnapsToDevicePixels" Value="true"/> <Setter Property="BorderThickness" Value="1"/> <Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Auto"/> <Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Auto"/> <Setter Property="ScrollViewer.CanContentScroll" Value="True"/> <Setter Property="ItemContainerStyle"> <Setter.Value> <!-- Simple ListBoxItem - This is used for each Item in a ListBox. The item's content is placed in the ContentPresenter --> <Style TargetType="{x:Type ListBoxItem}"> <Setter Property="SnapsToDevicePixels" Value="true"/> <Setter Property="OverridesDefaultStyle" Value="true"/> <Setter Property="VerticalContentAlignment" Value="Center"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type ListBoxItem}"> <Grid SnapsToDevicePixels="true"> <Border x:Name="Border"> <Grid Height="40"> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto"/> <ColumnDefinition Width="*"/> </Grid.ColumnDefinitions> <Image x:Name="DisplayImage" Source="{Binding Path=ThumbnailImage}" Height="30" Width="30" Grid.Column="0"/> <ContentPresenter x:Name="DisplayText" HorizontalAlignment="Stretch" VerticalAlignment="Center" Grid.Column="1"/> <!--<ContentPresenter.Resources> <Style TargetType="{x:Type TextBlock}"> <Setter Property="Foreground" Value="Black"/> </Style> </ContentPresenter.Resources>--> <!--Content="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=ListBox}, Path=DisplayMemberPath, Converter={StaticResource myDisplayMemberConverter}}"--> <!--<Label x:Name="Text" Content="{Binding Path=FullNameAndTitle}" Foreground="Black" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" VerticalContentAlignment="Center" HorizontalAlignment="Stretch" Grid.Column="1" Height="40"/>--> </Grid> </Border> </Grid> <ControlTemplate.Triggers> <Trigger Property="IsSelected" Value="true"> <!--<Setter Property="FontWeight" Value="Bold" TargetName="DisplayText"/>--> <!--<Setter Property="Style" Value="{StaticResource SelectedTextStyle}" TargetName="DisplayText"/>--> <Setter Property="Background" Value="DarkBlue" TargetName="Border"/> <Setter Property="Width" Value="40" TargetName="DisplayImage"/> <Setter Property="Height" Value="40" TargetName="DisplayImage"/> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> </Setter.Value> </Setter> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type ListBox}"> <Grid> <Border x:Name="Border" Background="{TemplateBinding Background}" BorderBrush="Black" BorderThickness="{TemplateBinding BorderThickness}"> <Grid> <ScrollViewer Margin="1,1,1,1" Focusable="false" Background="{TemplateBinding Background}" SnapsToDevicePixels="True"> <StackPanel IsItemsHost="true"/> </ScrollViewer> </Grid> </Border> </Grid> <ControlTemplate.Triggers> <Trigger Property="IsGrouping" Value="true"> <Setter Property="ScrollViewer.CanContentScroll" Value="false"/> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> ``` I have to use the contentpresenter as I am filtering what is displayed (text wise) using the DisplayMemberPath of the ListBox itself. All I want to do is set the FontWeight to Bold and the Foreground to White when an item is selected in the ListBox. Has anyone encountered a problem like this? I have looked at some related questions but people have been able to use a TextBlock to get around their issues I can't unfortunately. Any info ppl can give will be appreciated. Cheers
There is also another way. You can add in your `ContentPresenter` this attribute ``` TextBlock.Foreground="YourColour" ``` In this case you can also use animations over that property.
249,692
<p>I'm having difficulty parsing some JSON data returned from my server using jQuery.ajax()</p> <p>To perform the AJAX I'm using:</p> <pre><code>$.ajax({ url: myUrl, cache: false, dataType: "json", success: function(data){ ... }, error: function(e, xhr){ ... } }); </code></pre> <p>And if I return an array of items then it works fine:</p> <pre><code>[ { title: "One", key: "1" }, { title: "Two", key: "2" } ] </code></pre> <p>The success function is called and receives the correct object.</p> <p>However, when I'm trying to return a single object:</p> <pre><code>{ title: "One", key: "1" } </code></pre> <p>The error function is called and xhr contains 'parsererror'. I've tried wrapping the JSON in parenthesis on the server before sending it down the wire, but it makes no difference. Yet if I paste the content into a string in Javascript and then use the eval() function, it evaluates it perfectly.</p> <p>Any ideas what I'm doing wrong?</p> <p>Anthony</p>
[ { "answer_id": 249758, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 7, "selected": true, "text": "<p>Is your server sending data as Content-Type <code>\"*/json\"</code>? If not, modify the response headers accordingly. Sending <code>\"application/json\"</code> would be fine, for example.</p>\n" }, { "answer_id": 250245, "author": "Josh", "author_id": 2204759, "author_profile": "https://Stackoverflow.com/users/2204759", "pm_score": 5, "selected": false, "text": "<p>This problem is usually because your request received the wrong mime type. When developing on your own computer, sometimes you are not receiving the proper mime type from the \"server\", which is your own computer. I ran into this problem once when developing by opening the locally stored file in the browser (e.g. the url was \"c:/project/test.html\").</p>\n\n<p>Try using the beforeSend property to add a callback function that overrides the mime type. This will trick the code into dealing with json despite the wrong mime type being sent by the server and received by your calling code. Some example code is below.</p>\n\n<p>The proper mime type is application/json according to <a href=\"https://stackoverflow.com/questions/477816/what-is-the-correct-json-content-type\">this question</a>, but I do know that application/j-son worked when I tried it (now several years ago). You should probably try application/json first.</p>\n\n<pre><code>var jsonMimeType = \"application/json;charset=UTF-8\";\n$.ajax({\n type: \"GET\",\n url: myURL,\n beforeSend: function(x) {\n if(x &amp;&amp; x.overrideMimeType) {\n x.overrideMimeType(jsonMimeType);\n }\n },\n dataType: \"json\",\n success: function(data){\n // do stuff...\n }\n});\n</code></pre>\n" }, { "answer_id": 250309, "author": "David Alpert", "author_id": 8997, "author_profile": "https://Stackoverflow.com/users/8997", "pm_score": 1, "selected": false, "text": "<p>If returning an array works and returning a single object doesn't, you might also try returning your single object as an array containing that single object:</p>\n\n<pre><code>[ { title: \"One\", key: \"1\" } ]\n</code></pre>\n\n<p>that way you are returning a consistent data structure, an array of objects, no matter the data payload.</p>\n\n<p>i see that you've tried wrapping your single object in \"parenthesis\", and suggest this with example because of course JavaScript treats [ .. ] differently than ( .. )</p>\n" }, { "answer_id": 250328, "author": "bobince", "author_id": 18936, "author_profile": "https://Stackoverflow.com/users/18936", "pm_score": 2, "selected": false, "text": "<pre><code>{ title: \"One\", key: \"1\" }\n</code></pre>\n\n<p>Is not what you think. As an expression, it's an Object literal, but as a statement, it's:</p>\n\n<pre><code>{ // new block\n title: // define a label called 'title' for goto statements\n \"One\", // statement: the start of an expression which will be ignored\n key: // ...er, what? you can't have a goto label in the middle of an expression\n // ERROR\n</code></pre>\n\n<p>Unfortunately eval() does not give you a way to specify whether you are giving it a statement or an expression, and it tends to guess wrong.</p>\n\n<p>The usual solution is indeed to wrap <em>anything</em> in parentheses before sending it to the eval() function. You say you've tried that on the server... clearly somehow that isn't getting through. It should be waterproof to say on the client end, whatever is receiving the XMLHttpRequest response:</p>\n\n<pre><code>eval('('+responseText+')');\n</code></pre>\n\n<p>instead of:</p>\n\n<pre><code>eval(responseText);\n</code></pre>\n\n<p>as long as the response is really an expression not a statement. (eg. it doesn't have multiple, semicolon-or-newline-separated clauses.)</p>\n" }, { "answer_id": 251096, "author": "Ben Combee", "author_id": 1323, "author_profile": "https://Stackoverflow.com/users/1323", "pm_score": 6, "selected": false, "text": "<p>According to the <a href=\"http://json.org\" rel=\"noreferrer\">json.org</a> specification, your return is invalid. The names are always quoted, so you should be returning</p>\n\n<pre><code>{ \"title\": \"One\", \"key\": \"1\" }\n</code></pre>\n\n<p>and </p>\n\n<pre><code>[ { \"title\": \"One\", \"key\": \"1\" }, { \"title\": \"Two\", \"key\": \"2\" } ]\n</code></pre>\n\n<p>This may not be the problem with your setup, since you say one of them works now, but it should be fixed for correctness in case you need to switch to another JSON parser in the future.</p>\n" }, { "answer_id": 325072, "author": "Dave Ward", "author_id": 60, "author_profile": "https://Stackoverflow.com/users/60", "pm_score": 1, "selected": false, "text": "<p>If jQuery's error handler is being called and the XHR object contains \"parser error\", that's probably a parser error coming back from the server.</p>\n\n<p>Is your multiple result scenario when you call the service without a parameter, but it's breaking when you try to supply a parameter to retrieve the single record? </p>\n\n<p>What backend are you returning this from? </p>\n\n<p>On ASMX services, for example, that's often the case when parameters are supplied to jQuery as a JSON object instead of a JSON string. If you provide jQuery an actual JSON object for its \"data\" parameter, it will serialize that into standard &amp; delimited k,v pairs instead of sending it as JSON.</p>\n" }, { "answer_id": 327647, "author": "Jay", "author_id": 41690, "author_profile": "https://Stackoverflow.com/users/41690", "pm_score": 1, "selected": false, "text": "<p>I found in some of my implementations I had to add:</p>\n\n<pre><code>obj = new Object; obj = (data.obj);\n</code></pre>\n\n<p>which seemed to solve the problem. Eval or not it seemed to do exactly the same for me.</p>\n" }, { "answer_id": 350890, "author": "Andreas Grech", "author_id": 44084, "author_profile": "https://Stackoverflow.com/users/44084", "pm_score": 2, "selected": false, "text": "<p>If you are consuming ASP.NET Web Services using jQuery, make sure you have the following included in your web.config:</p>\n\n<pre><code>&lt;webServices&gt;\n &lt;protocols&gt;\n &lt;add name=\"HttpGet\"/&gt;\n &lt;add name=\"HttpPost\"/&gt;\n &lt;/protocols&gt;\n&lt;/webServices&gt;\n</code></pre>\n" }, { "answer_id": 2146564, "author": "jonburney", "author_id": 260022, "author_profile": "https://Stackoverflow.com/users/260022", "pm_score": 2, "selected": false, "text": "<p>I had a similar problem to this where Firefox 3.5 worked fine and parsed my JSON data but Firefox 3.0.6 returned a parseerror. Turned out it was a blank space at the start of the JSON that caused Firefox 3.0.6 to throw an error. Removing the blank space fixed it</p>\n" }, { "answer_id": 2519983, "author": "John Mee", "author_id": 75033, "author_profile": "https://Stackoverflow.com/users/75033", "pm_score": 5, "selected": false, "text": "<p>JSON strings are wrapped in <strong>double</strong> quotes; single quotes are not a valid substitute.</p>\n\n<pre><code>{\"who\": \"Hello World\"}\n</code></pre>\n\n<p>is valid but this is not...</p>\n\n<pre><code>{'who': 'Hello World'}\n</code></pre>\n\n<p>Whilst not the OP's issue, thought it worth noting for others who land here.</p>\n" }, { "answer_id": 4465752, "author": "Jubair", "author_id": 354306, "author_profile": "https://Stackoverflow.com/users/354306", "pm_score": 3, "selected": false, "text": "<p>I had this issue and for a bit I used </p>\n\n<pre><code>eval('('+data+')')\n</code></pre>\n\n<p>to get the data returned in an object. but then later had other issues getting a 'missing ) in parenthetical' error and found out that jQuery has a function specifically for evaluating a string for a json structure: </p>\n\n<pre><code>$.parseJSON(data)\n</code></pre>\n\n<p>should do the trick. This is in addition to having your json string in the proper format of course..</p>\n" }, { "answer_id": 4631253, "author": "Jonathon Hill", "author_id": 168815, "author_profile": "https://Stackoverflow.com/users/168815", "pm_score": 1, "selected": false, "text": "<p>jQuery chokes on certain JSON keys. I was sending this JSON snippet in PHP:</p>\n\n<pre><code>echo json_encode((object) array('result' =&gt; 'success'));\n</code></pre>\n\n<p>Renaming the 'result' key to something else works. I would guess this is a reserved word collision of some kind, and could be a bug in jQuery (1.4.2).</p>\n" }, { "answer_id": 5542221, "author": "Dave DuPlantis", "author_id": 8174, "author_profile": "https://Stackoverflow.com/users/8174", "pm_score": 1, "selected": false, "text": "<p>In a ColdFusion environment, one thing that will cause an error, even with well-formed JSON, is having <strong>Enable Request Debugging Output</strong> turned on in the ColdFusion Administrator (under Debugging &amp; Logging > Debug Output Settings). Debugging information will be returned with the JSON data and will thus make it invalid. </p>\n" }, { "answer_id": 5838466, "author": "webwiseguys", "author_id": 731907, "author_profile": "https://Stackoverflow.com/users/731907", "pm_score": 0, "selected": false, "text": "<p>I was struggling with this, and spent a few hours trying to figure this out, until I used firebug to show the data object.</p>\n\n<pre><code>var data = eval(\"(\" + data.responseText + \")\");\nconsole.log(data.count);\n</code></pre>\n" }, { "answer_id": 10044085, "author": "valir", "author_id": 783850, "author_profile": "https://Stackoverflow.com/users/783850", "pm_score": 1, "selected": false, "text": "<p>also try this</p>\n\n<pre><code>$.ajax({\n url: url,\n data:datas,\n success:function(datas, textStatus, jqXHR){\n var returnedData = jQuery.parseJSON(datas.substr(datas.indexOf('{')));\n})};\n</code></pre>\n\n<p>in my case server responds with unknow character before '{'</p>\n" }, { "answer_id": 10627793, "author": "Nezzy", "author_id": 704426, "author_profile": "https://Stackoverflow.com/users/704426", "pm_score": 3, "selected": false, "text": "<p>If you are echoing out the json response and your headers don't match */json then you can use the built in jQuery.parseJSON api to parse the response.</p>\n\n<pre><code>response = '{\"name\":\"John\"}';\nvar obj = jQuery.parseJSON(response);\nalert( obj.name === \"John\" );\n</code></pre>\n" }, { "answer_id": 23247208, "author": "Brent", "author_id": 589577, "author_profile": "https://Stackoverflow.com/users/589577", "pm_score": 1, "selected": false, "text": "<p>I was getting status = parseerror and xhr.status = 200.</p>\n\n<p>The issue for me was the URL's inside the JSON response had '\\' switching to '/' fixed this.</p>\n" }, { "answer_id": 24885407, "author": "user2854865", "author_id": 2854865, "author_profile": "https://Stackoverflow.com/users/2854865", "pm_score": -1, "selected": false, "text": "<p>use</p>\n\n<pre><code>$data = yourarray(); \njson_encode($data)\n</code></pre>\n\n<p>on server side.\nOn client side\nuse ajax with Datatype JSON and be sure your document encoding is not UTF-8 with BOM it has to be UTF-8.</p>\n" }, { "answer_id": 24978063, "author": "user3612872", "author_id": 3612872, "author_profile": "https://Stackoverflow.com/users/3612872", "pm_score": 2, "selected": false, "text": "<p>You will to have to set header content type in your php like this:</p>\n\n<pre><code> &lt;?php\n\n header('Content-type:application/json');\n\n ?&gt;\n</code></pre>\n\n<p>Watch these Video for better understanding.... </p>\n\n<p>Reference: <a href=\"http://www.youtube.com/watch?v=EvFXWqEqh6o\" rel=\"nofollow\">http://www.youtube.com/watch?v=EvFXWqEqh6o</a></p>\n" }, { "answer_id": 40569157, "author": "IAM_AL_X", "author_id": 3552393, "author_profile": "https://Stackoverflow.com/users/3552393", "pm_score": 2, "selected": false, "text": "<p>The techniques \"eval()\" and \"JSON.parse()\" use mutually exclusive formats. </p>\n\n<ul>\n<li>With \"eval()\" parenthesis are <strong>required</strong>.</li>\n<li>With \"JSON.parse()\" parenthesis are <strong>forbidden</strong>.</li>\n</ul>\n\n<p>Beware, there are \"stringify()\" functions that produce \"eval\" format. For ajax, you should use only the JSON format. </p>\n\n<p>While \"eval\" incorporates the entire JavaScript language, JSON uses only a tiny subset of the language. Among the constructs in the JavaScript language that \"eval\" must recognize is the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/block\" rel=\"nofollow noreferrer\">\"Block statement\" (a.k.a. \"compound statement\")</a>; which is a pair or curly braces \"{}\" with some statements inside. But curly braces are also used in the syntax of object literals. The interpretation is differentiated by the context in which the code appears. Something might look like an object literal to you, but \"eval\" will see it as a compound statement. </p>\n\n<p>In the JavaScript language, object literals occur to the right of an assignment.</p>\n\n<pre><code>var myObj = { ...some..code..here... };\n</code></pre>\n\n<p>Object literals don't occur on their own.</p>\n\n<pre><code>{ ...some..code..here... } // this looks like a compound statement\n</code></pre>\n\n<p>Going back to the OP's original question, asked in 2008, he inquired why the following fails in \"eval()\":</p>\n\n<pre><code>{ title: \"One\", key: \"1\" }\n</code></pre>\n\n<p>The answer is that it looks like a compound statement. To convert it into an object, you must put it into a context where a compound statement is impossible. That is done by putting parenthesis around it</p>\n\n<pre><code>( { title: \"One\", key: \"1\" } ) // not a compound statment, so must be object literal\n</code></pre>\n\n<p>The OP also asked why a similar statement <strong>did</strong> successfully eval:</p>\n\n<pre><code>[ { title: \"One\", key: \"1\" }, { title: \"Two\", key: \"2\" } ]\n</code></pre>\n\n<p>The same answer applies -- the curly braces are in a context where a compound statement is impossible. This is an array context, \"<code>[...]</code>\", and arrays can contain objects, but they cannot contain statements.</p>\n\n<p>Unlike \"eval()\", JSON is very limited in its capabilities. The limitation is intentional. The designer of JSON intended a minimalist subset of JavaScript, using only syntax that could appear on the right hand side of an assignment. So if you have some code that correctly parses in JSON...</p>\n\n<pre><code>var myVar = JSON.parse(\"...some...code...here...\");\n</code></pre>\n\n<p>...that implies it will also legally parse on the right hand side of an assignment, like this..</p>\n\n<pre><code>var myVar = ...some..code..here... ;\n</code></pre>\n\n<p>But that is not the only restriction on JSON. The <a href=\"http://www.json.org\" rel=\"nofollow noreferrer\">BNF language specification for JSON</a> is very simple. For example, it does not allow for the use of single quotes to indicate strings (like JavaScript and Perl do) and it does not have a way to express a single character as a byte (like 'C' does). Unfortunately, it also does not allow comments (which would be really nice when creating configuration files). The upside of all those limitations is that parsing JSON is fast and offers no opportunity for code injection (a security threat). </p>\n\n<p>Because of these limitations, JSON has no use for parenthesis. Consequently, a parenthesis in a JSON string is an illegal character.</p>\n\n<p>Always use JSON format with ajax, for the following reasons:</p>\n\n<ul>\n<li>A typical ajax pipeline will be configured for JSON.</li>\n<li>The use of \"eval()\" will be criticised as a security risk.</li>\n</ul>\n\n<p>As an example of an ajax pipeline, consider a program that involves a Node server and a jQuery client. The client program uses a jQuery call having the form <code>$.ajax({dataType:'json',...etc.});</code>. JQuery creates a jqXHR object for later use, then packages and sends the associated request. The server accepts the request, processes it, and then is ready to respond. The server program will call the method <code>res.json(data)</code> to package and send the response. Back at the client side, jQuery accepts the response, consults the associated jqXHR object, and processes the JSON formatted data. This all works without any need for manual data conversion. The response involves no explicit call to JSON.stringify() on the Node server, and no explicit call to JSON.parse() on the client; that's all handled for you.</p>\n\n<p>The use of \"eval\" is associated with code injection security risks. You might think there is no way that can happen, but hackers can get quite creative. Also, \"eval\" is problematic for Javascript optimization.</p>\n\n<p>If you do find yourself using a using a \"stringify()\" function, be aware that some functions with that name will create strings that are compatible with \"eval\" and not with JSON. For example, in Node, the following gives you function that creates strings in \"eval\" compatible format:</p>\n\n<pre><code>var stringify = require('node-stringify'); // generates eval() format\n</code></pre>\n\n<p>This can be useful, but unless you have a specific need, it's probably not what you want.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249692", "https://Stackoverflow.com", "https://Stackoverflow.com/users/366/" ]
I'm having difficulty parsing some JSON data returned from my server using jQuery.ajax() To perform the AJAX I'm using: ``` $.ajax({ url: myUrl, cache: false, dataType: "json", success: function(data){ ... }, error: function(e, xhr){ ... } }); ``` And if I return an array of items then it works fine: ``` [ { title: "One", key: "1" }, { title: "Two", key: "2" } ] ``` The success function is called and receives the correct object. However, when I'm trying to return a single object: ``` { title: "One", key: "1" } ``` The error function is called and xhr contains 'parsererror'. I've tried wrapping the JSON in parenthesis on the server before sending it down the wire, but it makes no difference. Yet if I paste the content into a string in Javascript and then use the eval() function, it evaluates it perfectly. Any ideas what I'm doing wrong? Anthony
Is your server sending data as Content-Type `"*/json"`? If not, modify the response headers accordingly. Sending `"application/json"` would be fine, for example.
249,701
<p>I have a header file x.h which is included by more than one *.c source files. This header file has some structure variables defined.</p> <p>I have put multiple inclusion prevention guard at the beginning of the header file as:</p> <pre><code>#ifndef X_H #define X_H ... .. //header file declarations and definitons. #endif//X_H </code></pre> <p>On building I get linker errors related to multiple definitions. I understand the problem.</p> <ol> <li><p>Won't a multiple inclusion prevention guard at the top of header file as I have, prevent multiple inclusions of the header file x.h and thereby avoid multiple definitions of the variables that are there in x.h?</p></li> <li><p><code>#pragma</code> once does not work on this particular compiler, so what is the solution? Someone had posted <a href="https://stackoverflow.com/questions/223771/repeated-multiple-definition-errors-from-including-same-header-in-multiple-cpps#223798">this</a> answer to a similar question. It doesn't seem to work for me. How does this solution work?</p></li> </ol>
[ { "answer_id": 249707, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 2, "selected": false, "text": "<p>Using a multiple inclusion guard prevents <em>compiler</em> errors, but you're getting a linker error. Do you have data definitions in the header file that don't use <code>extern</code>?</p>\n" }, { "answer_id": 249723, "author": "Pieter", "author_id": 5822, "author_profile": "https://Stackoverflow.com/users/5822", "pm_score": 4, "selected": false, "text": "<p>Using include guards prevents one compilation unit from including the header twice. E.g. if header B.h includes A.h and B.cpp includes A.h and B.h, everything from A.h would be declared twice in the compilation B.cpp if you weren't using include guards.</p>\n\n<p>Your include guards prevent this from happening, all's fine till now.</p>\n\n<p>But you get multiple definitions at link time, i.e. two compilation units define the same thing, this probably means you got a real definition in your header, use extern for all variables, make sure functions are either inline or are defined in the cpp file.</p>\n" }, { "answer_id": 249745, "author": "Roddy", "author_id": 1737, "author_profile": "https://Stackoverflow.com/users/1737", "pm_score": 6, "selected": false, "text": "<p>If the linker is complaining, it means you have definitions rather than just declarations in your header. Here's an example of things that would be wrong.</p>\n\n<pre><code>#ifndef X_H\n#define X_H\n\nint myFunc()\n{\n return 42; // Wrong! definition in header.\n}\n\nint myVar; // Wrong! definition in header.\n\n#endif\n</code></pre>\n\n<p>You should split this into source and header file like this:</p>\n\n<p>Header:</p>\n\n<pre><code>#ifndef X_H\n#define X_H\n\nextern int myFunc();\n\nextern int myVar; \n\n#endif\n</code></pre>\n\n<p>C Source:</p>\n\n<pre><code>int myFunc()\n{\n return 42; \n}\n\nint myVar; \n</code></pre>\n" }, { "answer_id": 3269427, "author": "nclement", "author_id": 306574, "author_profile": "https://Stackoverflow.com/users/306574", "pm_score": 4, "selected": false, "text": "<p>If the functions aren't large, you can use \"inline\" before them and the linker won't complain.</p>\n" }, { "answer_id": 9576187, "author": "perreal", "author_id": 390913, "author_profile": "https://Stackoverflow.com/users/390913", "pm_score": 5, "selected": false, "text": "<p>Header guards are only good for a single compilation unit, i.e., source file. If you happen to include a header file multiple times, perhaps because all headers included from <code>main.c</code> in turn include <code>stdio.h</code> then guards will help.</p>\n\n<p>If you have the definition of a function <code>f</code> in <code>x.h</code> which is included by <code>main.c</code> and <code>util.c</code>, then it is like copying and pasting the definition of <code>f</code> into <code>main.c</code> when creating <code>main.o</code> and doing the same for <code>util.c</code> to create <code>util.o</code>. Then the linker will complain and this happens despite your header guards. Having multiple <code>#include \"x.h\"</code> statements in <code>main.c</code> is possible of course because of these guards.</p>\n" }, { "answer_id": 12531657, "author": "Michael", "author_id": 712014, "author_profile": "https://Stackoverflow.com/users/712014", "pm_score": 0, "selected": false, "text": "<p>Maybe <code>X_H</code> is already defined somewhere else? I just ran into this issue, where Xlib defines <code>X_H</code> in /usr/include/X11/X.h.</p>\n\n<p>To check, you can call <code>gcc -dM -E</code> (if you are using gcc), e.g. in the buildsystem I’m using that works with <code>CC=gcc CFLAGS=\"-dM -E\" make</code>. If the output file contains <code>#define X_H</code> even though you remove it from your file (use <code>Y_H</code> for example), then it is already defined outside your source code.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249701", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2759376/" ]
I have a header file x.h which is included by more than one \*.c source files. This header file has some structure variables defined. I have put multiple inclusion prevention guard at the beginning of the header file as: ``` #ifndef X_H #define X_H ... .. //header file declarations and definitons. #endif//X_H ``` On building I get linker errors related to multiple definitions. I understand the problem. 1. Won't a multiple inclusion prevention guard at the top of header file as I have, prevent multiple inclusions of the header file x.h and thereby avoid multiple definitions of the variables that are there in x.h? 2. `#pragma` once does not work on this particular compiler, so what is the solution? Someone had posted [this](https://stackoverflow.com/questions/223771/repeated-multiple-definition-errors-from-including-same-header-in-multiple-cpps#223798) answer to a similar question. It doesn't seem to work for me. How does this solution work?
If the linker is complaining, it means you have definitions rather than just declarations in your header. Here's an example of things that would be wrong. ``` #ifndef X_H #define X_H int myFunc() { return 42; // Wrong! definition in header. } int myVar; // Wrong! definition in header. #endif ``` You should split this into source and header file like this: Header: ``` #ifndef X_H #define X_H extern int myFunc(); extern int myVar; #endif ``` C Source: ``` int myFunc() { return 42; } int myVar; ```
249,703
<p>I have some scripts that ought to have stopped running but hang around forever. Is there some way I can figure out what they're writing to STDOUT and STDERR in a readable way?</p> <p>I tried, for example, to do:</p> <pre><code>$ tail -f /proc/(pid)/fd/1 </code></pre> <p>but that doesn't really work. It was a long shot anyway.</p> <p>Any other ideas? </p> <p><code>strace</code> on its own is quite verbose and unreadable for seeing this.</p> <p>Note: I am <em>only</em> interested in their output, not in anything else. I'm capable of figuring out the other things on my own; this question is only focused on getting access to stdout and stderr of the running process <em>after</em> starting it.</p>
[ { "answer_id": 249725, "author": "Jauco", "author_id": 6874, "author_profile": "https://Stackoverflow.com/users/6874", "pm_score": 4, "selected": true, "text": "<p>I'm not sure if it will work for you, but I read a page a while back describing a <a href=\"http://etbe.coker.com.au/2008/02/27/redirecting-output-from-a-running-process/\" rel=\"noreferrer\">method that uses gdb</a> </p>\n" }, { "answer_id": 249752, "author": "janm", "author_id": 7256, "author_profile": "https://Stackoverflow.com/users/7256", "pm_score": 1, "selected": false, "text": "<p>You don't state your operating system, but I'm going to take a stab and say \"Linux\".</p>\n\n<p>Seeing what is being written to stderr and stdout is probably not going to help. If it is useful, you could use tee(1) before you start the script to take a copy of stderr and stdout.</p>\n\n<p>You can use ps(1) to look for wchan. This tells you what the process is waiting for. If you look at the strace output, you can ignore the bulk of the output and identify the last (blocked) system call. If it is an operation on a file handle, you can go backwards in the output and identify the underlying object (file, socket, pipe, etc.) From there the answer is likely to be clear.</p>\n\n<p>You can also send the process a signal that causes it to dump core, and then use the debugger and the core file to get a stack trace.</p>\n" }, { "answer_id": 249932, "author": "Thomas Vander Stichele", "author_id": 2900, "author_profile": "https://Stackoverflow.com/users/2900", "pm_score": 6, "selected": false, "text": "<p>Since I'm not allowed to edit Jauco's answer, I'll give the full answer that worked for me (Russell's page relies on un-guaranteed behaviour that, if you close file descriptor 1 for STDOUT, the next <code>creat</code> call will open FD 1.</p>\n\n<p>So, run a simple endless script like this:</p>\n\n<pre><code>import time\n\nwhile True:\n print 'test'\n time.sleep(1)\n</code></pre>\n\n<p>Save it to test.py, run with</p>\n\n<pre><code>$ python test.py\n</code></pre>\n\n<p>Get the PID:</p>\n\n<pre><code>$ ps auxw | grep test.py\n</code></pre>\n\n<p>Now, attach <code>gdb</code>:</p>\n\n<pre><code>$ gdb -p (pid)\n</code></pre>\n\n<p>and do the <code>fd</code> magic:</p>\n\n<pre><code>(gdb) call creat(\"/tmp/stdout\", 0600)\n$1 = 3\n(gdb) call dup2(3, 1)\n$2 = 1\n</code></pre>\n\n<p>Now you can <code>tail /tmp/stdout</code> and see the output that used to go to STDOUT.</p>\n" }, { "answer_id": 251429, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>GDB method seems better, but you can do this with <code>strace</code>, too:</p>\n\n<pre><code>$ strace -p &lt;PID&gt; -e write=1 -s 1024 -o file\n</code></pre>\n\n<p>Via the man page for <code>strace</code>:</p>\n\n<pre><code> -e write=set\n Perform a full hexadecimal and ASCII dump of all the\n data written to file descriptors listed in the spec-\n ified set. For example, to see all output activity\n on file descriptors 3 and 5 use -e write=3,5. Note\n that this is independent from the normal tracing of\n the write(2) system call which is controlled by the\n option -e trace=write.\n</code></pre>\n\n<p>This prints out somewhat more than you need (the hexadecimal part), but you can <code>sed</code> that out easily.</p>\n" }, { "answer_id": 8685132, "author": "Jeff Ward", "author_id": 1026023, "author_profile": "https://Stackoverflow.com/users/1026023", "pm_score": 2, "selected": false, "text": "<p><code>strace</code> outputs a lot less with just <code>-ewrite</code> (and not the <code>=1</code> suffix). And it's a bit simpler than the GDB method, IMO.</p>\n\n<p>I used it to see the progress of an existing MythTV encoding job (<code>sudo</code> because I don't own the encoding process):</p>\n\n<pre><code>$ ps -aef | grep -i handbrake\nmythtv 25089 25085 99 16:01 ? 00:53:43 /usr/bin/HandBrakeCLI -i /var/lib/mythtv/recordings/1061_20111230122900.mpg -o /var/lib/mythtv/recordings/1061_20111230122900.mp4 -e x264 -b 1500 -E faac -B 256 -R 48 -w 720\njward 25293 20229 0 16:30 pts/1 00:00:00 grep --color=auto -i handbr\n\n$ sudo strace -ewrite -p 25089\nProcess 25089 attached - interrupt to quit\nwrite(1, \"\\rEncoding: task 1 of 1, 70.75 % \"..., 73) = 73\nwrite(1, \"\\rEncoding: task 1 of 1, 70.76 % \"..., 73) = 73\nwrite(1, \"\\rEncoding: task 1 of 1, 70.77 % \"..., 73) = 73\nwrite(1, \"\\rEncoding: task 1 of 1, 70.78 % \"..., 73) = 73^C\n</code></pre>\n" }, { "answer_id": 11892574, "author": "Lari Hotari", "author_id": 166062, "author_profile": "https://Stackoverflow.com/users/166062", "pm_score": 3, "selected": false, "text": "<p>I used strace and de-coded the hex output to clear text: </p>\n\n<pre><code>PID=some_process_id\nsudo strace -f -e trace=write -e verbose=none -e write=1,2 -q -p $PID -o \"| grep '^ |' | cut -c11-60 | sed -e 's/ //g' | xxd -r -p\"\n</code></pre>\n\n<p>I combined this command from other answers.</p>\n" }, { "answer_id": 12361415, "author": "Mark Renouf", "author_id": 758, "author_profile": "https://Stackoverflow.com/users/758", "pm_score": 3, "selected": false, "text": "<p>There's several new utilities that wrap up the \"gdb method\" and add some extra touches. The one I use now is called \"reptyr\" (\"Re-PTY-er\"). In addition to grabbing STDERR/STDOUT, it will actually change the controlling terminal of a process (even if it wasn't previously attached to a terminal).</p>\n\n<p>The best use of this is to start up a screen session, and use it to reattach a running process to the terminal within screen so you can safely detach from it and come back later.</p>\n\n<p>It's packaged on popular distros (Ex: 'apt-get install reptyr').</p>\n\n<p><a href=\"http://onethingwell.org/post/2924103615/reptyr\" rel=\"noreferrer\">http://onethingwell.org/post/2924103615/reptyr</a></p>\n" }, { "answer_id": 26363348, "author": "Jérôme Pouiller", "author_id": 301717, "author_profile": "https://Stackoverflow.com/users/301717", "pm_score": 2, "selected": false, "text": "<p>You can use reredirect (<a href=\"https://github.com/jerome-pouiller/reredirect/\" rel=\"nofollow\">https://github.com/jerome-pouiller/reredirect/</a>). </p>\n\n<p>Type</p>\n\n<pre><code>reredirect -m FILE PID\n</code></pre>\n\n<p>and outputs (standard and error) will be written in FILE.</p>\n\n<p>reredirect <code>README</code> also explains how to restore original state of process, how to redirect to another command or to redirect only stdout or stderr.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2900/" ]
I have some scripts that ought to have stopped running but hang around forever. Is there some way I can figure out what they're writing to STDOUT and STDERR in a readable way? I tried, for example, to do: ``` $ tail -f /proc/(pid)/fd/1 ``` but that doesn't really work. It was a long shot anyway. Any other ideas? `strace` on its own is quite verbose and unreadable for seeing this. Note: I am *only* interested in their output, not in anything else. I'm capable of figuring out the other things on my own; this question is only focused on getting access to stdout and stderr of the running process *after* starting it.
I'm not sure if it will work for you, but I read a page a while back describing a [method that uses gdb](http://etbe.coker.com.au/2008/02/27/redirecting-output-from-a-running-process/)
249,704
<p>Has anyone tested sorting with Selenium? I'd like to verify that sorting a table in different ways work (a-z, z-a, state, date, etc.). Any help would be very much appreciated.</p> <p>/Göran</p>
[ { "answer_id": 296686, "author": "krosenvold", "author_id": 23691, "author_profile": "https://Stackoverflow.com/users/23691", "pm_score": 0, "selected": false, "text": "<p>You can get value of fields like this:</p>\n\n<pre><code> //div[@id='sortResult']/div[1]/div (this'd be row 1 of the search result)\n //div[@id='sortResult']/div[2]/div ( row 2)\n</code></pre>\n\n<p>(I'm making some assumptions about the HTML structure here, but you get my drift...)</p>\n\n<p>These can be quite fragile assertions, I'd recommend you anchor these xpath references to an outer container element (not the root of your document, as lots of \"automatic\" tools do).</p>\n\n<p>When you click sort, the value changes. You'll have to find out what the values are supposed to be.</p>\n\n<p>Also watch out for browser compatibility with such xpaths. They're not always ;)</p>\n" }, { "answer_id": 798338, "author": "Peter Bernier", "author_id": 6112, "author_profile": "https://Stackoverflow.com/users/6112", "pm_score": 0, "selected": false, "text": "<p>The way I approached this was to define the expected sorted results as an array and then iterate over the results returned from the sorted page to make sure they met my expectations. </p>\n\n<p>It's a little slow, but it does work. (We actually managed to find a few low-level sorting defects on multiple pages this way..)</p>\n" }, { "answer_id": 1964222, "author": "Dave Hunt", "author_id": 154975, "author_profile": "https://Stackoverflow.com/users/154975", "pm_score": 0, "selected": false, "text": "<p>You could use the WebDriver API from Selenium 2.0 (currently in alpha) to return an array of elements with the <code>findElements</code> command before and after the sort. This becomes a bit more difficult however if what you're sorting is paginated.</p>\n" }, { "answer_id": 4176425, "author": "Mahesh", "author_id": 507201, "author_profile": "https://Stackoverflow.com/users/507201", "pm_score": 1, "selected": false, "text": "<p>I have shared a strategy to test sorting feature of an application on my <a href=\"http://functionaltestautomation.blogspot.com/2010/11/testing-sorting-feature-of-application.html\" rel=\"nofollow\">blog</a>. You can use this to automate test cases that verify the sorting feature of an application. You could use it on place like the search result page, item listing and report module of the application. The strategy explained does not require creation of test data and is fully scalable. </p>\n" }, { "answer_id": 11112854, "author": "Ranadheer Reddy", "author_id": 1215594, "author_profile": "https://Stackoverflow.com/users/1215594", "pm_score": 2, "selected": false, "text": "<p>Before checking it with <strong>selenium</strong>, You have to do small thing. Store the table values(which comes after sorting) in a <code>string</code> or <code>array</code>. </p>\n\n<p>Now perform the sorting using selenium and capture the new list as</p>\n\n<pre><code>string new_list= selenium.gettable(\"xpath\");\n</code></pre>\n\n<p>Now compare both the values and check whether they are same or not. </p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249704", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Has anyone tested sorting with Selenium? I'd like to verify that sorting a table in different ways work (a-z, z-a, state, date, etc.). Any help would be very much appreciated. /Göran
Before checking it with **selenium**, You have to do small thing. Store the table values(which comes after sorting) in a `string` or `array`. Now perform the sorting using selenium and capture the new list as ``` string new_list= selenium.gettable("xpath"); ``` Now compare both the values and check whether they are same or not.
249,709
<p>How can i, in a bash script, execute a command when the user stops the script (with ctrl - c)?</p> <p>Currently, i have this:</p> <pre><code>afplay file.mp3 while true: do osascript -e "set volume 10" end </code></pre> <p>But i would like it to execute <code>killall afplay</code> when the user is finished with it, regardless if it is command-c or another keypress.</p>
[ { "answer_id": 249733, "author": "Vebjorn Ljosa", "author_id": 17498, "author_profile": "https://Stackoverflow.com/users/17498", "pm_score": 4, "selected": true, "text": "<p><code>trap 'killall afplay' EXIT</code></p>\n" }, { "answer_id": 249736, "author": "CesarB", "author_id": 28258, "author_profile": "https://Stackoverflow.com/users/28258", "pm_score": 2, "selected": false, "text": "<p>Use <code>trap</code>.</p>\n\n<pre><code>trap \"kill $pid\" INT TERM EXIT\n</code></pre>\n\n<p>Also avoid <code>killall</code> or <code>pkill</code>, since it could kill unrelated processes (for instance, from another instance of your script, or even a different script). Instead, put the player's PID in a variable and kill only that PID.</p>\n" }, { "answer_id": 249741, "author": "Alnitak", "author_id": 6782, "author_profile": "https://Stackoverflow.com/users/6782", "pm_score": 2, "selected": false, "text": "<p>You need to put a <code>trap</code> statement in your bash script:</p>\n\n<pre><code>trap 'killall afplay' EXIT\n</code></pre>\n\n<p>Note however that this won't work if the bash process is sent a <code>KILL</code> signal (9) as it's not possible for processes to intercept that signal.</p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249709", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2592/" ]
How can i, in a bash script, execute a command when the user stops the script (with ctrl - c)? Currently, i have this: ``` afplay file.mp3 while true: do osascript -e "set volume 10" end ``` But i would like it to execute `killall afplay` when the user is finished with it, regardless if it is command-c or another keypress.
`trap 'killall afplay' EXIT`
249,721
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/249760/how-to-convert-unix-timestamp-to-datetime-and-vice-versa">How to convert UNIX timestamp to DateTime and vice versa?</a> </p> </blockquote> <p>I've got the following class:</p> <pre><code>[DataContractAttribute] public class TestClass { [DataMemberAttribute] public DateTime MyDateTime { get; set; } } </code></pre> <p>Here's the JSON:</p> <pre><code>{ "MyDateTime":"1221818565" } </code></pre> <p>The JSON is being returned from a PHP webservice.</p> <p>What I need to do, is convert that epoch string into a valid C# DateTime. What's the best way of doing this?</p> <p>I can do this:</p> <pre><code>[IgnoreDataMemberAttribute] public DateTime MyDateTime { get; set; } [DataMemberAttribute(Name = "MyDateTime")] public Int32 MyDateTimeTicks { get { return this.MyDateTime.Convert(...); } set { this.Created = new DateTime(...); } } </code></pre> <p>But the trouble with this is, the MyDateTimeTicks is public (changing it to private causes an exception in the serialization process)</p>
[ { "answer_id": 251804, "author": "Dan Esparza", "author_id": 19020, "author_profile": "https://Stackoverflow.com/users/19020", "pm_score": 2, "selected": false, "text": "<p>Here's what I've come up with. In C#, it looks like you need to create a new DateTime and add the epoch value as 'seconds' to this DateTime. Here's what it looks like in code:</p>\n\n<pre><code>new System.DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds(1221818565);\n</code></pre>\n\n<p>When using the Visual Studio immediate window, I printed the result of this operation to the debugger console:</p>\n\n<pre><code>{9/19/2008 10:02:45 AM}\n Date: {9/19/2008 12:00:00 AM}\n Day: 19\n DayOfWeek: Friday\n DayOfYear: 263\n Hour: 10\n Kind: Unspecified\n Millisecond: 0\n Minute: 2\n Month: 9\n Second: 45\n Ticks: 633574153650000000\n TimeOfDay: {10:02:45}\n Year: 2008\n</code></pre>\n" }, { "answer_id": 251845, "author": "ageektrapped", "author_id": 631, "author_profile": "https://Stackoverflow.com/users/631", "pm_score": 1, "selected": false, "text": "<p>What you want is the following:</p>\n\n<pre><code>DateTime unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);\nDateTime dotnetTime = unixEpoch.AddSeconds(Convert.ToDouble(ticks));\n</code></pre>\n\n<p>where <code>ticks</code> is the value passed to you by PHP.</p>\n" }, { "answer_id": 252301, "author": "TheSoftwareJedi", "author_id": 18941, "author_profile": "https://Stackoverflow.com/users/18941", "pm_score": 5, "selected": true, "text": "<p>Finishing what you posted, AND making it private seemed to work fine for me.</p>\n\n<pre><code>[DataContract]\npublic class TestClass\n{\n\n private static readonly DateTime unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);\n\n [IgnoreDataMember]\n public DateTime MyDateTime { get; set; }\n\n [DataMember(Name = \"MyDateTime\")]\n private int MyDateTimeTicks\n {\n get { return (int)(this.MyDateTime - unixEpoch).TotalSeconds; }\n set { this.MyDateTime = unixEpoch.AddSeconds(Convert.ToInt32(value)); }\n }\n\n}\n</code></pre>\n" }, { "answer_id": 5023900, "author": "Jeremy", "author_id": 267411, "author_profile": "https://Stackoverflow.com/users/267411", "pm_score": 2, "selected": false, "text": "<p>I know your question was for PHP, but I just wanted to note a \"gotcha\" for .NET JSON: it appears that .NET gives you the date in \"milliseconds since epoch\" (as opposed to seconds). In this case, the AddSeconds line should be:\n<code>unixEpoch.AddMilliseconds(Int64.Parse(date));</code></p>\n\n<p>More info: <a href=\"http://blogs.msdn.com/b/marcelolr/archive/2008/03/05/system-datetime-ticks-vs-json-date.aspx\" rel=\"nofollow\">http://blogs.msdn.com/b/marcelolr/archive/2008/03/05/system-datetime-ticks-vs-json-date.aspx</a></p>\n" }, { "answer_id": 11887882, "author": "yossi", "author_id": 1588164, "author_profile": "https://Stackoverflow.com/users/1588164", "pm_score": 3, "selected": false, "text": "<pre><code>private DateTime ConvertJsonStringToDateTime(string jsonTime)\n {\n if (!string.IsNullOrEmpty(jsonTime) &amp;&amp; jsonTime.IndexOf(\"Date\") &gt; -1)\n {\n string milis = jsonTime.Substring(jsonTime.IndexOf(\"(\") + 1);\n string sign = milis.IndexOf(\"+\") &gt; -1 ? \"+\" : \"-\";\n string hours = milis.Substring(milis.IndexOf(sign));\n milis = milis.Substring(0, milis.IndexOf(sign));\n hours = hours.Substring(0, hours.IndexOf(\")\"));\n return new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(Convert.ToInt64(milis)).AddHours(Convert.ToInt64(hours) / 100); \n }\n\n return DateTime.Now;\n }\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249721", "https://Stackoverflow.com", "https://Stackoverflow.com/users/986/" ]
> > **Possible Duplicate:** > > [How to convert UNIX timestamp to DateTime and vice versa?](https://stackoverflow.com/questions/249760/how-to-convert-unix-timestamp-to-datetime-and-vice-versa) > > > I've got the following class: ``` [DataContractAttribute] public class TestClass { [DataMemberAttribute] public DateTime MyDateTime { get; set; } } ``` Here's the JSON: ``` { "MyDateTime":"1221818565" } ``` The JSON is being returned from a PHP webservice. What I need to do, is convert that epoch string into a valid C# DateTime. What's the best way of doing this? I can do this: ``` [IgnoreDataMemberAttribute] public DateTime MyDateTime { get; set; } [DataMemberAttribute(Name = "MyDateTime")] public Int32 MyDateTimeTicks { get { return this.MyDateTime.Convert(...); } set { this.Created = new DateTime(...); } } ``` But the trouble with this is, the MyDateTimeTicks is public (changing it to private causes an exception in the serialization process)
Finishing what you posted, AND making it private seemed to work fine for me. ``` [DataContract] public class TestClass { private static readonly DateTime unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); [IgnoreDataMember] public DateTime MyDateTime { get; set; } [DataMember(Name = "MyDateTime")] private int MyDateTimeTicks { get { return (int)(this.MyDateTime - unixEpoch).TotalSeconds; } set { this.MyDateTime = unixEpoch.AddSeconds(Convert.ToInt32(value)); } } } ```
249,729
<p>I am writing a Jython script to sort a list of URLs.</p> <p>I have a list that looks like this:</p> <p><a href="http://www.domain.com/folder1/folder2/|,1" rel="nofollow noreferrer">http://www.domain.com/folder1/folder2/|,1</a><br /> <a href="http://www.domain.com/folder1/|,1" rel="nofollow noreferrer">http://www.domain.com/folder1/|,1</a><br /> <a href="http://www.domain.com/folder1/folder2/folder3/|,1" rel="nofollow noreferrer">http://www.domain.com/folder1/folder2/folder3/|,1</a><br /> <a href="http://www.domain.com/folder1/|,1" rel="nofollow noreferrer">http://www.domain.com/folder1/|,1</a><br /> <a href="http://www.domain.com/folder1/folder2/|,1" rel="nofollow noreferrer">http://www.domain.com/folder1/folder2/|,1</a><br /> <a href="http://www.domain.com/folder1/folder2/|,1" rel="nofollow noreferrer">http://www.domain.com/folder1/folder2/|,1</a><br /> <a href="http://www.domain.com/folder1/folder2/folder3/|,1" rel="nofollow noreferrer">http://www.domain.com/folder1/folder2/folder3/|,1</a><br /></p> <p>The pipe and the comma separates the path from the amount of files that are under that path. Is it possible some how use Jython to order the URLs by length, so it would end up look like the below list:</p> <p><a href="http://www.domain.com/folder1/|,1" rel="nofollow noreferrer">http://www.domain.com/folder1/|,1</a><br /> <a href="http://www.domain.com/folder1/|,1" rel="nofollow noreferrer">http://www.domain.com/folder1/|,1</a><br /> <a href="http://www.domain.com/folder1/folder2/|,1" rel="nofollow noreferrer">http://www.domain.com/folder1/folder2/|,1</a><br /> <a href="http://www.domain.com/folder1/folder2/|,1" rel="nofollow noreferrer">http://www.domain.com/folder1/folder2/|,1</a><br /> <a href="http://www.domain.com/folder1/folder2/|,1" rel="nofollow noreferrer">http://www.domain.com/folder1/folder2/|,1</a><br /> <a href="http://www.domain.com/folder1/folder2/folder3/|,1" rel="nofollow noreferrer">http://www.domain.com/folder1/folder2/folder3/|,1</a><br /> <a href="http://www.domain.com/folder1/folder2/folder3/|,1" rel="nofollow noreferrer">http://www.domain.com/folder1/folder2/folder3/|,1</a><br /></p> <p>Hope you guys get what I mean, any help would be appreciated. Cheers</p>
[ { "answer_id": 249742, "author": "Michael McCarty", "author_id": 25007, "author_profile": "https://Stackoverflow.com/users/25007", "pm_score": 0, "selected": false, "text": "<p>Wouldn't sorting them take care of this?</p>\n" }, { "answer_id": 249754, "author": "bobince", "author_id": 18936, "author_profile": "https://Stackoverflow.com/users/18936", "pm_score": 3, "selected": true, "text": "<p>Sort-by-length, using a sort function:</p>\n\n<pre><code>urls.sort(lambda a, b: cmp(len(a), len(b)))\n</code></pre>\n\n<p>For performance, some might prefer the decorate-sort-undecorate pattern:</p>\n\n<pre><code>urllengths= [(len(url), url) for url in urls]\nurllengths.sort()\nurls= [url for (l, url) in urllengths]\n</code></pre>\n\n<p>Or as a one-liner:</p>\n\n<pre><code>urls= zip(*sorted((len(url), url) for url in urls))[1]\n</code></pre>\n" }, { "answer_id": 249766, "author": "gimel", "author_id": 6491, "author_profile": "https://Stackoverflow.com/users/6491", "pm_score": 1, "selected": false, "text": "<p>Until jython catches up to <em>python 2.4</em>, you cannot use the <em>key</em> argument to <em>list.sort()</em>:</p>\n\n<pre><code>mylist.sort(key=len)\n</code></pre>\n\n<p>So, like in the good old days, we have the <a href=\"http://code.activestate.com/recipes/52234/\" rel=\"nofollow noreferrer\">decorate-sort-undecorate</a> idiom. To sort <code>mylist</code> by item length, we generate a <code>decorated_list</code> of <code>(len(item),item)</code> tuples, sort that, and finally strip the items back:</p>\n\n<pre><code>decorated_list = zip(map(len, mylist), mylist)\ndecorated_list.sort()\nsorted_list = [i[1] for i in decorated_list]\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249729", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30786/" ]
I am writing a Jython script to sort a list of URLs. I have a list that looks like this: <http://www.domain.com/folder1/folder2/|,1> <http://www.domain.com/folder1/|,1> <http://www.domain.com/folder1/folder2/folder3/|,1> <http://www.domain.com/folder1/|,1> <http://www.domain.com/folder1/folder2/|,1> <http://www.domain.com/folder1/folder2/|,1> <http://www.domain.com/folder1/folder2/folder3/|,1> The pipe and the comma separates the path from the amount of files that are under that path. Is it possible some how use Jython to order the URLs by length, so it would end up look like the below list: <http://www.domain.com/folder1/|,1> <http://www.domain.com/folder1/|,1> <http://www.domain.com/folder1/folder2/|,1> <http://www.domain.com/folder1/folder2/|,1> <http://www.domain.com/folder1/folder2/|,1> <http://www.domain.com/folder1/folder2/folder3/|,1> <http://www.domain.com/folder1/folder2/folder3/|,1> Hope you guys get what I mean, any help would be appreciated. Cheers
Sort-by-length, using a sort function: ``` urls.sort(lambda a, b: cmp(len(a), len(b))) ``` For performance, some might prefer the decorate-sort-undecorate pattern: ``` urllengths= [(len(url), url) for url in urls] urllengths.sort() urls= [url for (l, url) in urllengths] ``` Or as a one-liner: ``` urls= zip(*sorted((len(url), url) for url in urls))[1] ```
249,747
<p>Im currently working on a PPC application that I would like to test in the PPC emulator "USA Windows mobile 5.0 PC R2 Emulator" without using Active Sync. Somewhere in my back head I think I have been able to just do that: But when I start a debug session with Visual Studio, it can not deploy the application to the emulator. All I get in the build log is:</p> <pre><code>9&gt;------ Deploy started: Project: DLL1, Configuration: Debug Salsa ARMv4 Windows Mobile 5.0 Pocket PC SDK (ARMV4I) ------ 9&gt;There are no more files. 9&gt; 10&gt;------ Skipped Deploy: Project: DLL2, Configuration: Debug Salsa ARMv4 Windows Mobile 5.0 Pocket PC SDK (ARMV4I) ------ 10&gt;Project not selected to build for this solution configuration 11&gt;------ Deploy started: Project: DLL3, Configuration: Debug Salsa ARMv4 Windows Mobile 5.0 Pocket PC SDK (ARMV4I) ------ 11&gt;There are no more files. 11&gt; ========== Build: 0 succeeded, 0 failed, 7 up-to-date, 5 skipped ========== ========== Deploy: 3 succeeded, 2 failed, 7 skipped ========== </code></pre> <p>If I cradle it (Using Device Emulator manager) and let the device sync through ActiveSync, then Visual Studio can deploy and debug. But I would like to debug some connectivity issues without being connected thorugh ActiveSync. How can I do that?</p>
[ { "answer_id": 249811, "author": "SmacL", "author_id": 22564, "author_profile": "https://Stackoverflow.com/users/22564", "pm_score": 0, "selected": false, "text": "<p>From your build log, you are targetting the <strong>ARMv4</strong> processor. You need to target <strong>Win32 (WCE emulator)</strong> in order to use and debug through the emulator.</p>\n" }, { "answer_id": 251427, "author": "Shane Powell", "author_id": 23235, "author_profile": "https://Stackoverflow.com/users/23235", "pm_score": 0, "selected": false, "text": "<p>It should work without ActiveSync by default. The only problem I can think of is that you have set the emulator transport to \"TCP Connect Transport\" which would require a ActiveSync connection.</p>\n\n<p>In Tools / Options / Devices, select the \"USA Windows mobile 5.0 PC R2 Emulator\" and select Properties. Make sure the Transport is set to \"DMA Transport\".</p>\n\n<p>Hope that helps.</p>\n" }, { "answer_id": 262107, "author": "baash05", "author_id": 31325, "author_profile": "https://Stackoverflow.com/users/31325", "pm_score": 0, "selected": false, "text": "<p>To be honest I'd think it wouldn't be possible to test a \"wireless\" application while you're wired. Same goes for if you're debugging through the wireless connection. The process of debugging will have an affect on your coms. \nFirst the HH's are typically smarter then we'd like them to be. While wired they use that path to the net. (be like water) </p>\n\n<p>Suppose the connection is strengthened by your IDE so you can debug.. Well then you're not really testing accurately. \nSuppose on the other hand that your connection's band width is affected by debugging. Well again it's not accurate.</p>\n\n<p>I'd add a log to your applications coms'.. </p>\n\n<p>Typically I have a log file that's generated when the coms starts and gets closed when the coms is done. This log file doesn't need much logic and actually turns out to be something I leave in the app when I'm ready to release. Nothing like having a client send you the log file when something goes bad. The overhead is quite low because it's always starting over. </p>\n" }, { "answer_id": 388910, "author": "redsolo", "author_id": 28553, "author_profile": "https://Stackoverflow.com/users/28553", "pm_score": 2, "selected": false, "text": "<p>The actual problem was that I had different target devices when I built the project and tried to deploy it. At the end VS would deploy one file to an ActiveSync device, one to the emulator and so forth. It was not suprisngly that it didnt work. If I changed the target device for the current project, it would not change it for the other projects...</p>\n\n<p>So if you have problems deploying using Visual Studio and having multiple projects in a solution, make sure that they all go the same target device. </p>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249747", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28553/" ]
Im currently working on a PPC application that I would like to test in the PPC emulator "USA Windows mobile 5.0 PC R2 Emulator" without using Active Sync. Somewhere in my back head I think I have been able to just do that: But when I start a debug session with Visual Studio, it can not deploy the application to the emulator. All I get in the build log is: ``` 9>------ Deploy started: Project: DLL1, Configuration: Debug Salsa ARMv4 Windows Mobile 5.0 Pocket PC SDK (ARMV4I) ------ 9>There are no more files. 9> 10>------ Skipped Deploy: Project: DLL2, Configuration: Debug Salsa ARMv4 Windows Mobile 5.0 Pocket PC SDK (ARMV4I) ------ 10>Project not selected to build for this solution configuration 11>------ Deploy started: Project: DLL3, Configuration: Debug Salsa ARMv4 Windows Mobile 5.0 Pocket PC SDK (ARMV4I) ------ 11>There are no more files. 11> ========== Build: 0 succeeded, 0 failed, 7 up-to-date, 5 skipped ========== ========== Deploy: 3 succeeded, 2 failed, 7 skipped ========== ``` If I cradle it (Using Device Emulator manager) and let the device sync through ActiveSync, then Visual Studio can deploy and debug. But I would like to debug some connectivity issues without being connected thorugh ActiveSync. How can I do that?
The actual problem was that I had different target devices when I built the project and tried to deploy it. At the end VS would deploy one file to an ActiveSync device, one to the emulator and so forth. It was not suprisngly that it didnt work. If I changed the target device for the current project, it would not change it for the other projects... So if you have problems deploying using Visual Studio and having multiple projects in a solution, make sure that they all go the same target device.
249,760
<p>There is this example code, but then it starts talking about millisecond / nanosecond problems.</p> <p>The same question is on MSDN, <em><a href="https://learn.microsoft.com/archive/blogs/brada/seconds-since-the-unix-epoch-in-c" rel="noreferrer">Seconds since the Unix epoch in C#</a></em>.</p> <p>This is what I've got so far:</p> <pre><code>public Double CreatedEpoch { get { DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime(); TimeSpan span = (this.Created.ToLocalTime() - epoch); return span.TotalSeconds; } set { DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime(); this.Created = epoch.AddSeconds(value); } } </code></pre>
[ { "answer_id": 249793, "author": "Luk", "author_id": 5789, "author_profile": "https://Stackoverflow.com/users/5789", "pm_score": 2, "selected": false, "text": "<p>A Unix tick is 1 second (if I remember well), and a .NET tick is 100&nbsp;nanoseconds. </p>\n\n<p>If you've been encountering problems with nanoseconds, you might want to try using AddTick(10000000 * value).</p>\n" }, { "answer_id": 250400, "author": "ScottCher", "author_id": 24179, "author_profile": "https://Stackoverflow.com/users/24179", "pm_score": 11, "selected": true, "text": "<p>Here's what you need:</p>\n<pre><code>public static DateTime UnixTimeStampToDateTime( double unixTimeStamp )\n{\n // Unix timestamp is seconds past epoch\n DateTime dateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);\n dateTime = dateTime.AddSeconds( unixTimeStamp ).ToLocalTime();\n return dateTime;\n}\n</code></pre>\n<p>Or, for Java (which is different because the timestamp is in milliseconds, not seconds):</p>\n<pre><code>public static DateTime JavaTimeStampToDateTime( double javaTimeStamp )\n{\n // Java timestamp is milliseconds past epoch\n DateTime dateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);\n dateTime = dateTime.AddMilliseconds( javaTimeStamp ).ToLocalTime();\n return dateTime;\n}\n</code></pre>\n" }, { "answer_id": 5641328, "author": "n8CodeGuru", "author_id": 311864, "author_profile": "https://Stackoverflow.com/users/311864", "pm_score": 3, "selected": false, "text": "<p>I found the right answer just by comparing the conversion to 1/1/1970 w/o the local time adjustment;</p>\n\n<pre><code>DateTime date = new DateTime(2011, 4, 1, 12, 0, 0, 0);\nDateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0);\nTimeSpan span = (date - epoch);\ndouble unixTime =span.TotalSeconds;\n</code></pre>\n" }, { "answer_id": 7596509, "author": "Dmitry Fedorkov", "author_id": 934618, "author_profile": "https://Stackoverflow.com/users/934618", "pm_score": 8, "selected": false, "text": "<p>DateTime to UNIX timestamp:</p>\n\n<pre><code>public static double DateTimeToUnixTimestamp(DateTime dateTime)\n{\n return (TimeZoneInfo.ConvertTimeToUtc(dateTime) - \n new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc)).TotalSeconds;\n}\n</code></pre>\n" }, { "answer_id": 10147471, "author": "gl051", "author_id": 1226576, "author_profile": "https://Stackoverflow.com/users/1226576", "pm_score": 6, "selected": false, "text": "<p>From <a href=\"https://en.wikipedia.org/wiki/Coordinated_Universal_Time#Daylight_saving_time\" rel=\"noreferrer\">Wikipedia</a>:</p>\n\n<blockquote>\n <p>UTC does not change with a change of seasons, but local time or civil time may change if a time zone jurisdiction observes daylight saving time (summer time). For example, local time on the east coast of the United States is five hours behind UTC during winter, but four hours behind while daylight saving is observed there.</p>\n</blockquote>\n\n<p>So this is my code:</p>\n\n<pre><code>TimeSpan span = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0,DateTimeKind.Utc));\ndouble unixTime = span.TotalSeconds;\n</code></pre>\n" }, { "answer_id": 12770507, "author": "Chris Thoman", "author_id": 918685, "author_profile": "https://Stackoverflow.com/users/918685", "pm_score": 4, "selected": false, "text": "<p>To supplement ScottCher's answer, I recently found myself in the annoying scenario of having both seconds and milliseconds UNIX timestamps arbitrarily mixed together in an input data set. The following code seems to handle this well:</p>\n\n<pre><code>static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);\nstatic readonly double MaxUnixSeconds = (DateTime.MaxValue - UnixEpoch).TotalSeconds;\n\npublic static DateTime UnixTimeStampToDateTime(double unixTimeStamp)\n{\n return unixTimeStamp &gt; MaxUnixSeconds\n ? UnixEpoch.AddMilliseconds(unixTimeStamp)\n : UnixEpoch.AddSeconds(unixTimeStamp);\n}\n</code></pre>\n" }, { "answer_id": 20796273, "author": "i3arnon", "author_id": 885318, "author_profile": "https://Stackoverflow.com/users/885318", "pm_score": 2, "selected": false, "text": "<p>I needed to convert a <a href=\"https://learn.microsoft.com/windows/desktop/api/winsock/ns-winsock-timeval\" rel=\"nofollow noreferrer\">timeval struct</a> (seconds, microseconds) containing <code>UNIX time</code> to <code>DateTime</code> without losing precision and haven't found an answer here so I thought I just might add mine:</p>\n\n<pre><code>DateTime _epochTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);\nprivate DateTime UnixTimeToDateTime(Timeval unixTime)\n{\n return _epochTime.AddTicks(\n unixTime.Seconds * TimeSpan.TicksPerSecond +\n unixTime.Microseconds * TimeSpan.TicksPerMillisecond/1000);\n}\n</code></pre>\n" }, { "answer_id": 24906105, "author": "Felix Keil", "author_id": 3703372, "author_profile": "https://Stackoverflow.com/users/3703372", "pm_score": 5, "selected": false, "text": "<p>Be careful, if you need precision higher than milliseconds!</p>\n\n<p>.NET (v4.6) methods (e.g. <strong>FromUnixTimeMilliseconds</strong>) don't provide this precision.</p>\n\n<p><strong>AddSeconds</strong> and <strong>AddMilliseconds</strong> also cut off the microseconds in the double.</p>\n\n<p>These versions have high precision:</p>\n\n<p><strong>Unix -> DateTime</strong></p>\n\n<pre><code>public static DateTime UnixTimestampToDateTime(double unixTime)\n{\n DateTime unixStart = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);\n long unixTimeStampInTicks = (long) (unixTime * TimeSpan.TicksPerSecond);\n return new DateTime(unixStart.Ticks + unixTimeStampInTicks, System.DateTimeKind.Utc);\n}\n</code></pre>\n\n<p><strong>DateTime -> Unix</strong></p>\n\n<pre><code>public static double DateTimeToUnixTimestamp(DateTime dateTime)\n{\n DateTime unixStart = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);\n long unixTimeStampInTicks = (dateTime.ToUniversalTime() - unixStart).Ticks;\n return (double) unixTimeStampInTicks / TimeSpan.TicksPerSecond;\n}\n</code></pre>\n" }, { "answer_id": 25270450, "author": "Hot Licks", "author_id": 581994, "author_profile": "https://Stackoverflow.com/users/581994", "pm_score": 2, "selected": false, "text": "<pre><code>DateTime unixEpoch = DateTime.ParseExact(\"1970-01-01\", \"yyyy-MM-dd\", System.Globalization.CultureInfo.InvariantCulture);\nDateTime convertedTime = unixEpoch.AddMilliseconds(unixTimeInMillisconds);\n</code></pre>\n\n<p>Of course, one can make <code>unixEpoch</code> a global static, so it only needs to appear once in your project, and one can use <code>AddSeconds</code> if the UNIX time is in seconds.</p>\n\n<p>To go the other way:</p>\n\n<pre><code>double unixTimeInMilliseconds = timeToConvert.Subtract(unixEpoch).TotalMilliseconds;\n</code></pre>\n\n<p>Truncate to Int64 and/or use <code>TotalSeconds</code> as needed.</p>\n" }, { "answer_id": 26225744, "author": "i3arnon", "author_id": 885318, "author_profile": "https://Stackoverflow.com/users/885318", "pm_score": 9, "selected": false, "text": "<p>The <a href=\"http://www.visualstudio.com/en-us/news/vs2015-preview-vs#Net\" rel=\"noreferrer\">latest version of .NET (v4.6)</a> has added built-in support for Unix time conversions. That includes both to and from Unix time represented by either seconds or milliseconds.</p>\n\n<ul>\n<li>Unix time in seconds to UTC <code>DateTimeOffset</code>:</li>\n</ul>\n\n<p></p>\n\n<pre><code>DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeSeconds(1000);\n</code></pre>\n\n<ul>\n<li><code>DateTimeOffset</code> to Unix time in seconds:</li>\n</ul>\n\n<p></p>\n\n<pre><code>long unixTimeStampInSeconds = dateTimeOffset.ToUnixTimeSeconds();\n</code></pre>\n\n<ul>\n<li>Unix time in milliseconds to UTC <code>DateTimeOffset</code>:</li>\n</ul>\n\n<p></p>\n\n<pre><code>DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeMilliseconds(1000000);\n</code></pre>\n\n<ul>\n<li><code>DateTimeOffset</code> to Unix time in milliseconds:</li>\n</ul>\n\n<p></p>\n\n<pre><code>long unixTimeStampInMilliseconds = dateTimeOffset.ToUnixTimeMilliseconds();\n</code></pre>\n\n<hr>\n\n<p>Note: These methods convert to and from a UTC <code>DateTimeOffset</code>. To get a <code>DateTime</code> representation simply use the <code>DateTimeOffset.UtcDateTime</code> or <code>DateTimeOffset.LocalDateTime</code> properties:</p>\n\n<pre><code>DateTime dateTime = dateTimeOffset.UtcDateTime;\n</code></pre>\n" }, { "answer_id": 29908680, "author": "orad", "author_id": 450913, "author_profile": "https://Stackoverflow.com/users/450913", "pm_score": 4, "selected": false, "text": "<p>See <a href=\"https://github.com/IdentityModel/IdentityModel/blob/master/source/IdentityModel.Shared/EpochTimeExtensions.cs\" rel=\"noreferrer\">IdentityModel.EpochTimeExtensions</a></p>\n\n<pre><code>public static class EpochTimeExtensions\n{\n /// &lt;summary&gt;\n /// Converts the given date value to epoch time.\n /// &lt;/summary&gt;\n public static long ToEpochTime(this DateTime dateTime)\n {\n var date = dateTime.ToUniversalTime();\n var ticks = date.Ticks - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).Ticks;\n var ts = ticks / TimeSpan.TicksPerSecond;\n return ts;\n }\n\n /// &lt;summary&gt;\n /// Converts the given date value to epoch time.\n /// &lt;/summary&gt;\n public static long ToEpochTime(this DateTimeOffset dateTime)\n {\n var date = dateTime.ToUniversalTime();\n var ticks = date.Ticks - new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero).Ticks;\n var ts = ticks / TimeSpan.TicksPerSecond;\n return ts;\n }\n\n /// &lt;summary&gt;\n /// Converts the given epoch time to a &lt;see cref=\"DateTime\"/&gt; with &lt;see cref=\"DateTimeKind.Utc\"/&gt; kind.\n /// &lt;/summary&gt;\n public static DateTime ToDateTimeFromEpoch(this long intDate)\n {\n var timeInTicks = intDate * TimeSpan.TicksPerSecond;\n return new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddTicks(timeInTicks);\n }\n\n /// &lt;summary&gt;\n /// Converts the given epoch time to a UTC &lt;see cref=\"DateTimeOffset\"/&gt;.\n /// &lt;/summary&gt;\n public static DateTimeOffset ToDateTimeOffsetFromEpoch(this long intDate)\n {\n var timeInTicks = intDate * TimeSpan.TicksPerSecond;\n return new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero).AddTicks(timeInTicks);\n }\n}\n</code></pre>\n" }, { "answer_id": 30518793, "author": "superlogical", "author_id": 52360, "author_profile": "https://Stackoverflow.com/users/52360", "pm_score": -1, "selected": false, "text": "<p>For .NET 4.6 and later:</p>\n\n<pre><code>public static class UnixDateTime\n{\n public static DateTimeOffset FromUnixTimeSeconds(long seconds)\n {\n if (seconds &lt; -62135596800L || seconds &gt; 253402300799L)\n throw new ArgumentOutOfRangeException(\"seconds\", seconds, \"\");\n\n return new DateTimeOffset(seconds * 10000000L + 621355968000000000L, TimeSpan.Zero);\n }\n\n public static DateTimeOffset FromUnixTimeMilliseconds(long milliseconds)\n {\n if (milliseconds &lt; -62135596800000L || milliseconds &gt; 253402300799999L)\n throw new ArgumentOutOfRangeException(\"milliseconds\", milliseconds, \"\");\n\n return new DateTimeOffset(milliseconds * 10000L + 621355968000000000L, TimeSpan.Zero);\n }\n\n public static long ToUnixTimeSeconds(this DateTimeOffset utcDateTime)\n {\n return utcDateTime.Ticks / 10000000L - 62135596800L;\n }\n\n public static long ToUnixTimeMilliseconds(this DateTimeOffset utcDateTime)\n {\n return utcDateTime.Ticks / 10000L - 62135596800000L;\n }\n\n [Test]\n public void UnixSeconds()\n {\n DateTime utcNow = DateTime.UtcNow;\n DateTimeOffset utcNowOffset = new DateTimeOffset(utcNow);\n\n long unixTimestampInSeconds = utcNowOffset.ToUnixTimeSeconds();\n\n DateTimeOffset utcNowOffsetTest = UnixDateTime.FromUnixTimeSeconds(unixTimestampInSeconds);\n\n Assert.AreEqual(utcNowOffset.Year, utcNowOffsetTest.Year);\n Assert.AreEqual(utcNowOffset.Month, utcNowOffsetTest.Month);\n Assert.AreEqual(utcNowOffset.Date, utcNowOffsetTest.Date);\n Assert.AreEqual(utcNowOffset.Hour, utcNowOffsetTest.Hour);\n Assert.AreEqual(utcNowOffset.Minute, utcNowOffsetTest.Minute);\n Assert.AreEqual(utcNowOffset.Second, utcNowOffsetTest.Second);\n }\n\n [Test]\n public void UnixMilliseconds()\n {\n DateTime utcNow = DateTime.UtcNow;\n DateTimeOffset utcNowOffset = new DateTimeOffset(utcNow);\n\n long unixTimestampInMilliseconds = utcNowOffset.ToUnixTimeMilliseconds();\n\n DateTimeOffset utcNowOffsetTest = UnixDateTime.FromUnixTimeMilliseconds(unixTimestampInMilliseconds);\n\n Assert.AreEqual(utcNowOffset.Year, utcNowOffsetTest.Year);\n Assert.AreEqual(utcNowOffset.Month, utcNowOffsetTest.Month);\n Assert.AreEqual(utcNowOffset.Date, utcNowOffsetTest.Date);\n Assert.AreEqual(utcNowOffset.Hour, utcNowOffsetTest.Hour);\n Assert.AreEqual(utcNowOffset.Minute, utcNowOffsetTest.Minute);\n Assert.AreEqual(utcNowOffset.Second, utcNowOffsetTest.Second);\n Assert.AreEqual(utcNowOffset.Millisecond, utcNowOffsetTest.Millisecond);\n }\n}\n</code></pre>\n" }, { "answer_id": 31588322, "author": "Fred", "author_id": 2470524, "author_profile": "https://Stackoverflow.com/users/2470524", "pm_score": 4, "selected": false, "text": "<p>Unix time conversion is new in .NET Framework 4.6.</p>\n\n<p>You can now more easily convert date and time values to or from .NET Framework types and Unix time. This can be necessary, for example, when converting time values between a JavaScript client and .NET server. The following APIs have been added to the <a href=\"https://learn.microsoft.com/dotnet/api/system.datetimeoffset\" rel=\"nofollow noreferrer\">DateTimeOffset structure</a>:</p>\n\n<pre><code>static DateTimeOffset FromUnixTimeSeconds(long seconds)\nstatic DateTimeOffset FromUnixTimeMilliseconds(long milliseconds)\nlong DateTimeOffset.ToUnixTimeSeconds()\nlong DateTimeOffset.ToUnixTimeMilliseconds()\n</code></pre>\n" }, { "answer_id": 50904674, "author": "madan", "author_id": 1251980, "author_profile": "https://Stackoverflow.com/users/1251980", "pm_score": 1, "selected": false, "text": "<pre><code>public static class UnixTime\n {\n private static readonly DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0);\n\n public static DateTime UnixTimeToDateTime(double unixTimeStamp)\n {\n return Epoch.AddSeconds(unixTimeStamp).ToUniversalTime();\n }\n }\n</code></pre>\n\n<p>you can call UnixTime.UnixTimeToDateTime(double datetime))</p>\n" }, { "answer_id": 53248007, "author": "mesut", "author_id": 1334979, "author_profile": "https://Stackoverflow.com/users/1334979", "pm_score": 3, "selected": false, "text": "<pre><code>var dt = DateTime.Now; \nvar unixTime = ((DateTimeOffset)dt).ToUnixTimeSeconds();\n</code></pre>\n\n<p>// 1510396991</p>\n\n<pre><code>var dt = DateTimeOffset.FromUnixTimeSeconds(1510396991);\n</code></pre>\n\n<p>// [11.11.2017 10:43:11 +00:00]</p>\n" }, { "answer_id": 54722681, "author": "Yang Zhang", "author_id": 1982524, "author_profile": "https://Stackoverflow.com/users/1982524", "pm_score": 3, "selected": false, "text": "<p>From .net 4.6, you can do this:</p>\n\n<pre><code>var dateTime = DateTimeOffset.FromUnixTimeSeconds(unixDateTime).DateTime;\n</code></pre>\n" }, { "answer_id": 57790748, "author": "Riyaz Hameed", "author_id": 1570636, "author_profile": "https://Stackoverflow.com/users/1570636", "pm_score": 3, "selected": false, "text": "<p>Written a simplest extension that works for us. If anyone looks for it...</p>\n\n<pre><code>public static class DateTimeExtensions\n{\n public static DateTime FromUnixTimeStampToDateTime(this string unixTimeStamp)\n {\n\n return DateTimeOffset.FromUnixTimeSeconds(long.Parse(unixTimeStamp)).UtcDateTime;\n }\n}\n</code></pre>\n" }, { "answer_id": 57974399, "author": "AMieres", "author_id": 4550898, "author_profile": "https://Stackoverflow.com/users/4550898", "pm_score": 3, "selected": false, "text": "<pre><code>System.DateTimeOffset.Now.ToUnixTimeSeconds()\n</code></pre>\n" }, { "answer_id": 61380874, "author": "Ramil Aliyev", "author_id": 8810311, "author_profile": "https://Stackoverflow.com/users/8810311", "pm_score": 5, "selected": false, "text": "<p>You can use <strong>DateTimeOffset</strong>.</p>\n<p>For example. I have a DateTime object</p>\n<pre><code>var dateTime1 = DateTime.Now;\n</code></pre>\n<p>If I want to convert it to the Unix time stamps, it can be achieved as follows</p>\n<pre><code>var unixTimeSeconds = new DateTimeOffset(dateTime1).ToUnixTimeSeconds()\n</code></pre>\n<p>If you want convert unix timeStamp to normal DateTime, you can use this code piece:</p>\n<pre><code>var dateTime2 = DateTimeOffset.FromUnixTimeSeconds(unixTimeSeconds).LocalDateTime;\n</code></pre>\n<p>or</p>\n<pre><code>var dateTime2 = DateTimeOffset.FromUnixTimeSeconds(unixTimeSeconds).UtcDateTime;\n</code></pre>\n<p>For more information please visit this link :</p>\n<p><a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.datetimeoffset.tounixtimeseconds?view=netframework-4.8\" rel=\"noreferrer\">DateTimeOffset.ToUnixTimeSeconds Method</a>,<br />\n<a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.datetimeoffset.fromunixtimeseconds?view=netframework-4.8\" rel=\"noreferrer\">DateTimeOffset.FromUnixTimeSeconds</a></p>\n" }, { "answer_id": 68662817, "author": "Nilufar Makhmudova", "author_id": 3480038, "author_profile": "https://Stackoverflow.com/users/3480038", "pm_score": 4, "selected": false, "text": "<p>Unix epoch is now part of DateTime class. Converting millis to DateTime is as easy as</p>\n<pre><code>DateTime.UnixEpoch.AddMilliseconds(millis)\n</code></pre>\n" }, { "answer_id": 69231326, "author": "Brendan Sluke", "author_id": 7660196, "author_profile": "https://Stackoverflow.com/users/7660196", "pm_score": 3, "selected": false, "text": "<p>In C# 8.0 (.NET Core 2.1) it is a simple one liner:</p>\n<pre><code>DateTime.UnixEpoch.AddSeconds(unixTimeInSeconds)\n</code></pre>\n" } ]
2008/10/30
[ "https://Stackoverflow.com/questions/249760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/986/" ]
There is this example code, but then it starts talking about millisecond / nanosecond problems. The same question is on MSDN, *[Seconds since the Unix epoch in C#](https://learn.microsoft.com/archive/blogs/brada/seconds-since-the-unix-epoch-in-c)*. This is what I've got so far: ``` public Double CreatedEpoch { get { DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime(); TimeSpan span = (this.Created.ToLocalTime() - epoch); return span.TotalSeconds; } set { DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime(); this.Created = epoch.AddSeconds(value); } } ```
Here's what you need: ``` public static DateTime UnixTimeStampToDateTime( double unixTimeStamp ) { // Unix timestamp is seconds past epoch DateTime dateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); dateTime = dateTime.AddSeconds( unixTimeStamp ).ToLocalTime(); return dateTime; } ``` Or, for Java (which is different because the timestamp is in milliseconds, not seconds): ``` public static DateTime JavaTimeStampToDateTime( double javaTimeStamp ) { // Java timestamp is milliseconds past epoch DateTime dateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); dateTime = dateTime.AddMilliseconds( javaTimeStamp ).ToLocalTime(); return dateTime; } ```