body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>A particular application may refer to a specific property in one of three languages in different contexts: in lowercase English, in uppercase English, and in Hebrew. To facilitate ease of converting one language to another, this monstrosity exists:</p> <pre><code>public string translatePersonType(string personType, string lang) { switch (personType) { case "employee": case "EMPLOYEE": case "ืขื•ื‘ื“": switch (lang) { case "eng": return "employee"; case "ENG": return "EMPLOYEE"; case "heb": return "ืขื•ื‘ื“"; } break; case "contractor": case "CONTRACTOR": case "ืงื‘ืœืŸ": switch (lang) { case "eng": return "contractor"; case "ENG": return "CONTRACTOR"; case "heb": return "ืงื‘ืœืŸ"; } break; case "supplier": case "SUPPLIER": case "ืกืคืง": switch (lang) { case "eng": return "supplier"; case "ENG": return "SUPPLIER"; case "heb": return "ืกืคืง"; } break; case "customer": case "CUSTOMER": case "ืœืงื•ื—": switch (lang) { case "eng": return "customer"; case "ENG": return "CUSTOMER"; case "heb": return "ืœืงื•ื—"; } break; default: return ""; }// end switch (personType) return ""; }// end translatePersonType </code></pre> <p>Can this be refactored to be more concise and maintainable? For reference, this is the database field behind the property:</p> <pre><code>personType SET('CUSTOMER','SUPPLIER','EMPLOYEE', 'CONTRACTOR') NOT NULL </code></pre> <p>Thanks.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T20:44:27.950", "Id": "15925", "Score": "0", "body": "Per @Carl Manaster s answer: using a table is simpler in this case than using a switch or a dictionary. Table is more natural. The details are up to you - you can store this mapping in the database, in an Excel file, in a CSV file, and then run LINQ on it ..." } ]
[ { "body": "<p>OK, this is Java and might take a little tickling to work in C#, but:</p>\n\n<pre><code>final String[] employee = {\"employee\", \"EMPLOYEE\", \"ืขื•ื‘ื“\"};\nfinal String[] contractor = {\"contractor\", \"CONTRACTOR\", \"ืงื‘ืœืŸ\"};\nfinal String[] supplier = {\"supplier\", \"SUPPLIER\", \"ืกืคืง\"};\nfinal String[] customer = {\"customer\", \"CUSTOMER\", \"ืœืงื•ื—\"};\nfinal String[][] classifications = {employee, contractor, supplier, customer};\n\npublic String translatePersonType(String personType, String lang) {\n int index = 0;\n if (lang == \"ENG\") index = 1;\n if (lang == \"heb\") index = 2;\n for (String[] classification : classifications) {\n if (Arrays.asList(classification).contains(personType)) {\n return classification[index];\n }\n }\n return null;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-16T22:53:05.693", "Id": "16070", "Score": "0", "body": "The basic idea is sound, simple to maintain (adding languages or types), and it is very compact. I can translate this easily into C#. Thank you!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T18:05:02.903", "Id": "9936", "ParentId": "9934", "Score": "5" } }, { "body": "<p>I think something like this should be enclosed in a class:</p>\n\n<pre><code>class PersonType\n{\n private readonly string m_englishName;\n private readonly string m_hebrewName;\n\n public string EnglishNameLowerCase { get { return m_englishName.ToLower(); } }\n public string EnglishNameUpperCase { get { return m_englishName.ToUpper(); } }\n public string HebrewName { get { return m_hebrewName; } }\n\n public PersonType(string englishName, string hebrewName)\n {\n m_englishName = englishName;\n m_hebrewName = hebrewName;\n }\n\n public bool IsMatch(string name)\n {\n return name == EnglishNameLowerCase\n || name == EnglishNameUpperCase\n || name == HebrewName;\n }\n\n public string GetName(string lang)\n {\n switch (lang)\n {\n case \"eng\":\n return EnglishNameLowerCase;\n case \"ENG\":\n return EnglishNameUpperCase;\n case \"heb\":\n return HebrewName;\n }\n\n throw new ArgumentException(\"lang\");\n }\n}\n\nโ€ฆ\n\nprivate static readonly PersonType[] PersonTypes =\n new[]\n {\n new PersonType(\"employee\", \"ืขื•ื‘ื“\"),\n new PersonType(\"contractor\", \"ืงื‘ืœืŸ\"),\n new PersonType(\"supplier\", \"ืกืคืง\"),\n new PersonType(\"customer\", \"ืœืงื•ื—\")\n }\n\npublic string TranslatePersonType(string personType, string lang)\n{\n return PersonTypes.Single(pt =&gt; pt.IsMatch(personType).GetName(lang);\n}\n</code></pre>\n\n<p>Even though it's still quite long, it would be much easier to add another person type or language.</p>\n\n<p>Also, I think it would make more sense if <code>lang</code> was an <code>enum</code>, not a <code>string</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T18:28:55.680", "Id": "9937", "ParentId": "9934", "Score": "2" } }, { "body": "<p>This kind of switch statements can be refactored using maps/dictionaries. I would do it like this:</p>\n\n<p><em>Edit: I actually made a couple of mistakes. After adding more unit tests I came up with a hopefully better version.</em></p>\n\n<pre><code>//V. 2:\npublic static string TranslatePersonTypeBetterRefactored(string personType, string lang)\n{\n var allDicts = new Dictionary&lt;string, Dictionary&lt;string, string&gt;&gt;\n {\n {\n \"heb\", new Dictionary&lt;string, string&gt;()\n {\n { \"employee\", \"ืขื•ื‘ื“\" },\n { \"contractor\", \"ืงื‘ืœืŸ\" },\n { \"supplier\", \"ืกืคืง\" },\n { \"customer\", \"ืœืงื•ื—\" }\n }\n },\n {\n \"eng\", new Dictionary&lt;string, string&gt;()\n {\n { \"ืขื•ื‘ื“\", \"employee\" },\n { \"ืงื‘ืœืŸ\", \"contractor\" },\n { \"ืกืคืง\", \"supplier\" },\n { \"ืœืงื•ื—\", \"customer\" }\n }\n },\n {\n \"_eng\", new Dictionary&lt;string, string&gt;()\n {\n { \"employee\", \"employee\" },\n { \"contractor\", \"contractor\" },\n { \"supplier\", \"supplier\" },\n { \"customer\", \"customer\" }\n }\n }\n };\n\n Dictionary&lt;string, string&gt; dict;\n string tran;\n\n if ((allDicts.TryGetValue(lang.ToLower(), out dict) &amp;&amp;\n dict.TryGetValue(personType.ToLower(), out tran)) ||\n (allDicts.TryGetValue(string.Format(\"_{0}\", lang.ToLower()), out dict) &amp;&amp;\n dict.TryGetValue(personType.ToLower(), out tran)))\n {\n var shouldBeUpper = lang.Any(c =&gt; char.IsUpper(c));\n\n return shouldBeUpper ? tran.ToUpper()\n : tran;\n }\n\n return string.Empty;\n}\n\n//V. 1 (buggy):\npublic static string TranslatePersonTypeRefactored(string personType, string lang)\n{\n var engToUpper = lang == \"ENG\";\n var engToLower = lang == \"eng\";\n\n if (engToUpper &amp;&amp; personType.Any(c =&gt; char.IsLower(c)))\n return personType.ToUpper();\n\n if (engToLower &amp;&amp; personType.Any(c =&gt; char.IsUpper(c)))\n return personType.ToLower();\n\n var hebrewToEnglishWords = new Dictionary&lt;string, string&gt;\n {\n { \"ืขื•ื‘ื“\", \"employee\" },\n { \"ืงื‘ืœืŸ\", \"contractor\" },\n { \"ืกืคืง\", \"supplier\" },\n { \"ืœืงื•ื—\", \"customer\" }\n };\n\n var hebrewToEngTranslation = hebrewToEnglishWords[personType];\n\n return engToLower ? hebrewToEngTranslation\n : hebrewToEngTranslation.ToUpper();\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T13:50:30.077", "Id": "15891", "Score": "1", "body": "Instead of the conditional expression after return, you could also put each language dictionary in a dictionary with lang as key too. `Dictionary<string, Dictionary<string, string>> {{ \"heb\", new Dictionar<string, string> {{ \"ืขื•ื‘ื“\", \"employee\" }, ...}}, \"ENG\", new Dictionary<string, string> {{ \"supplier\", \"SUPPLIER\" }, ...}};` :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T10:49:27.270", "Id": "9959", "ParentId": "9934", "Score": "6" } } ]
{ "AcceptedAnswerId": "9936", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T17:43:18.390", "Id": "9934", "Score": "7", "Tags": [ "c#" ], "Title": "Refactor embedded switch" }
9934
<p>I've made a solution for <a href="http://acm.timus.ru/problem.aspx?space=1&amp;num=1292&amp;locale=en" rel="nofollow noreferrer">this problem</a>:</p> <blockquote> <p><strong>Task:</strong></p> <p>Write a program for calculation of the distance to the next space station.</p> <p><strong>Algorithm:</strong></p> <p>First base is located at the distance equal to SMK from the beginning of the path (Sirius in our case). The next station is located at the distance of F(SMK) from the first. Third station โ€” at the distance of F(F(SMK)) and so on. Here \$F\$ โ€” is the Top Secret Mars Function (TSMF). Its value is the sum of the cubes of digits its argument in decimal notation (for example \$F(12) = 1^3 + 2^3 &gt; = 9\$). So if the distance from the (\$I โˆ’ 1\$)-th to \$I\$-th stations is \$X\$, then the distance between \$I\$-th and (\$I + 1\$)-th stations is \$F(X)\$. Your cruiser is located between (\$N โˆ’ 1\$)-th and \$N\$-th space stations at the distance of \$L\$ from (\$N โˆ’ 1\$)-th station. Taking \$N\$, \$K\$ (Secret Mars Key) and \$L\$ as input your program should output the distance \$M\$ between your cruiser and \$N\$-th station. Oh, by the way! The value of SMK is always divisible by 3.</p> <p><strong>Input:</strong></p> <p>Number \$T\$ (\$2 โ‰ค T โ‰ค 33333\$) is placed in the first line of input โ€” it is the number of tests for your program. It followed by the next \$T\$ lines.</p> <p>Each of these \$T\$ lines contains 3 integer numbers:</p> <p>\$N\$ (\$2 โ‰ค N โ‰ค 33333\$), \$K\$ (\$3 โ‰ค K โ‰ค 33333\$) and \$L\$ (\$L โ‰ฅ 1\$)</p> <p><strong>Output:</strong></p> <p>\$T\$ lines. \$I\$-th line contains the calculated value of \$M\$ for \$I\$-th test case.</p> <p><strong>It has to run in less than one second and take up less than 16 megabytes of memory.</strong></p> <p><strong>Sample:</strong></p> <p><a href="http://img33.imageshack.us/img33/502/81219587.jpg" rel="nofollow noreferrer">http://img33.imageshack.us/img33/502/81219587.jpg</a></p> </blockquote> <p><a href="http://ideone.com/2kWEN" rel="nofollow noreferrer">Here</a> is the compiled code:</p> <pre><code>static void Main() { int T = Convert.ToInt32(Console.ReadLine()); for (int k = 0; k &lt; T; k++) { string[] split = (Console.ReadLine()).Split(new Char[] { ' ' }); int N = Convert.ToInt32(split[0]); double K = 0; string Kst = split[1]; double POST = 0; for (int i = 0; i &lt; N - 1; i++) { for (int j = 0; j &lt;= Kst.Length - 1; j++) { int Kindex = int.Parse(Convert.ToString(Kst[j])); K = K + Kindex*Kindex*Kindex; } POST = K; Kst = Convert.ToString(K); K = 0; } Console.WriteLine(POST - Convert.ToDouble(split[2])); } } </code></pre> <p>But this code doesn't go through the time limit of 1.0 second. How can I improve the speed of this solution?</p>
[]
[ { "body": "<p>Here are a few tips:</p>\n\n<ul>\n<li><p>Instead of getting each character, creating a new string from it, and then parse the string into a number, just get the character and convert the character code into the number.</p></li>\n<li><p>Alternatively, parse the whole number once, then get the digits numerically using modulo.</p></li>\n<li><p>There are only ten digits, so you can easily set up an array of precalculated cube values.</p></li>\n<li><p><code>K</code> is a double, but there are no floating point operations here. Use an <code>int</code>, or a <code>long</code> if needed.</p></li>\n</ul>\n\n<p>Example:</p>\n\n<pre><code>int T = Convert.ToInt32(Console.ReadLine());\nint[] cube = { 0, 1, 4, 9, 16, 25, 36, 49, 64, 81 };\nfor (int k = 0; k &lt; T; k++) {\n string[] split = Console.ReadLine().Split(' ');\n int N = Convert.ToInt32(split[0]);\n int Kst = Convert.ToInt32(split[1]);\n int K = 0;\n for (int i = 0; i &lt; N - 1; i++) {\n K = 0;\n while (Kst &gt; 0) {\n K += cube[Kst % 10];\n Kst /= 10;\n }\n Kst = K;\n }\n Console.WriteLine(K - Convert.ToInt32(split[2]));\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T21:33:18.777", "Id": "9947", "ParentId": "9942", "Score": "13" } }, { "body": "<pre><code>static void Main()\n{ \nint T = Convert.ToInt32(Console.ReadLine());\nfor (int k = 0; k &lt; T; k++)\n</code></pre>\n\n<p>That is a confusing of <code>k</code>, because <code>K</code> is used for something quite different. I suggest using <code>t</code> (of course for non contest code, you should have longer names.</p>\n\n<pre><code>{\n string[] split = (Console.ReadLine()).Split(new Char[] { ' ' });\n int N = Convert.ToInt32(split[0]);\n double K = 0;\n string Kst = split[1];\n double POST = 0;\n</code></pre>\n\n<p>Its odd that you decided to capitalize all the letters in this</p>\n\n<pre><code> for (int i = 0; i &lt; N - 1; i++)\n {\n for (int j = 0; j &lt;= Kst.Length - 1; j++)\n {\n int Kindex = int.Parse(Convert.ToString(Kst[j]));\n</code></pre>\n\n<p>That's not a index, don't call it Kindex. As Guffa noted is not a great idea to convert between strings and integers all the time like that. It'll be a speed killer. Instead, I suggest using modulo and division to extract the digits</p>\n\n<pre><code> K = K + Kindex*Kindex*Kindex;\n }\n POST = K; \n Kst = Convert.ToString(K);\n K = 0;\n</code></pre>\n\n<p>Do this at the beginning of the loop, that makes more sense</p>\n\n<pre><code> }\n Console.WriteLine(POST - Convert.ToDouble(split[2]));\n</code></pre>\n\n<p>I'd have done this conversion back at the beginning with the other conversions.\n }</p>\n\n<pre><code>}\n</code></pre>\n\n<p>As for your actual algorithm, I don't want to just give you the answer, because the point is to figure out. But, I can give you a hint. Print out the sequences of F(K), F(F(K)), etc for various K and see what happens.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T01:52:44.290", "Id": "86488", "Score": "0", "body": "Good hint. I'm glad I read it before answering and giving it away." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T23:25:15.127", "Id": "9949", "ParentId": "9942", "Score": "7" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T20:40:44.390", "Id": "9942", "Score": "4", "Tags": [ "c#", "algorithm", "performance", "programming-challenge" ], "Title": "Calculation of the distance to the next space station" }
9942
<p>This takes in a user specified number of points then finds the two points with the shortest distance.</p> <pre><code>import java.util.Scanner; import java.lang.Math; public class FindNearestPoints { public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.print("Enter the number of points: "); final int numOfPoints = scan.nextInt(); double[][] points = new double[numOfPoints][2]; double shortestDistance=0; double distance=0; String closestPoint1=""; String closestPoint2=""; //enter x,y coords into the ix2 table points[][] for (int i=0; i&lt;numOfPoints; i++) { System.out.print("Enter point x" + i + ": "); points[i][0] = scan.nextDouble(); System.out.print("Enter point y" + i + ": "); points[i][1] = scan.nextDouble(); } //get the distance between the point in the ith row and the (m+1)th row //and check if it's shorter than the distance between 0th and 1st for (int i=0; i&lt;numOfPoints; i++) { //use m=i rather than 0 to avoid duplicate computations for (int m=i; m&lt;numOfPoints-1;m++) { double dx = points[i][0] - points[m+1][0]; double dy = points[i][1] - points[m+1][1]; distance = Math.sqrt(dx*dx + dy*dy); //set shortestDistance and closestPoints to the first iteration if (m == 0 &amp;&amp; i == 0) { shortestDistance = distance; closestPoint1 = "(" + points[0][0] + "," + points[0][1] + ")"; closestPoint2 = "(" + points[1][0] + "," + points[1][1] + ")"; } //then check if any further iterations have shorter distances else if (distance &lt; shortestDistance) { shortestDistance = distance; closestPoint1 = "(" + points[i][0] + "," + points[i][1] + ")"; closestPoint2 = "(" + points[m+1][0] + "," + points[m+1][1] + ")"; } } } System.out.println("The shortest distance is: " + shortestDistance); System.out.println("The closest points are " + closestPoint1 + " and " + closestPoint2); } } </code></pre>
[]
[ { "body": "<p>For starters, this code should use a Point class, consisting of an x and y location. Your variable points would then be Point[] rather than a two dimensional array. The Point class should have a method for reading values, printing values and calculating the distance between two points.</p>\n\n<p>Then, using the Point class, your code would be dramatically simpler and easier to read. It might even be easier to write from scratch rather than try and fix what you have.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T21:30:29.483", "Id": "15829", "Score": "0", "body": "I purposefully neglected to mention that this lab required 2D arrays because I hoped there was a class like this. Thanks. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T22:22:30.493", "Id": "15833", "Score": "0", "body": "in the real world `Point[]` is apparently much less memory-efficient than a 2d array of Java primitives. http://teddziuba.com/2008/02/the-road-to-hell-is-64-bits-wi.html" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T01:16:54.517", "Id": "15838", "Score": "1", "body": "Memory efficiency is very rarely an issue in the real world. The cost of the programmer's time is far more expensive than the cost in CPU cycles 98% of the time. Trying to optimize an algorithm without justifiable need is called \"premature optimization\" and is far more likely than not to be a mistake." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-12-19T05:06:13.023", "Id": "282733", "Score": "0", "body": "@Leonid, Can you please fix the broken link?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-12-20T00:19:15.180", "Id": "282916", "Score": "0", "body": "@N00bPr0grammer Dziuba has deleted his blog." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T20:52:47.043", "Id": "9944", "ParentId": "9943", "Score": "10" } }, { "body": "<h2>Algorithm</h2>\n\n<p>This is a classical problem in computational geometry and <a href=\"http://en.wikipedia.org/wiki/Closest_pair_of_points_problem\" rel=\"nofollow noreferrer\">there are a lot of efficient approaches</a> if you're interested. The longest distance problem (aka. diameter of a polygon) is more interesting though, and will introduce you to a really useful tool in computational geometry: <a href=\"https://web.archive.org/web/20120501000000*/http://cgm.cs.mcgill.ca/~orm/rotcal.html\" rel=\"nofollow noreferrer\">the rotating calipers</a>.</p>\n\n<h2>Code</h2>\n\n<p>It's easy to read, but three improvements can be made:</p>\n\n<ol>\n<li><code>for (int m=i; m&lt;numOfPoints-1;m++)</code> is indeed an interesting optimization (x2 improvement). It would be more readable to make m go from <code>i+1</code> to <code>numOfPoints</code>.</li>\n<li>You can avoid computing <code>Math.sqrt(dx*dx + dy*dy);</code>. <code>dx*dx + dy*dy</code> is enough to compare the distances. When printing the distance, you can use <code>Math.sqrt</code>.</li>\n<li>First set <code>shortestDistance</code> to <code>Double.MAX_VALUE</code>, this will avoid you the <code>if (m == 0 &amp;&amp; i == 0)</code> case and the resulting duplication: you'll always find a distance shorter than infinity.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T21:33:01.787", "Id": "15830", "Score": "0", "body": "Thank you! This is basically what I was looking for, very interesting stuff." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-22T11:57:56.380", "Id": "58565", "Score": "0", "body": "I don't think 'shortestDistance' should be set to Double.MAX_VALUE. The name suggests a short distance, not the maximum double value." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-22T15:08:47.893", "Id": "58594", "Score": "0", "body": "@user1021726 Which is why setting it first to the maximum double value is a safe way to make sure the next distance will be shorter. Think of it as infinity. Did I miss something?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-12-19T05:03:07.210", "Id": "282732", "Score": "0", "body": "Can you please fix the broken link, `the rotating calipers` please?" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T20:58:12.527", "Id": "9945", "ParentId": "9943", "Score": "10" } }, { "body": "<pre><code>import java.util.Scanner;\nimport java.lang.Math;\n\npublic class FindNearestPoints\n{\n public static void main(String[] args)\n {\n Scanner scan = new Scanner(System.in);\n\n System.out.print(\"Enter the number of points: \");\n final int numOfPoints = scan.nextInt();\n\n double[][] points = new double[numOfPoints][2];\n double shortestDistance=0;\n double distance=0;\n String closestPoint1=\"\";\n String closestPoint2=\"\";\n</code></pre>\n\n<p>Declare your variables close to where you use them, not all at the beginning. </p>\n\n<pre><code> //enter x,y coords into the ix2 table points[][]\n for (int i=0; i&lt;numOfPoints; i++)\n {\n System.out.print(\"Enter point x\" + i + \": \");\n points[i][0] = scan.nextDouble();\n System.out.print(\"Enter point y\" + i + \": \");\n points[i][1] = scan.nextDouble();\n }\n\n //get the distance between the point in the ith row and the (m+1)th row\n //and check if it's shorter than the distance between 0th and 1st\n for (int i=0; i&lt;numOfPoints; i++)\n {\n //use m=i rather than 0 to avoid duplicate computations\n for (int m=i; m&lt;numOfPoints-1;m++)\n {\n</code></pre>\n\n<p>Use <code>for(m = i + 1; m &lt; numOfPoints; m++)</code> That way you don't have to <code>m + 1</code> everywhere</p>\n\n<pre><code> double dx = points[i][0] - points[m+1][0];\n double dy = points[i][1] - points[m+1][1];\n distance = Math.sqrt(dx*dx + dy*dy);\n\n //set shortestDistance and closestPoints to the first iteration\n</code></pre>\n\n<p>I don't understand this comment.</p>\n\n<pre><code> if (m == 0 &amp;&amp; i == 0)\n {\n shortestDistance = distance;\n closestPoint1 = \"(\" + points[0][0] + \",\" + points[0][1] + \")\";\n closestPoint2 = \"(\" + points[1][0] + \",\" + points[1][1] + \")\";\n</code></pre>\n\n<p>I suggest storing the numbers associated with the closest points, not a string.</p>\n\n<pre><code> }\n //then check if any further iterations have shorter distances\n else if (distance &lt; shortestDistance)\n</code></pre>\n\n<p>You are doing the same thing you did above. Use <code>||</code> to combine the two conditions</p>\n\n<pre><code> {\n shortestDistance = distance;\n closestPoint1 = \"(\" + points[i][0] + \",\" + points[i][1] + \")\";\n closestPoint2 = \"(\" + points[m+1][0] + \",\" + points[m+1][1] + \")\";\n }\n }\n }\n System.out.println(\"The shortest distance is: \" + shortestDistance);\n System.out.println(\"The closest points are \" + closestPoint1 + \" and \" + closestPoint2);\n } \n}\n</code></pre>\n\n<p>The whole thing would do better to split across several functions instead of all in one.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T21:38:07.320", "Id": "15831", "Score": "0", "body": "I've read before that variables should be declared as you say, but I've noticed that my professor has all of the variables declared at the top when she gives sample code. I'm not sure why." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T21:51:53.750", "Id": "15832", "Score": "0", "body": "@micah, some older languages required declaring all your variables at the top and some programmers have never stopped doing it. I usually take it as a sign that somebody doesn't care enough about code readability." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T21:02:05.320", "Id": "9946", "ParentId": "9943", "Score": "9" } } ]
{ "AcceptedAnswerId": "9945", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T20:44:14.767", "Id": "9943", "Score": "9", "Tags": [ "java", "homework", "computational-geometry", "clustering" ], "Title": "Finding points with the shortest distance" }
9943
<p><strong><em>Problem:</em></strong> <em>Find the intersection of two Object arrays without creating any new classes (no anonymous classes either) and without using any native Java classes in the solution (so no ArrayList implementations etc., but Object can be used)</em></p> <p>My solution:</p> <pre><code>public Object[] handleArrayIntersection(Object[] array1, Object[] array2) { if(array1.length == 0 || array2.length == 0){ return new Object[0]; } // the maximum possible number of intersections is the smaller array's size int maxPossibleLength = array1.length &lt; array2.length ? array1.length : array2.length; Object[] intersectionValues = new Object[maxPossibleLength]; int itemCount = 0; for(int i = 0; i &lt; array1.length; i++){ Object arr1Val = array1[i]; if(contains(array2, arr1Val) &amp;&amp; !contains(intersectionValues, arr1Val)){ intersectionValues[itemCount] = arr1Val; itemCount++; } } // reduce the array down to only contain the intersections Object[] intersection = new Object[itemCount]; for(int i = 0; i &lt; itemCount; i++){ intersection[i] = intersectionValues[i]; } return intersection; } public boolean contains(Object[] newArr, Object arr1Val) { boolean contains = false; for(int i = 0; i &lt; newArr.length; i++){ Object val = newArr[i]; if((val == null &amp;&amp; arr1Val == null) || (val != null &amp;&amp; val.equals(arr1Val))){ contains = true; break; } } return contains; } </code></pre> <p>I haven't tried to solve this type of problem for awhile and I am really curious what people think of this solution in terms of efficiency, robustness and readability. I arrived at this solution by using TDD (Test Driven Development), but I'm not including the test because I'm more interested in people reviewing the solution.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T23:33:24.710", "Id": "15835", "Score": "2", "body": "Except for renaming the parameters of contains(), this looks OK to me. I would also simply \"return true\" from inside the loop and \"return false\" after the loop completes, instead of keeping the `contains` variable around; it's not really serving much of a purpose." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T00:20:01.140", "Id": "15837", "Score": "0", "body": "@CarlManaster thanks. for the feedback. Anyone have ideas on how to optimize this code?" } ]
[ { "body": "<p>If you want to optimize you can : Use arrayCopy() from the System Class to create the final array and reduce variable. Here is my \"solution\" : </p>\n\n<pre><code>public static Object[] handleArrayIntersection(Object[] array1, Object[] array2) {\n Object[] dest;\n\n int itemCount = 0;\n Object[] intersect = new Object[array1.length &lt; array2.length ? array1.length : array2.length];\n\n for(int i = 0; i &lt; array1.length; i++) {\n Object arr1Val = array1[i];\n if(contains(array2, arr1Val) &amp;&amp; !contains(intersect, arr1Val)) {\n intersect[itemCount++] = arr1Val;\n }\n }\n\n dest = new Object[itemCount];\n if(itemCount &gt; 0) {\n System.arraycopy(intersect, 0, dest, 0, itemCount);\n }\n\n return dest;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T08:42:01.767", "Id": "9953", "ParentId": "9948", "Score": "3" } }, { "body": "<p>You should iterate through the smallest array. If array1 is very much larger than array2 then most of the elements are unlikely to be in array2 and the contains test is more likely to be false.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-20T09:57:37.907", "Id": "10177", "ParentId": "9948", "Score": "2" } } ]
{ "AcceptedAnswerId": "9953", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T23:04:23.313", "Id": "9948", "Score": "3", "Tags": [ "java", "optimization" ], "Title": "Intersection of Array Question, limited only to methods" }
9948
<p>I have written a game engine for the game <a href="http://en.wikipedia.org/wiki/Reversi" rel="nofollow">Reversi, also called Othello</a>. The game engine works not exactly like the official rules. For example it is possible to place "holes" on the board, places which can never hold a stone.</p> <p>The game engine works fine, I have only some problems with the command line interface which includes lots of IO. Another problem I couldn't solve is exception handling. I read, that in Haskell, exceptions are rarely used. Nevertheless I was unable to refactor them to pure code. I have placed comments to the functions where the exceptions occur.</p> <p>So, the main points which need review are:</p> <ol> <li>Exceptions</li> <li>How to handle errors in the program? Exceptions should not be used and type signatures like <code>x :: XXX -&gt; Either ErrorResult SuccessResult</code> look ugly.</li> <li>How to work with qualified imports? Are there style rules how to qualify them?</li> <li>It is inefficient to compute Game.possibleMoves more than one time per step. How to cache it during the steps? Should I save them to the Game data type?</li> <li>Is it possible to improve signatures like <code>x :: Game -&gt; XXX -&gt; IO Game</code>? Because there is no namespace for a data type, the data have have to be delivered explicitly. Thus, is there some syntactic sugar to do this?</li> <li>Code smells</li> </ol> <p>A sample game:</p> <pre><code>&gt; newGame 8 8 &gt; move F5 &gt; move D6 &gt; move C5 &gt; print -------- -------- -------- ---WB--- --BBBB-- ---W---- -------- -------- turn: White &gt; possibleMoves Possible moves: B4,B6,F4,F6 &gt; abort Game over! Black has won (5:2)! &gt; quit </code></pre> <p>The code is not yet documented and it contains about 450 lines of code. I hope, this means not to much work for a code review. ;)</p> <p>Main.hs</p> <pre><code>import qualified Data.Map as Map import qualified Data.List as List import qualified Data.List.Split as Split import qualified Data.Text as T import qualified Data.Array as A import qualified Data.Maybe as Maybe import qualified Text.Printf as Print import qualified Control.Exception as E import Control.Exception.Base import System.IO import Position import Board import Cell import Game import InputParser main :: IO () main = loop emptyGame &gt;&gt; return () loop :: Game -&gt; IO Game loop game = putStr "&gt; " &gt;&gt; hFlush stdout &gt;&gt; getLine &gt;&gt;= handleCommand game . splitCommand . trim handleCommand :: Game -&gt; (String, String) -&gt; IO Game handleCommand game (command, args) = case command of "quit" -&gt; return game "newGame" -&gt; createNewGame game args &gt;&gt;= loop "hole" -&gt; createHole game args &gt;&gt;= loop "move" -&gt; move game args &gt;&gt;= loop "abort" -&gt; abort game &gt;&gt;= loop "print" -&gt; printCommand game &gt;&gt;= loop "possibleMoves" -&gt; showPossibleMoves game &gt;&gt;= loop _ -&gt; putStrLn "command not found" &gt;&gt; loop game createNewGame :: Game -&gt; String -&gt; IO Game createNewGame game args | mode game /= GameOverMode = printError "there is already an active game" &gt;&gt; return game | otherwise = if canMove newGame then return newGame else calculatePass newGame where newGame = parseAs args gameParser $ \f -&gt; case f of (width, height, Nothing) -&gt; createGame width height (width, height, Just positions) -&gt; createGameWithConfig width height positions -- how to change error? createHole :: Game -&gt; String -&gt; IO Game createHole game args | mode game /= NewMode = printError "can't add hole area. there is no game yet or the game is already started'" &gt;&gt; return game | otherwise = if canMove newGame then return newGame else calculatePass newGame where newGame = parseAs args holeParser $ \f -&gt; case f of (from, to) -&gt; addHole' game from to addHole' game from to | containsCells (board game) from to = error "can't add hole. it is not empty'" | otherwise = addHole game from to -- how to change error? move :: Game -&gt; String -&gt; IO Game move game args = do bool &lt;- requireGameStarted game if bool then return game else if canMove newGame then return newGame else calculatePass newGame where newGame = parseAs args position $ \f -&gt; case f of pos -&gt; game `moveTo'` pos moveTo' game pos | notElem pos $ possibleMoves game = error "move not possible" | otherwise = game `moveTo` pos printCommand :: Game -&gt; IO Game printCommand game = do bool &lt;- requireGameStarted game if bool then return game else putStr (mkString game) &gt;&gt; putStrLn ("turn: " ++ show (curPlayer game)) &gt;&gt; return game where mkString = unlines . rows . table . board --table :: Board -&gt; A.Array (Int, Int) Char table (Board width height cells) = A.array ((1, 1), (height, width)) [((y, x), sign $ Map.findWithDefault EmptyCell (Position x y) cells) | y &lt;- [1 .. height], x &lt;- [1 .. width]] --rows :: A.Array (Int, Int) a -&gt; [[a]] rows arr = [[arr A.! (x, y) | y &lt;- [cLow .. cHigh]] | x &lt;- [rLow .. rHigh]] where ((rLow, cLow), (rHigh, cHigh)) = A.bounds arr abort :: Game -&gt; IO Game abort game = do bool &lt;- requireGameStarted game if bool then return game else calculateWinner (endGame game) showPossibleMoves :: Game -&gt; IO Game showPossibleMoves game = do bool &lt;- requireGameStarted game if bool then return game else putStrLn ("Possible moves: " ++ moves) &gt;&gt; return game where moves = List.intercalate "," (map show $ List.sort $ possibleMoves game) calculatePass :: Game -&gt; IO Game calculatePass game = if canMove passed then newGame else calculateWinner game where passed = passMove game newGame = putStrLn (show (curPlayer game) ++ " passes") &gt;&gt; return passed calculateWinner :: Game -&gt; IO Game calculateWinner game = putStrLn str &gt;&gt; return newGame where newGame = endGame game (white, black) = List.partition (== White) $ filter (/= Hole) $ Map.elems $ cells $ board newGame (numOfWhite, numOfBlack) = (length white, length black) winner = if numOfWhite &gt; numOfBlack then White else Black max' = max numOfWhite numOfBlack min' = min numOfWhite numOfBlack str = if numOfWhite == numOfBlack then "Game has ended in a draw." else Print.printf "Game over! %s has won (%d:%d)!" (show winner) max' min' requireGameStarted :: Game -&gt; IO Bool requireGameStarted (Game mode _ _) | mode /= NewMode &amp;&amp; mode /= ActiveMode = printError "game not started" &gt;&gt; return True | otherwise = return False trim :: String -&gt; String trim = T.unpack . T.strip . T.pack splitCommand :: String -&gt; (String, String) splitCommand str = splitAt index str where index = Maybe.fromMaybe (length str) $ List.elemIndex ' ' str printError :: String -&gt; IO () printError str = putStrLn ("Error!" ++ str) </code></pre> <p>InputParser.hs</p> <pre><code>module InputParser (parseAs, gameParser, holeParser, position) where import Text.ParserCombinators.Parsec import Control.Applicative import Data.Char import Game import Position parseAs :: String -&gt; Parser a -&gt; (a -&gt; Game) -&gt; Game parseAs input p f = case parse safeP "" input of Left err -&gt; error $ show err Right x -&gt; f x where safeP = spaces *&gt; p &lt;* spaces &lt;* eof number :: Parser Int number = read &lt;$&gt; many1 digit &lt;?&gt; "number" config :: Parser String config = many1 $ oneOf "WB#-," position :: Parser Position position = (\x y -&gt; Position (ord x - ord 'A' + 1) y) &lt;$&gt; upper &lt;*&gt; number gameParser :: Parser (Int, Int, Maybe String) gameParser = (,,) &lt;$&gt; number &lt;* spaces &lt;*&gt; number &lt;* spaces &lt;*&gt; optionMaybe config holeParser :: Parser (Position, Position) holeParser = (,) &lt;$&gt; position &lt;* char ':' &lt;*&gt; position </code></pre> <p>Game.hs</p> <pre><code>module Game ( Game(..), GameMode(..), emptyGame, createGame, createGameWithConfig, canMove, passMove, endGame, addHole, possibleMoves, moveTo) where import qualified Data.List.Split as Split import qualified Text.Printf as Print import qualified Data.List as List import qualified Data.Map as Map import Board import Position import Cell data GameMode = NewMode | ActiveMode | GameOverMode deriving (Show, Eq) data Game = Game { mode :: GameMode, board :: Board, curPlayer :: Cell } directions :: [Int -&gt; Int -&gt; Position] directions = [\x y -&gt; Position (x+1) y, \x y -&gt; Position (x+1) (y+1), \x y -&gt; Position x (y+1), \x y -&gt; Position (x-1) (y+1), \x y -&gt; Position (x-1) y, \x y -&gt; Position (x-1) (y-1), \x y -&gt; Position x (y-1), \x y -&gt; Position (x+1) (y-1)] startPositions :: [((Int, Int), Cell)] startPositions = [((0, 0), White), ((1, 0), Black), ((0, 1), Black), ((1, 1), White)] emptyGame :: Game emptyGame = Game GameOverMode (Board 0 0 Map.empty) Black createGame :: Int -&gt; Int -&gt; Game createGame w h = createGameWithConfig w h "" -- how to change error? createGameWithConfig :: Int -&gt; Int -&gt; String -&gt; Game createGameWithConfig width height str | not $ isValidSize width minWidth maxWidth = error "invalid width" | not $ isValidSize height minHeight maxHeight = error "invalid height" | otherwise = Game NewMode (Board width height $ Map.fromList cells) Black where cells = if null str then middleCells width height else calculateCells width height str middleCells :: Int -&gt; Int -&gt; [(Position, Cell)] middleCells width height = map (\((x, y), cell) -&gt; (Position (x+xMiddle) (y+yMiddle), cell)) startPositions where (xMiddle, yMiddle) = (width `div` 2, height `div` 2) -- how to change error? calculateCells :: Int -&gt; Int -&gt; String -&gt; [(Position, Cell)] calculateCells width height str | not $ isValidData str width height = error "invalid data" | otherwise = [ (Position x y, asCell c) | y &lt;- [1 .. height], x &lt;- [1 .. width], let c = rows !! (y-1) !! (x-1), isCell c] where rows = Split.splitOn "," str isValidData :: String -&gt; Int -&gt; Int -&gt; Bool isValidData str width height = length rows == height &amp;&amp; isRowValid `all` rows where rows = Split.splitOn "," str isRowValid row = length row == width &amp;&amp; (\c -&gt; isCell c || isEmpty c) `all` row isValidSize :: Int -&gt; Int -&gt; Int -&gt; Bool isValidSize int from to = int &gt;= from &amp;&amp; int &lt;= to &amp;&amp; int `mod` 2 == 0 possibleMoves :: Game -&gt; [Position] possibleMoves (Game _ board cur) = List.nub $ possiblePositions =&lt;&lt; cellsToProof where cellsToProof = Map.keys $ Map.filter (cur ==) $ cells board possiblePositions pos = id =&lt;&lt; map (checkDirection pos) directions checkDirection pos f | isCurPlayer = [] | otherwise = loop $ f (x newPos) (y newPos) where newPos = f (x pos) (y pos) isCurPlayer = not (isOfPlayer board newPos $ nextPlayer cur) isInvalid pos = not (board `isInRange` pos) || isOfPlayer board pos cur || board `isHole` pos loop pos | isInvalid pos = [] | board `isFree` pos = [pos] | otherwise = loop $ f (x pos) (y pos) -- how to change error? moveTo :: Game -&gt; Position -&gt; Game moveTo game @ (Game _ board cur) pos | notElem pos $ possibleMoves game = error $ "it is impossible to move to position " ++ show pos | otherwise = Game ActiveMode newBoard $ nextPlayer cur where positions = pos:(transform =&lt;&lt; directions) newBoard = transformBy board positions cur transform f = loop [] $ f (x pos) (y pos) where loop xs pos | isOfPlayer board pos $ nextPlayer cur = loop (pos:xs) $ f (x pos) (y pos) | isOfPlayer board pos cur = xs | otherwise = [] -- how to change error? addHole :: Game -&gt; Position -&gt; Position -&gt; Game addHole (Game mode board cur) from to | containsCells board from to = error $ Print.printf "can't add hole (%s:%s). It is not empty" (show from) (show to) | otherwise = Game mode newBoard cur where positions = [ Position x y | y &lt;- [y from .. y to], x &lt;- [x from .. x to]] newBoard = transformBy board positions Hole canMove :: Game -&gt; Bool canMove = not . null . possibleMoves nextPlayer :: Cell -&gt; Cell nextPlayer cur | cur == White = Black | otherwise = White passMove :: Game -&gt; Game passMove (Game mode board cur) = Game mode board $ nextPlayer cur endGame :: Game -&gt; Game endGame (Game _ board cur) = Game GameOverMode board cur </code></pre> <p>Board.hs</p> <pre><code>module Board ( Board(..), maxWidth, maxHeight, minWidth, minHeight, isFree, isInRange, isOfPlayer, isHole, containsCells, transformBy) where import Position import Cell import Data.Map data Board = Board { width :: Int, height :: Int, cells :: Map Position Cell } maxWidth = 26 :: Int maxHeight = 98 :: Int minWidth = 2 :: Int minHeight = 2 :: Int isFree :: Board -&gt; Position -&gt; Bool isFree board @ (Board _ _ cells) pos = board `isInRange` pos &amp;&amp; pos `notMember` cells isInRange :: Board -&gt; Position -&gt; Bool isInRange (Board width height _) (Position x y) = x &gt; 0 &amp;&amp; x &lt;= width &amp;&amp; y &gt; 0 &amp;&amp; y &lt;= height isOfPlayer :: Board -&gt; Position -&gt; Cell -&gt; Bool isOfPlayer (Board _ _ cells) pos player = player == findWithDefault EmptyCell pos cells isHole :: Board -&gt; Position -&gt; Bool isHole (Board _ _ cells) pos = Hole == findWithDefault EmptyCell pos cells containsCells :: Board -&gt; Position -&gt; Position -&gt; Bool containsCells (Board _ _ cells) from to | from == to = Hole /= findWithDefault Hole from cells | otherwise = any (Hole /=) cellsToCheck where cellsToCheck = [ findWithDefault Hole pos cells | y &lt;- [y from .. y to - 1], x &lt;- [x from .. x to - 1], let pos = Position x y] transformBy :: Board -&gt; [Position] -&gt; Cell -&gt; Board transformBy (Board w h cells) positions cell = Board w h newCells where newCells = foldl f cells positions f cells pos = insert pos cell cells </code></pre> <p>Cell.hs</p> <pre><code>module Cell ( Cell(..), sign, asCell, isEmpty, isCell) where data Cell = White | Black | Hole | EmptyCell deriving (Show, Eq) sign :: Cell -&gt; Char sign White = 'W' sign Black = 'B' sign Hole = '#' sign EmptyCell = '-' dataCells = map sign [White, Black, Hole] asCell :: Char -&gt; Cell asCell c | c == sign White = White | c == sign Black = Black | c == sign Hole = Hole isEmpty :: Char -&gt; Bool isEmpty c = c == sign EmptyCell isCell :: Char -&gt; Bool isCell c = c `elem` dataCells </code></pre> <p>Position.hs</p> <pre><code>module Position (Position(..)) where import Data.Char data Position = Position { x :: Int, y :: Int } deriving (Eq) instance Show Position where show (Position x y) = chr (ord 'A' + x - 1) : show y instance Ord Position where (Position x1 y1) `compare` (Position x2 y2) = toOrd $ if comp == 0 then y1 - y2 else comp where comp = x1 - x2 toOrd :: Int -&gt; Ordering toOrd x | x == 0 = EQ | x &gt; 0 = GT | otherwise = LT </code></pre> <hr> <p>After reading @Cygals post I overworked my code. Now all works fine. I did changes to two files:</p> <p>Main.hs</p> <pre><code>import qualified Data.Map as Map import qualified Data.List as List import qualified Data.List.Split as Split import qualified Data.Text as T import qualified Data.Array as A import qualified Data.Maybe as Maybe import qualified Text.Printf as Print import Control.Exception import Control.Exception.Base import System.IO import Position import Board import Cell import Game import InputParser main :: IO () main = loop emptyGame &gt;&gt; return () loop :: Game -&gt; IO Game loop game = putStr "&gt; " &gt;&gt; hFlush stdout &gt;&gt; getLine &gt;&gt;= handleInpuut game handleInpuut :: Game -&gt; String -&gt; IO Game handleInpuut game input | null command = loop game | command == "quit" = return game | otherwise = do handler &lt;- try $ handleCommand game splitted case handler of Left e -&gt; putStrLn ("Error: " ++ show (e :: ErrorCall)) &gt;&gt; loop game Right g -&gt; loop g where splitted @ (command, _) = splitCommand $ trim input handleCommand :: Game -&gt; (String, String) -&gt; IO Game handleCommand game (command, args) = case command of "newGame" -&gt; createNewGame game args "hole" -&gt; createHole game args "move" -&gt; move game args "abort" -&gt; abort game "print" -&gt; printCommand game "possibleMoves" -&gt; showPossibleMoves game _ -&gt; putStrLn "command not found" &gt;&gt; return game createNewGame :: Game -&gt; String -&gt; IO Game createNewGame game args | mode game /= GameOverMode = error "there is already an active game" | otherwise = if canMove newGame then return newGame else calculatePass newGame where newGame = parseAs args gameParser $ \f -&gt; case f of (width, height, Nothing) -&gt; createGame width height (width, height, Just positions) -&gt; createGameWithConfig width height positions createHole :: Game -&gt; String -&gt; IO Game createHole game args | mode game /= NewMode = error "can't add hole area. there is no game yet or the game is already started" | otherwise = if canMove newGame then return newGame else calculatePass newGame where newGame = parseAs args holeParser $ \f -&gt; case f of (from, to) -&gt; addHole' game from to addHole' game from to | containsCells (board game) from to = error "can't add hole. it is not empty" | otherwise = addHole game from to move :: Game -&gt; String -&gt; IO Game move game args = do requireGameStarted game if canMove newGame then return newGame else calculatePass newGame where newGame = parseAs args position $ \f -&gt; case f of pos -&gt; game `moveTo'` pos moveTo' game pos | notElem pos $ possibleMoves game = error "move not possible" | otherwise = game `moveTo` pos printCommand :: Game -&gt; IO Game printCommand game = do requireGameStarted game putStr $ mkString game putStrLn $ "turn: " ++ show (curPlayer game) return game where mkString = unlines . rows . table . board --table :: Board -&gt; A.Array (Int, Int) Char table (Board width height cells) = A.array ((1, 1), (height, width)) [((y, x), sign $ Map.findWithDefault EmptyCell (Position x y) cells) | y &lt;- [1 .. height], x &lt;- [1 .. width]] --rows :: A.Array (Int, Int) a -&gt; [[a]] rows arr = [[arr A.! (x, y) | y &lt;- [cLow .. cHigh]] | x &lt;- [rLow .. rHigh]] where ((rLow, cLow), (rHigh, cHigh)) = A.bounds arr abort :: Game -&gt; IO Game abort game = do requireGameStarted game calculateWinner (endGame game) showPossibleMoves :: Game -&gt; IO Game showPossibleMoves game = do requireGameStarted game putStrLn ("Possible moves: " ++ moves) return game where moves = List.intercalate "," (map show $ List.sort $ possibleMoves game) calculatePass :: Game -&gt; IO Game calculatePass game | canMove passed = newGame | otherwise = calculateWinner game where passed = passMove game newGame = putStrLn (show (curPlayer game) ++ " passes") &gt;&gt; return passed calculateWinner :: Game -&gt; IO Game calculateWinner game = putStrLn str &gt;&gt; return newGame where newGame = endGame game (white, black) = List.partition (== White) $ filter (/= Hole) $ Map.elems $ cells $ board newGame (numOfWhite, numOfBlack) = (length white, length black) winner = if numOfWhite &gt; numOfBlack then White else Black max' = max numOfWhite numOfBlack min' = min numOfWhite numOfBlack str = if numOfWhite == numOfBlack then "Game has ended in a draw." else Print.printf "Game over! %s has won (%d:%d)!" (show winner) max' min' requireGameStarted :: Game -&gt; IO () requireGameStarted (Game mode _ _ _) | mode /= NewMode &amp;&amp; mode /= ActiveMode = error "game not started" | otherwise = return () trim :: String -&gt; String trim = T.unpack . T.strip . T.pack splitCommand :: String -&gt; (String, String) splitCommand str = splitAt index str where index = Maybe.fromMaybe (length str) $ List.elemIndex ' ' str </code></pre> <p>Game.hs</p> <pre><code>module Game ( Game(..), GameMode(..), emptyGame, createGame, createGameWithConfig, canMove, passMove, endGame, addHole, moveTo) where import qualified Data.List.Split as Split import qualified Text.Printf as Print import qualified Data.List as List import qualified Data.Map as Map import Board import Position import Cell data GameMode = NewMode | ActiveMode | GameOverMode deriving (Show, Eq) data Game = Game { mode :: GameMode, board :: Board, curPlayer :: Cell, possibleMoves :: [Position] } directions :: [Int -&gt; Int -&gt; Position] directions = [\x y -&gt; Position (x+1) y, \x y -&gt; Position (x+1) (y+1), \x y -&gt; Position x (y+1), \x y -&gt; Position (x-1) (y+1), \x y -&gt; Position (x-1) y, \x y -&gt; Position (x-1) (y-1), \x y -&gt; Position x (y-1), \x y -&gt; Position (x+1) (y-1)] startPositions :: [((Int, Int), Cell)] startPositions = [((0, 0), White), ((1, 0), Black), ((0, 1), Black), ((1, 1), White)] emptyGame :: Game emptyGame = Game GameOverMode (Board 0 0 Map.empty) Black [] createGame :: Int -&gt; Int -&gt; Game createGame w h = createGameWithConfig w h "" createGameWithConfig :: Int -&gt; Int -&gt; String -&gt; Game createGameWithConfig width height str | not $ isValidSize width minWidth maxWidth = error "invalid width" | not $ isValidSize height minHeight maxHeight = error "invalid height" | otherwise = Game NewMode newBoard Black $ calculatePossibleMoves newBoard Black where newBoard = Board width height $ Map.fromList cells cells = if null str then middleCells width height else calculateCells width height str middleCells :: Int -&gt; Int -&gt; [(Position, Cell)] middleCells width height = map (\((x, y), cell) -&gt; (Position (x+xMiddle) (y+yMiddle), cell)) startPositions where (xMiddle, yMiddle) = (width `div` 2, height `div` 2) calculateCells :: Int -&gt; Int -&gt; String -&gt; [(Position, Cell)] calculateCells width height str | not $ isValidData str width height = error "invalid data" | otherwise = [ (Position x y, asCell c) | y &lt;- [1 .. height], x &lt;- [1 .. width], let c = rows !! (y-1) !! (x-1), isCell c] where rows = Split.splitOn "," str isValidData :: String -&gt; Int -&gt; Int -&gt; Bool isValidData str width height = length rows == height &amp;&amp; isRowValid `all` rows where rows = Split.splitOn "," str isRowValid row = length row == width &amp;&amp; (\c -&gt; isCell c || isEmpty c) `all` row isValidSize :: Int -&gt; Int -&gt; Int -&gt; Bool isValidSize int from to = int &gt;= from &amp;&amp; int &lt;= to &amp;&amp; int `mod` 2 == 0 calculatePossibleMoves :: Board -&gt; Cell -&gt; [Position] calculatePossibleMoves board cur = List.nub $ possiblePositions =&lt;&lt; cellsToProof where cellsToProof = Map.keys $ Map.filter (cur ==) $ cells board possiblePositions pos = id =&lt;&lt; map (checkDirection pos) directions checkDirection pos f | isCurPlayer = [] | otherwise = loop $ f (x newPos) (y newPos) where newPos = f (x pos) (y pos) isCurPlayer = not (isOfPlayer board newPos $ nextPlayer cur) isInvalid pos = not (board `isInRange` pos) || isOfPlayer board pos cur || board `isHole` pos loop pos | isInvalid pos = [] | board `isFree` pos = [pos] | otherwise = loop $ f (x pos) (y pos) moveTo :: Game -&gt; Position -&gt; Game moveTo game @ (Game _ board cur moves) pos | notElem pos moves = error $ "it is impossible to move to position " ++ show pos | otherwise = Game ActiveMode newBoard next $ calculatePossibleMoves newBoard next where positions = pos:(transform =&lt;&lt; directions) newBoard = transformBy board positions cur next = nextPlayer cur transform f = loop [] $ f (x pos) (y pos) where loop xs pos | isOfPlayer board pos next = loop (pos:xs) $ f (x pos) (y pos) | isOfPlayer board pos cur = xs | otherwise = [] addHole :: Game -&gt; Position -&gt; Position -&gt; Game addHole (Game mode board cur _) from to | containsCells board from to = error $ Print.printf "can't add hole (%s:%s). It is not empty" (show from) (show to) | otherwise = Game mode newBoard cur $ calculatePossibleMoves newBoard cur where positions = [ Position x y | y &lt;- [y from .. y to], x &lt;- [x from .. x to]] newBoard = transformBy board positions Hole canMove :: Game -&gt; Bool canMove = not . null . possibleMoves nextPlayer :: Cell -&gt; Cell nextPlayer cur | cur == White = Black | otherwise = White passMove :: Game -&gt; Game passMove (Game mode board cur _) = Game mode board next $ calculatePossibleMoves board next where next = nextPlayer cur endGame :: Game -&gt; Game endGame (Game _ board cur moves) = Game GameOverMode board cur moves </code></pre>
[]
[ { "body": "<ul>\n<li><strong>Handling of errors</strong> is done via <em>monads</em>, but you don't need to understand monads in their full glory to know how to <a href=\"http://book.realworldhaskell.org/read/error-handling.html\" rel=\"nofollow\">handle errors gracefully in Haskell</a>. Oh, and <a href=\"http://book.realworldhaskell.org/read/error-handling.html#errors.exceptions\" rel=\"nofollow\">Haskell has exceptions</a> (that's the same link as before), but it's not always the best way to do it.</li>\n<li><strong>Imports</strong> You can look at the guidelines of the HaskellWiki regarding <a href=\"http://www.haskell.org/haskellwiki/Import_modules_properly\" rel=\"nofollow\">imports</a>.</li>\n<li><strong>Signatures</strong> <code>x :: Game -&gt; XXX -&gt; IO Game</code> is explicit in a nice way, I don't believe it should be avoided.</li>\n<li><strong>Caching possibleMoves</strong> You can cache them in <code>Game</code> or something else, but you can also wonder how related it is to the issue of <a href=\"http://www.haskell.org/haskellwiki/Memoization\" rel=\"nofollow\">memoization</a>. </li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T10:22:01.093", "Id": "9958", "ParentId": "9950", "Score": "4" } } ]
{ "AcceptedAnswerId": "9958", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T23:57:25.460", "Id": "9950", "Score": "4", "Tags": [ "haskell" ], "Title": "Reversi (Othello) game engine + command line interface" }
9950
<p>I'm currently working with TornadoWeb but appear to have picked up a lot of bad habbits. I'd appreciate some feedback on the code below: </p> <pre><code>import tornado.ioloop import tornado.web import tornado.template #modules import auth import base import tag #pymongo import pymongo connection = pymongo.Connection("127.0.0.1", 27017) db = connection.prod loader = tornado.template.Loader("templates") class CustomerJS(tornado.web.RequestHandler): def get(self): ckey = self.get_secure_cookie('ckey') self.set_header("Content-Type", "Application/x-javascript") self.write(loader.load('js/customer.js').generate(ckey=ckey)) class Account(base.Base): def get(self): self.render('account.html', None) class Sites(base.Base): def get(self): self.render('sites.html', None) class Ads(base.Base): def get(self): self.render('ads.html', None) application = tornado.web.Application([ ## MAIN TABS # home (r"/version/3/home", Account), # ads (r"/version/3/ads", Ads), (r"/version/3/tags", tag.Tags), (r"/version/3/tagPost", tag.tagPost), (r"/version/3/tagRemove", tag.tagRemove), (r"/version/3/tagReportCookies", tag.tagReportCookies), (r"/version/3/s/(.*)", tornado.web.StaticFileHandler, {"path": "static"}), # JAVASCRIPT (r"/version/3/customer.js", CustomerJS), ], cookie_secret="COOKIESECRET=") if __name__ == "__main__": application.listen(9099) tornado.ioloop.IOLoop.instance().start() </code></pre>
[]
[ { "body": "<pre><code>import tornado.ioloop\nimport tornado.web\nimport tornado.template\n\n#modules\n</code></pre>\n\n<p>This comment doesn't say much, its fairly clear that anything starting with <code>import</code> is a module. It would be better to say something about why these three modules are grouped - eg, 'http/html modules'. But for a low number of imports, you mightn't bother with the comment at all.</p>\n\n<pre><code>import auth\nimport base\nimport tag\n\n#pymongo\n</code></pre>\n\n<p>Same again; this comment doesn't say anything that the code doesn't. This one you can just drop.</p>\n\n<pre><code>import pymongo\n</code></pre>\n\n<p>Put a blank line below your last <code>import</code>. Also, where are <code>auth</code>, <code>tag</code> and <code>base</code> from? They sound like your own support modules rather than part of a third-party package, in which case the imports should go <em>after</em> pymongo, rather than before, per PEP 8.</p>\n\n<pre><code>connection = pymongo.Connection(\"127.0.0.1\", 27017)\ndb = connection.prod\nloader = tornado.template.Loader(\"templates\")\nclass CustomerJS(tornado.web.RequestHandler):\n def get(self):\n ckey = self.get_secure_cookie('ckey')\n</code></pre>\n\n<p>Stick to either single or double quotes throughout your code, rather than swapping between them.</p>\n\n<pre><code> self.set_header(\"Content-Type\", \"Application/x-javascript\")\n self.write(loader.load('js/customer.js').generate(ckey=ckey))\n\n\nclass Account(base.Base):\n</code></pre>\n\n<p>If <code>base</code> is your own module, you should pick a better name for it.</p>\n\n<pre><code> def get(self):\n self.render('account.html', None)\n\nclass Sites(base.Base):\n def get(self):\n self.render('sites.html', None)\n\nclass Ads(base.Base):\n def get(self):\n self.render('ads.html', None)\n</code></pre>\n\n<p>These three classes differ only by one hard-coded string argument. I'm assuming these are going to be expanded a bit later, but even so - consider consolidating them. </p>\n\n<pre><code>application = tornado.web.Application([\n ## MAIN TABS\n # home\n</code></pre>\n\n<p>Drop this comment, its clear that its the home page from the next line.</p>\n\n<pre><code> (r\"/version/3/home\", Account),\n</code></pre>\n\n<p>Is there a reason why all of these strings are raw strings?</p>\n\n<pre><code> # ads\n</code></pre>\n\n<p>Does this comment really apply to the entire next block of code (including the bits dealing with <code>Tags</code> and <code>tagPost</code>, etc)? If it doesn't, the comment is not only redundant but actually <em>misleading</em>. </p>\n\n<pre><code> (r\"/version/3/ads\", Ads),\n (r\"/version/3/tags\", tag.Tags),\n (r\"/version/3/tagPost\", tag.tagPost),\n (r\"/version/3/tagRemove\", tag.tagRemove),\n (r\"/version/3/tagReportCookies\", tag.tagReportCookies),\n (r\"/version/3/s/(.*)\", tornado.web.StaticFileHandler, {\"path\": \"static\"}),\n</code></pre>\n\n<p>Why do you suddenly indent further from here?</p>\n\n<pre><code> # JAVASCRIPT\n</code></pre>\n\n<p>Put a blank line before this.</p>\n\n<pre><code> (r\"/version/3/customer.js\", CustomerJS),\n ], cookie_secret=\"COOKIESECRET=\")\n</code></pre>\n\n<p>You've passed a long list as the first argument to <code>Application</code>, and then a single string value as a second - but the way you've set it out, it could be mistaken as sending many arguments to <code>Application</code>. Better to do it this way:</p>\n\n<pre><code>Application(\n [ # Main tabs\n (r\"/version/3/home\", Account),\n (r\"/version/3/ads\", Ads),\n ...\n # Javascript\n (r\"/version/3/customer.js\", CustomerJS),\n ],\n cookie_secret=\"COOKIESECRET=\"\n)\n</code></pre>\n\n<p>Or something similar, to make it obvious what your code is actually doing.</p>\n\n<pre><code>if __name__ == \"__main__\":\n application.listen(9099)\n tornado.ioloop.IOLoop.instance().start()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-14T08:18:25.547", "Id": "10007", "ParentId": "9952", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T07:31:09.237", "Id": "9952", "Score": "2", "Tags": [ "python" ], "Title": "TornadoWeb Python" }
9952
<p>I was just looking at a standard scaffolded Rails controller spec, and tried to get it to use subject or let blocks, and failed miserably ... can subject or let tidy controller specs the same as it would a model spec?</p> <pre><code>require 'spec_helper' describe ProjectsController do def valid_attributes {} end def valid_session {} end before(:each) do @project = Project.create! valid_attributes end describe "GET index" do it "assigns all projects as @projects" do get :index, {}, valid_session assigns(:projects).should eq([@project]) end end describe "GET show" do it "assigns the requested project as @project" do get :show, {:id =&gt; @project.to_param}, valid_session assigns(:project).should eq(@project) end end #etc end </code></pre>
[]
[ { "body": "<p>Check <a href=\"https://codereview.stackexchange.com/a/695/12102\">the answer from Pavel Druzyak for a different question</a>. It answers your question as well. </p>\n\n<p>Your code can be refactored to this;</p>\n\n<pre><code>describe ProjectsController do\n let(:project) { Project.create! }\n\n describe \"GET index\" do\n before(:each) { get :index }\n it { should respond_with(:success) }\n it { should assign_to(:projects).with([project]) }\n end\n\n describe \"GET show\" do\n before(:each) { get :show, {:id =&gt; @project.to_param} }\n it { should respond_with(:success) }\n it { should assign_to(:projects).with(project) }\n end\nend\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-24T08:38:45.803", "Id": "10300", "ParentId": "9954", "Score": "3" } } ]
{ "AcceptedAnswerId": "10300", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T09:25:04.150", "Id": "9954", "Score": "2", "Tags": [ "ruby", "ruby-on-rails", "rspec" ], "Title": "Tidying scaffolded Rails controller spec with subject/let" }
9954
<p>I'm creating my first login process in CodeIgniter. I'm using the simpleloginsecure library for actual session management but I wrote the controller and model myself and I was hoping if you could see any flaws in it.</p> <p>My User_model Class</p> <pre><code>&lt;?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class User_model extends CI_Model { public function __construct() { parent::__construct(); } function login($email, $password) { if($this-&gt;simpleloginsecure-&gt;login($email, $password)) { return true; } return false; } } ?&gt; </code></pre> <p>My User Controller class</p> <pre><code>&lt;?php if(!defined('BASEPATH')) exit('No Direct script access allowed'); Class User extends CI_Controller { public function __construct() { parent::__construct(); $this-&gt;load-&gt;model('user_model'); } public function index() { if($this-&gt;session-&gt;userdata('logged_in')) { redirect('/user/dashboard/', 'location'); } else { $data['message'] = '&lt;p class="error"&gt;You need to be logged in to view the administration area&lt;/p&gt;'; $this-&gt;load-&gt;view('user/login', $data); } } public function dashboard() { if($this-&gt;session-&gt;userdata('logged_in')) { $data['title'] = 'Welcome'; $this-&gt;load-&gt;view('user/dashboard', $data); } else { $data['message'] = '&lt;p class="error"&gt;You need to be logged in to view the administration area&lt;/p&gt;'; redirect('/user/login/', 'location'); } } public function login() { if($this-&gt;session-&gt;userdata('logged_in')) { redirect('/user/dashboard/', 'location'); } $this-&gt;form_validation-&gt;set_rules('email', 'E-mail', 'trim|required|valid_email'); $this-&gt;form_validation-&gt;set_rules('password', 'Wachtwoord', 'trim|required|min_length[4]|max_length[32]'); if($this-&gt;form_validation-&gt;run() == FALSE) { $this-&gt;index(); } else { if($this-&gt;user_model-&gt;login($this-&gt;input-&gt;post('email'), $this-&gt;input-&gt;post('password'))) { redirect('/user/dashboard/', 'location'); } else { $this-&gt;index(); } } } public function logout() { $this-&gt;simpleloginsecure-&gt;logout(); redirect('/user/login/', 'location'); } } </code></pre>
[]
[ { "body": "<ol>\n<li>Simply use <code>return $this-&gt;simpleloginsecure-&gt;login($email, $password)</code> in the login method.</li>\n<li><code>redirect('/user/xxx')</code> is enough, since <code>location</code> is the default redirect type.</li>\n<li>Since you're doing a <code>redirect()</code>, <code>$data['message']</code>is probably \"dead code\" here. Use <a href=\"http://codeigniter.com/user_guide/libraries/sessions.html\" rel=\"nofollow\">CodeIgniter's Flashdata</a> instead.</li>\n<li><code>&lt;p class=\"error\"&gt;</code> should be handled in the view, the controller only needs to say there's an error. For example: <code>$data['message'] = array('error' =&gt; 'This is my error text');</code></li>\n<li>Trimming passwords is dangerous: what if my password starts with a space? Also, a space will look like a real character in an HTML password form, it makes no sense to trim it.</li>\n<li>When the validation fails, redirect to the login form and use flashdata to explain what got wrong.</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T13:19:11.540", "Id": "9967", "ParentId": "9966", "Score": "3" } } ]
{ "AcceptedAnswerId": "9967", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T12:59:03.427", "Id": "9966", "Score": "3", "Tags": [ "php", "security", "codeigniter" ], "Title": "Is this good login process in CodeIgniter?" }
9966
Microsoft Windows Azure Platform is a Microsoft cloud computing platform used to build, host and scale web applications through Microsoft data centers.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T13:39:57.620", "Id": "9969", "Score": "0", "Tags": null, "Title": null }
9969
The Actor model is a mathematical model of concurrent computation that treats "actors" as the universal primitives of concurrent digital computation: in response to a message that it receives, an actor can make local decisions, create more actors, send more messages, and determine how to respond to the next message received.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T13:40:40.943", "Id": "9971", "Score": "0", "Tags": null, "Title": null }
9971
<p>I was working on a syllable counting function for a text editor(this function is accurate enough). However, I would like to know if it is possible to optimize it, it already separated into another thread, but I would like to know if there is any kind of optimization that I can do with it to make it more efficient.</p> <pre><code>private static int SyllableCount(string word) { word = word.ToLower().Trim(); int count = System.Text.RegularExpressions.Regex.Matches(word, "[aeiouy]+").Count; if ((word.EndsWith("e") || (word.EndsWith("es") || word.EndsWith("ed"))) &amp;&amp; !word.EndsWith("le")) count--; return count; } </code></pre> <p>It uses regular expressions, something that <a href="http://www.dotnetperls.com/word-count" rel="nofollow">this</a> source mentions having poor performance in .net applications, is that the case? And if not, are there any other optimizations that I can perform on it?</p> <p>Anyway, it does not lag much, but my application does use around four threads already, just for keeping up with various text entry statistics, so now I'm just trying to shave the fat off so to speak.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T17:13:52.560", "Id": "15882", "Score": "1", "body": "Is it currently too slow? It sounds like youve just heard that it might be slow. There's no need to optimize it until you've figured out if it's actually too slow." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T13:59:05.070", "Id": "15892", "Score": "0", "body": "You might be interested to know that you're not the first trying to achieve syllabification. Here's an answer of mine on the subject: http://stackoverflow.com/questions/9096228/counting-syllables-in-a-word/9096723#9096723" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-14T19:06:22.003", "Id": "15966", "Score": "0", "body": "Of course, I already had the function, I wanted help optimizing it." } ]
[ { "body": "<p>If you're worried about regexp being slow, you could try a simple Split(): </p>\n\n<pre><code>int count = word.Split(new char[] { 'a','e','i','o','u','y' }, \n StringSplitOptions.RemoveEmptyEntries).Length ; \n</code></pre>\n\n<p>It would be easy to benchmark the difference. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T17:22:11.943", "Id": "15885", "Score": "0", "body": "This wouldn't count occurrences of two or more adjacent vowels as one \"syllable\", so \"sail\" would be counted incorrectly as having 2 syllables when the OP's algorithm would correctly count one." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T17:47:41.893", "Id": "15886", "Score": "0", "body": "@KeithS - fair point. Easily fixed by adding if (word.LastIndexOfAny(new char[] { 'a','e','i','o','u','y' } ) != word.Length - 1) count-- ; afterwards." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T17:19:38.507", "Id": "9973", "ParentId": "9972", "Score": "-1" } }, { "body": "<p>Well, Regex is going to be slow, by virtue of it being a very powerful, flexible engine that can't assume you'll never want to do something that a regex can achieve. This particular regex pattern is pretty simple (no lookbehinds, etc) but there will be some overhead inherent in Regex use which you can trim. You can iterate through the string and count occurrences of groups of vowels in linear time with very little overhead.</p>\n\n<pre><code>private static int SyllableCount(string word)\n{\n word = word.ToLower().Trim();\n bool lastWasVowel;\n var vowels = new []{'a','e','i','o','u','y'};\n int count;\n\n //a string is an IEnumerable&lt;char&gt;; convenient.\n foreach(var c in word)\n {\n if(vowels.Contains(c))\n {\n if(!lastWasVowel)\n count++;\n lastWasVowel = true;\n }\n else\n lastWasVowel = false; \n }\n\n if ((word.EndsWith(\"e\") || (word.EndsWith(\"es\") || word.EndsWith(\"ed\"))) \n &amp;&amp; !word.EndsWith(\"le\"))\n count--;\n\n return count;\n}\n</code></pre>\n\n<p>I'd A/B the above algorithm against the one you already have; you should see at least some performance increase. Notice that although this may well be faster as it does exactly what you want and doesn't see if you want to do anything else, it uses more LOC to achieve the same result. This is Regex's real power; powerful string analysis with very concise code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T17:24:12.623", "Id": "15887", "Score": "0", "body": "Actually, there are a few errors, but they will be easy to fix. Thanks for the answer" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T17:35:49.253", "Id": "15888", "Score": "0", "body": "Yeah I found a few in my first attempt. The code as edited should be correct." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T17:48:23.377", "Id": "15889", "Score": "0", "body": "It turns out that my method was faster, however your method was seems to be more accurate, thanks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T01:58:00.160", "Id": "15890", "Score": "2", "body": "Odd. the above code sample should behave identically to the regex-based algorithm." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-03-05T22:04:33.137", "Id": "297203", "Score": "0", "body": "awesome ty very much for this" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T17:20:43.880", "Id": "9974", "ParentId": "9972", "Score": "3" } } ]
{ "AcceptedAnswerId": "9974", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T17:10:02.880", "Id": "9972", "Score": "2", "Tags": [ "c#", "performance", ".net" ], "Title": "Syllable-counting function" }
9972
<p>i am testing an application that i wrote and want to test the solution my algorithm produces to a Monte carlo solution. I use the harddisk a lot and i was wondering if there was a solution that uses writing data to a file a lot less, since it is really slowing the process down.</p> <p>The solutions are computed on the nodes of a cluster and examined using this script ( that runs on a node): Parameter $1 is an outputfile that the program wrote.</p> <pre><code>file=$1 script=/home/hefke/ov_paper/scripts mv $file.out $file.out.old grep "Overlapscore:" $file.monte &gt; $file.grepped awk '/./{print $2}' $file.grepped &gt; $file.overlap print "$script/std_dev.sh $file.overlap &gt; $file.out" $script/std_dev.sh $file.overlap &gt; $file.out cat $file.analy &gt;&gt; $file.out cat "DONE" &gt;&gt; $file.out </code></pre> <p>Here is the script that collects the data on the main node. Analy and Monte files are my output files.</p> <pre><code>echo "Processing outputfiles for the mc_stdev_of_ov" script=/home/hefke/ov_paper/scripts curdir=`pwd` folder=filedata for file in `ls -1 $curdir/temp_output/$folder/*.analy| sed 's/\(.*\)\..*/\1/'|uniq` do echo $file $script/submitter.sh $curdir "processonefile.sh $file.out" done echo "$file.out now contains what stdtev spat out." cat $curdir/temp_output/$folder/*.out &gt;&gt; $curdir/temp_output/tmp.out awk -f keys.awk $curdir/temp_output/tmp.out &gt;&gt; table.out cat table.out </code></pre> <p>How can i optimize this procedure for speed?</p>
[]
[ { "body": "<p>You don't need to store in files between each command. Instead, just redirect the output:</p>\n\n<pre><code>$script/std_dev.sh &lt; &lt;(grep \"Overlapscore:\" $file.monte | awk '/./{print $2}') &gt; $file.out\n</code></pre>\n\n<p>The Bash Guide has an <a href=\"http://mywiki.wooledge.org/BashGuide/InputAndOutput\" rel=\"nofollow\">excellent article about I/O</a>.</p>\n\n<p>There's only one place where you write to tmp.out, and <code>awk</code> can take more than one file, so you can simplify those lines similarly:</p>\n\n<pre><code>awk -f keys.awk $curdir/temp_output/$folder/*.out\n</code></pre>\n\n<p>There's no <a href=\"http://partmaps.org/era/unix/award.html#uuk9letter\" rel=\"nofollow\">need to redirect to table.out and <code>cat</code>ing it afterwards</a>.</p>\n\n<p>You <a href=\"http://mywiki.wooledge.org/ParsingLs\" rel=\"nofollow\">shouldn't use <code>ls</code> in scripts</a>; you can simply loop over a glob:</p>\n\n<pre><code>for file in $curdir/temp_output/$folder/*.analy\n file=\"${file%.*}\" # Remove extension\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-14T13:28:35.453", "Id": "15946", "Score": "0", "body": "when i use script/std_dev.sh < <(grep \"Overlapscore:\" $file.monte | awk '/./{print $2}') > $file.out, it tells me :Missing name for redirect." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-14T13:50:11.040", "Id": "15949", "Score": "0", "body": "Are you sure you're [actually](http://www.linuxjournal.com/article/2156#comment-288) running [Bash](http://www.mantisbt.org/forums/viewtopic.php?f=3&t=6765)?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-15T06:44:14.380", "Id": "15994", "Score": "0", "body": "l0b0 you sir are a genius. as a matter of fact i am not :(. I am running the cshell. Thank you very much for your answer anyways :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-15T08:03:23.457", "Id": "15995", "Score": "0", "body": "not relating to the question any more, but is there a way to group commands with the () as in bash in cshell?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-15T08:53:19.400", "Id": "15998", "Score": "0", "body": "Sorry @tarrasch, csh is one beast I've never had to handle, so I really don't know. Maybe food for a separate question on [USE](http://unix.stackexchange.com/)?" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T15:09:51.553", "Id": "9983", "ParentId": "9977", "Score": "1" } }, { "body": "<p>It's not related, but please don't mind if I use an \"answer\" to just comment : it seems I can't comment, maybe because I don't have enough points yet to do so... </p>\n\n<p>Tarrasch, if you still use csh for your shell, please do not script in it.</p>\n\n<p>Please read: <a href=\"http://www.faqs.org/faqs/unix-faq/shell/csh-whynot/\" rel=\"nofollow\">http://www.faqs.org/faqs/unix-faq/shell/csh-whynot/</a></p>\n\n<p>Use instead sh, bash (or even ksh). And better to stick to sh-only because that's what's all unix system rely on (and rc scripts, for example, are based on).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-06T16:45:39.953", "Id": "19361", "ParentId": "9977", "Score": "2" } } ]
{ "AcceptedAnswerId": "9983", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T14:42:24.380", "Id": "9977", "Score": "1", "Tags": [ "optimization", "bash" ], "Title": "optimizing a bash script chain - speed suggestions?" }
9977
<p>I use Ruby 1.8.7. I have a method which selects records according to the item that I pass to the method.</p> <p>In my opinion, the code is not DRY. Could somebody offer suggestions on refactoring it to make it shorter?</p> <pre><code>def get_record (id,item) case item when "category" @temp = Category.find(id) when "status" @temp = Status.find(id) when "industry" @temp = Industry.find(id) end return @temp.name if @temp end </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T13:58:37.980", "Id": "15898", "Score": "0", "body": "I'd say the code is a sample of bad programming, but I fail to see the relation with DRY principles." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T14:01:38.117", "Id": "15899", "Score": "0", "body": "What the method should return when @temp is nil?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T14:17:40.093", "Id": "15900", "Score": "0", "body": "before I pass Item i m checking it for nil? and empty string." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T14:25:13.647", "Id": "15901", "Score": "0", "body": "I aagree with you Ingenu , but code leading to bugs and anty dry principles :)" } ]
[ { "body": "<p>You want to use <code>classify</code> and <code>constantize</code>:</p>\n\n<pre><code>require 'set'\nAUTHORIZED = Set[Product, Status, Industry]\ndef get_record(id, item)\n model = item.classify.constantize\n raise \"Go away, hacker\" unless AUTHORIZED.include? model\n model.find(id).name\nend\n</code></pre>\n\n<p>Be careful about security, as without the unless this will access any class in your system. This is just an example.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T14:32:17.947", "Id": "15909", "Score": "0", "body": "Marc-Andrรฉ Lafortune, incase this => CLASSES.fetch(item.to_sym).find(id) will be nil ? maybe is better to use CLASSES.fetch(item.to_sym).find(id).name rescue \"\" ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-14T14:23:06.660", "Id": "15950", "Score": "0", "body": "`find(id)` will raise an exception if the record can not be found. Use `find_by_id` if you want `nil` in those cases." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T14:11:10.937", "Id": "9981", "ParentId": "9978", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T13:53:15.487", "Id": "9978", "Score": "3", "Tags": [ "ruby" ], "Title": "Selecting records according to an item" }
9978
<p>All I want do to is simply get the result of how long (in seconds) the PHP takes to process the SQL query. Am I on a right track? Is my code correct to get the result I want?</p> <pre><code>&lt;?php $con = mysql_connect("localhost","root",""); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("test3", $con); $start = microtime(TRUE); $result = mysql_query("SELECT * FROM `test` ORDER BY `test`.`test2` DESC LIMIT 0,100"); echo "&lt;table border='1'&gt; &lt;tr&gt; &lt;th&gt;ID&lt;/th&gt; &lt;th&gt;test1&lt;/th&gt; &lt;th&gt;test2&lt;/th&gt; &lt;th&gt;test3&lt;/th&gt; &lt;th&gt;test4&lt;/th&gt; &lt;/tr&gt;"; while($row = mysql_fetch_array($result)) { echo "&lt;tr&gt;"; echo "&lt;td&gt;" . $row['ID'] . "&lt;/td&gt;"; echo "&lt;td&gt;" . $row['test1'] . "&lt;/td&gt;"; echo "&lt;td&gt;" . $row['test2'] . "&lt;/td&gt;"; echo "&lt;td&gt;" . $row['test3'] . "&lt;/td&gt;"; echo "&lt;td&gt;" . $row['test4'] . "&lt;/td&gt;"; echo "&lt;/tr&gt;"; } echo "&lt;/table&gt;"; $end = microtime(TRUE); $sqlTime = $end - $start; mysql_close($con); echo $sqlTime ?&gt; </code></pre>
[]
[ { "body": "<ol>\n<li>Yes, microtime is designed to be used for this. The PHP documentation mentions this <a href=\"http://www.php.net/manual/en/function.microtime.php\" rel=\"nofollow\">use case for <code>microtime()</code></a>.</li>\n<li>Consider putting this into a loop and print out the average result: if the measured time is too small, you can't provide a reliable estimation.</li>\n<li>Concerning the MySQL request: you should <a href=\"http://www.php.net/manual/en/mysqlinfo.api.choosing.php\" rel=\"nofollow\">switch to mysqli or PDO</a>.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T15:44:46.187", "Id": "15912", "Score": "0", "body": "Thanks, for the connection advice. I will change that, but I am still concerned whether `$end = microtime (TRUE)` is the right place to have? Or should I put it after the sql query?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T15:47:21.300", "Id": "15913", "Score": "0", "body": "It simply depends on what you want to measure: if it's simply MySQL, put it at the end, and if you want to include PHP processing, keep it there." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T15:36:41.500", "Id": "9986", "ParentId": "9985", "Score": "2" } } ]
{ "AcceptedAnswerId": "9986", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T15:15:00.403", "Id": "9985", "Score": "2", "Tags": [ "php", "mysql" ], "Title": "Calculating SQL query processing" }
9985
<p>i have 3 method which do almost the same thing,they different models to achieve the same goal.I did small refactoring but its still not looks like ruby,can we improve it? Thanks in advance. </p> <p>after: </p> <pre><code>def get_list(id,list_name,attribute_id,attribute,locale_string) map={ "resentact" =&gt; ResenAct }, "stageact" =&gt; StageAct , "payact" =&gt; PayAct" } @temp="" @list=map[list_name.downcase].find(:all, :conditions =&gt; {'id' =&gt; "# {id}".chop_space}) @list.each do |item| @temp = @temp + get_data(item.attribute_id,item) + " " + item.attribute + " " + locale_string+ ", " end return @temp.pop(2) if @temp.length &gt; 1 end </code></pre> <p>method call : get_list(id,payact,payact_id,date,"some_string")</p> <p>before:</p> <pre><code> def get_resentact_list(id) @temp="" @resentacts=ResentAct.find(:all, :conditions =&gt; {'product_id' =&gt; "#{id}".chop_space}) @resentacts.each do |item| @temp = @temp + get_data(item.shop_id,"resentact") + " " + item.cost.to_s + " " + "string1" + ", " end @temp = @temp[0,@temp.length-2] if @temp.length &gt; 1 return @temp </code></pre> <p>end </p> <pre><code> def get_stageact_list(id) @temp="" @stageacts=StageAct.find(:all, :conditions =&gt; {'product_id' =&gt; "#{id}".chop_space}) @stageacts.each do |item| @temp = @temp + "string1" + ": " + get_data(item.type_id,"type") + ", " + "str2" + ": " + item.summ + " " + "str3" + ", " end @temp = @temp[0,@temp.length-2] if @temp.length &gt; 1 return @temp end def get_payact_list(id) @temp="" @payacts=PayAct.find(:all, :conditions =&gt; {'product_id' =&gt; "#{id}".chop_space}) @payacts.each do |item| @temp = @temp + "str1" + ": " + item.date + ", " + "str2" + ": " + item.summ + " " + "str3" + ", " end @temp = @temp[0,@temp.length-2] if @temp.length &gt; 1 return @temp end </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-19T06:06:54.623", "Id": "16151", "Score": "1", "body": "1. please re-format your code. 2. please provide test code." } ]
[ { "body": "<pre><code>def get_payact_list(id) \n ## Dont use class instance variables ( prefixed with @ ) for method scoped variables\n @temp=\"\" # temp = \"\"\n ## In this case, you dont need the temporary variable, but lets keep it, but turn it into an array.\n # temp = [] \n\n ## No need for the temp variable here, and still using class instance variables.\n @payacts=PayAct.find(:all, :conditions =&gt; {'product_id' =&gt; \"#{id}\".chop_space})\n @payacts.each do |item|\n # PayAct.find(:all, :conditions =&gt; {'product_id' =&gt; \"#{id}\".chop_space}).each do |item|\n\n @temp = @temp + \"str1\" + \": \" + item.date + \", \" + \"str2\" + \": \" + item.summ + \" \" + \"str3\" + \", \"\n ## Lets simply push each item onto the array.\n ## While we are at it, we remove the trailing comma string. \n # temp &lt;&lt; \"str1\" + \": \" + item.date + \", \" + \"str2\" + \": \" + item.summ + \" \" + \"str3\"\n\n end\n # No need to mangle the end of the string, as we can simply join the temp array with a comma, which will not add to the end.\n @temp = @temp[0,@temp.length-2] if @temp.length &gt; 1\n # temp.join \", \"\n\n # no need for an explicit return. Ruby will return the value of the last expression.\n return @temp\nend\n</code></pre>\n\n<p>Complete example, without changing too much.</p>\n\n<pre><code>def get_payact_list(id) \n temp = [] \n PayAct.find(:all, :conditions =&gt; {'product_id' =&gt; \"#{id}\".chop_space}).each do |item|\n temp &lt;&lt; \"str1\" + \": \" + item.date + \", \" + \"str2\" + \": \" + item.summ + \" \" + \"str3\"\n end\n temp.join \", \" # is implicitly returned.\nend\n</code></pre>\n\n<p>We can do away with the temp variable by using collect() instead of each() and pushing to an array.</p>\n\n<pre><code>def get_payact_list(id) \n list = PayAct.find(:all, :conditions =&gt; {'product_id' =&gt; \"#{id}\".chop_space}).collect { |item|\n\n \"str1\" + \": \" + item.date + \", \" + \"str2\" + \": \" + item.summ + \" \" + \"str3\" \n } \n list.join \", \"\nend \n</code></pre>\n\n<p>Lets go the whole way, here are our new methods</p>\n\n<p>This still looks and feels like duplication, but without a bit more \nmetaprogramming than I want to go into right now, it will do.\nAt least the separate concerns are factored out.</p>\n\n<pre><code> def get_payact_list id \n format_act_list PayAct.find_by_product_id(id).collect { |item| \n [item.date, item.summ]\n }\n end\n\n # Note: the get_data method should be encapsulated on the item, leaving as is for now.\n def get_stageact_list id \n format_act_list StageAct.find_by_product_id(id).collect { |item| \n [ get_data(item.type_id,\"type\"), item.summ ] \n }\n end\n\n def get_resentact_list id\n format_act_list ResentAct.find_by_product_id(id).collect { |item| \n [ get_data(item.shop_id,\"resentact\"), item.cost ]\n }\n end\n\n\n def format_act_list list\n list.collect { |item| format_tuple(item) }.join ', '\n end\n\n # Takes an array and correctly formats the output\n # Ideally this would live in a presenter or a view. \n def format_tuple tuple \n \"str1: %s, str2: %s str3\" % [ tuple[0], tuple[1] ]\n end\n</code></pre>\n\n<p>And this is the supporting code.</p>\n\n<pre><code>class Act\n # I've moved this common finder method up the (fake) chain of inheritance I invented.\n # It could also live in each of the child objects i.e ( PayAct StageAct ResentAct )\n def self.find_by_product_id (product_id)\n self.find(:all, :conditions =&gt; {'product_id' =&gt; \"#{product_id}\".chop_space}) \n end\nend\n\nclass PayAct &lt; Act;end\nclass StageAct &lt; Act; end\nclass ResentAct &lt; Act; end\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-14T01:53:06.773", "Id": "10004", "ParentId": "9987", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T16:44:42.807", "Id": "9987", "Score": "1", "Tags": [ "ruby" ], "Title": "refactor ruby method" }
9987
<p>My problem is the following: I wrote a method, which counts words and returns a hash. There is a Ruby idiom which was found by me in some of the forums discussions, which I don't understand.</p> <p>Here is the whole code:</p> <pre><code>text = "bla bla blahh blahh" def count_words(string) inp = string.downcase.scan(/\b[\'a-z]+\b/i).inject(Hash.new 0){|c,w| c[w]+=1;c } return inp end puts count_words(text) </code></pre> <p>Here is the idiom: <code>inject(Hash.new 0){|c,w| c[w]+=1;c }</code></p> <p>My concrete questions are the following:</p> <p>1) How it understands when we should add 1 to the particular key?</p> <p>2) As far as I understand "inject" method, "c" is some sort of counter. So how does it happen that we write c[w]?</p>
[]
[ { "body": "<ol>\n<li><p>It is about <code>inject</code> initial value when you give <code>Hash.new(0)</code>\nand call <code>c[w] += 1</code> in block it is expanded to <code>c[w] = c[w] + 1</code> as we said\nto <code>Hash</code> initializer if it has no key then key will set to <code>0</code> when\nfirst appeared.</p></li>\n<li><p><code>c</code> here is an accumulator and instance of <code>inject</code> initial value.\naccumulator value will be set to return value of the block after\nevery turn. we are returning <code>c</code> because of this. it can be type of\nany object. <code>(1..10).inject(0) {|a,x| a + x }</code> for example it is\n<code>Fixnum</code> here.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T20:33:19.900", "Id": "15923", "Score": "0", "body": "thanks, but it's still unclear for me how can we use accumulator in the case different from working with a Fixnum object?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T20:36:57.487", "Id": "15924", "Score": "0", "body": "this is a good [blog post](http://blog.jayfields.com/2008/03/ruby-inject.html) about `inject`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T20:11:34.553", "Id": "9992", "ParentId": "9991", "Score": "2" } } ]
{ "AcceptedAnswerId": "9992", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T19:29:15.850", "Id": "9991", "Score": "1", "Tags": [ "ruby", "strings" ], "Title": "Words counter with a hash" }
9991
<p>From the Factor wiki:</p> <blockquote> <p>Factor is an experiment to build a modern, useful concatenative language with strong abstraction capabilities and good support for interactive development </p> </blockquote> <p>To get started, the Factor compiler can be found at <a href="http://factorcode.org/" rel="nofollow">factorcode.org</a>.</p> <p>More information about Factor can be found at <a href="http://concatenative.org/wiki/view/Factor" rel="nofollow">the wiki</a>.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T21:33:57.760", "Id": "9996", "Score": "0", "Tags": null, "Title": null }
9996
Factor is a concatenative programming language that is influenced by Forth, Joy and Lisp.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T21:33:57.760", "Id": "9997", "Score": "0", "Tags": null, "Title": null }
9997
<p>I wrote a string escaping function in C, and I'm trying to rewrite it to Haskell. The C version, along with comments explaining why it does what it does, <a href="https://github.com/joeyadams/haskell-libpq/blob/copy-from/cbits/escape-copy.c#L39" rel="nofollow">can be found on GitHub</a>.</p> <p>Here's a naรฏve implementation based on <a href="http://hackage.haskell.org/packages/archive/bytestring/latest/doc/html/Data-ByteString.html#v%3aconcatMap" rel="nofollow"><code>Data.ByteString.concatMap</code></a>:</p> <pre><code>{-# LANGUAGE ViewPatterns #-} import Data.Bits import Data.ByteString (ByteString) import Data.ByteString.Char8 () import Data.ByteString.Internal (c2w, w2c) import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as L escapeCopyBytea :: ByteString -&gt; ByteString escapeCopyBytea = B.concatMap f where f (w2c -&gt; '\\') = B.replicate 4 (c2w '\\') f c | c &gt;= 32 &amp;&amp; c &lt;= 126 = B.singleton c f c = B.pack [ c2w '\\' , c2w '\\' , c2w '0' + ((c `shiftR` 6) .&amp;. 0x7) , c2w '0' + ((c `shiftR` 3) .&amp;. 0x7) , c2w '0' + (c .&amp;. 0x7) ] mapChunks :: (ByteString -&gt; ByteString) -&gt; L.ByteString -&gt; L.ByteString mapChunks f = L.fromChunks . map f . L.toChunks main :: IO () main = L.getContents &gt;&gt;= L.putStr . mapChunks escapeCopyBytea </code></pre> <p>I'd expect this to be a few times slower than the C version. Nope, it is <strong>125 times slower</strong> than the C version.</p> <p>Then, I tried using <a href="http://hackage.haskell.org/package/blaze-builder" rel="nofollow">blaze-builder</a>:</p> <pre><code>import Blaze.ByteString.Builder import Data.Bits import Data.Monoid (mappend, mconcat, mempty) import Data.ByteString (ByteString) import Data.Word (Word8) import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as L writeBackslash :: Write writeBackslash = writeWord8 92 escape1 :: Word8 -&gt; Builder escape1 92 = fromWrite $ writeBackslash `mappend` writeBackslash `mappend` writeBackslash `mappend` writeBackslash escape1 c | c &gt;= 32 &amp;&amp; c &lt;= 126 = fromWrite $ writeWord8 c | otherwise = fromWrite $ writeBackslash `mappend` writeBackslash `mappend` writeWord8 (48 + ((c `shiftR` 6) .&amp;. 0x7)) `mappend` writeWord8 (48 + ((c `shiftR` 3) .&amp;. 0x7)) `mappend` writeWord8 (48 + (c .&amp;. 0x7)) escapeCopyBytea2 :: ByteString -&gt; Builder escapeCopyBytea2 = B.foldl' f mempty where f b c = b `mappend` escape1 c main :: IO () main = L.getContents &gt;&gt;= L.putStr . toLazyByteString . mconcat . map escapeCopyBytea2 . L.toChunks </code></pre> <p>This made a difference. It's even slower, 300 times slower than the C version. I thought blaze-builder was supposed to be really fast!</p> <p>Simply summing bytes, by folding over the input in a similar fashion as I do above, is reasonably fast (takes 5 times longer than the C version of the escaping code):</p> <pre><code>import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as L import Data.List (foldl') main :: IO () main = L.getContents &gt;&gt;= print . foldl' (+) 0 . map (B.foldl' (+) 0) . L.toChunks </code></pre> <p>What can I do to make this escaping function faster? Is it possible to get anywhere near the performance of C here, or is C (or perhaps working with <code>Ptr</code> or <code>Addr#</code> directly and doing it the C way) the only viable option to make this efficient?</p> <p><strong>Edit:</strong> I wrote a much faster implementation and <a href="https://github.com/joeyadams/haskell-concatMapWrite/" rel="nofollow">put it on GitHub</a>. However, it uses a lot of ugly buffer manipulation. I'd still like to know if there's a simpler way to escape bytes in Haskell that isn't slow.</p>
[]
[ { "body": "<p>Whew, this is quite a tricky one. The main problem here is that you really, really need to keep Haskell from allocating anything in the relatively spacious inner loop. Otherwise, you are looking at a dozen bytes going through the garbage collector for every byte you escape.</p>\n\n<p>As you note, blaze-builder has a reputation for being fast, mainly for being pretty good at this. Let's start off with an explanation why that is. Here's roughly how a <code>Builder</code> is defined (see <a href=\"http://hackage.haskell.org/packages/archive/blaze-builder/latest/doc/html/Blaze-ByteString-Builder-Internal-Types.html\" rel=\"nofollow\">Blaze.ByteString.Builder.Internal.Types</a>):</p>\n\n<pre><code>newtype Builder = Builder (forall r. BuildStep r -&gt; BuildStep r)\nnewtype BuildStep a = BufRange -&gt; IO (BuildSignal a)\ndata BufRange a = BufRange !(Ptr Word8) !(Ptr Word8)\n</code></pre>\n\n<p>The compiler will replace all <code>newtype</code> wrappers with simple \"casts\", and un-box <code>BufRange</code> where possible. So this means that, say, your <code>escape1</code> function would actually have an after-optimization type closer to:</p>\n\n<pre><code>escape1 :: Word8 -&gt; (BufRange -&gt; IO (BuildSignal a)) -&gt; BufRange -&gt; IO (BuildSignal a)\n</code></pre>\n\n<p>So this actually just takes the pointers from <code>BufRange</code> to write data using the <code>IO</code> monad, then finally calls the continuation. Ideally, we even know the continuation in question and can jump directly to the code. At no point does this require heap-allocation, everything gets nicely optimized out.</p>\n\n<p>So, what's the problem in your case? The trouble is the \"glue code\". Let us look at the source of <code>ByteString</code>'s <a href=\"http://hackage.haskell.org/packages/archive/bytestring/latest/doc/html/src/Data-ByteString.html#foldl\" rel=\"nofollow\"><code>foldl</code></a>, with some additional type annotations:</p>\n\n<pre><code>lgo :: Builder -&gt; Addr# -&gt; Addr# -&gt; IO Builder\nlgo !z !p !q | p == q = return z\n | otherwise = do c &lt;- peek p\n lgo (f z c) (p `plusPtr` 1) q\n</code></pre>\n\n<p>For every byte, this worker loop forces <code>f</code> in order to get the new \"accumulated value\". Unfortunately, that's a pretty bad idea here, as our accumulator is a <code>Builder</code> - a closure (as we saw above). Therefore this will actually allocate a huge list of closures, but not start producing anything of value until the very end.</p>\n\n<p>So, how to improve this? Remember again that our <code>f</code> has type <code>... -&gt; BuildStep r -&gt; BuildStep r</code> somewhere deep down. We would actually like to pass <code>lgo</code> as the <code>BuildStep</code> continuation, so after inlining it becomes a simple jump. We also don't really need the accumulation parameter, as the <code>Builder</code> is taking care of accumulating its result by itself.</p>\n\n<p>Going through with this, we actually get a lazy right fold:</p>\n\n<pre><code>lgo :: Addr# -&gt; Addr# -&gt; BuildStep r -&gt; BuildStep r\nlgo !p !q | p == q = v\n | otherwise = f (inlinePerformIO (peek p)) (lgo (p `plusPtr` 1) q)\n</code></pre>\n\n<p>(Note I also removed the <code>IO</code> by using <code>inlinePerformIO</code>, which might be unsafe in other usage scenarios, as any addresses escaping due to lazy evaluation might point to a garbage-collected buffer later!)</p>\n\n<p>The type signature looks a lot better now - and from my testing this actually performs roughly twice as fast as the original version. Where does the rest of the performance get lost? Well, a look at the Core shows code like</p>\n\n<pre><code>lgo = \\p q -&gt; case p == q of\n True -&gt; \\r -&gt; let ... in \\stp -&gt; ...\n False -&gt; \n</code></pre>\n\n<p>This means that GHC is generating a lot of partially-applied functions - primarily because the optimizer doesn't want to lose sharing in case we want to call <code>lgo</code> with the same <code>p</code> and <code>q</code>, but different <code>BuildSteps</code> (which we never will, but GHC can't prove that).</p>\n\n<p>So we need to force GHC to use higher arity for this function's implementation. Unfortunately, I am somewhat out of ideas how to accomplish that in an elegant way. So here's the manual solution -- writing our lambdas out at the top of the expression:</p>\n\n<pre><code>foldBuilder :: (Word8 -&gt; Builder) -&gt; B.ByteString -&gt; Builder\nfoldBuilder f (PS x s l) =\n fromBuildStepCont $ \\cont range -&gt;\n withForeignPtr x $ \\ptr -&gt; do\n let lgo !p !q !range'\n | p == q = cont range'\n | otherwise = do\n c &lt;- peek p\n let p' = p `plusPtr` 1\n step = unBuilder (f c) (BuildStep $ lgo p' q)\n runBuildStep step range'\n lgo (ptr `plusPtr` s) (ptr `plusPtr` (s+l)) range\n</code></pre>\n\n<p>I get decent performance out of this version here, and I suppose it's <em>slightly</em> better than implementing it completely by hand. It also happens to not require <code>inlinePerformIO</code> at all any more, which is a nice plus.</p>\n\n<p>Code can be found at <a href=\"https://github.com/scpmw/haskell-concatMapWrite/blob/master/escapeCopyBytea2.hs\" rel=\"nofollow\">GitHub</a>. I hope this helps in some way :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-16T20:04:48.263", "Id": "16064", "Score": "0", "body": "Neat, thanks! It runs in only 2 seconds on my test case (slower than my version, but at least it's simpler). However, it produces the wrong output when fed a hundred megabytes of data from /dev/urandom (I'm still troubleshooting). Also, I don't think using `c2w` instead of magic numbers like `92` and `48` impacts performance, but I could be wrong." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-16T20:50:29.267", "Id": "16067", "Score": "1", "body": "The problem appears to be premature garbage collection. If I touch all the input chunks at the end (leaking memory), the program produces the correct result." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-16T20:56:59.040", "Id": "16068", "Score": "0", "body": "Just add `touchForeignPtr x` after the peek. It fixes the problem, and does not affect performance." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-17T13:36:51.193", "Id": "16081", "Score": "0", "body": "Interesting. I thought `withForeignPtr` was a bit more robust than that... I'll have to investigate more sometime." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-17T14:33:03.493", "Id": "16082", "Score": "0", "body": "The problem is that `withForeignPtr` simply touches the foreign pointer after the inner computation completes. Accesses to `ptr` afterward may be invalidated by garbage collection. `runBuildStep` sometimes returns a continuation (`BufferFull` or `InsertByteString`) which is called outside of `withForeignPtr`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-17T18:53:23.447", "Id": "16096", "Score": "0", "body": "Well, yes - but why is that a problem? If I read the [source code](https://github.com/ghc/ghc/blob/master/compiler/codeGen/CgPrimOp.hs#L195) correctly, `touch#` doesn't do anything but make sure there's a reference to the pointer around so it doesn't get GC'd too soon. One touch at the end should be enough for that... But well, if it doesn't work, there's obviously something I'm missing here." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-17T19:07:30.593", "Id": "16097", "Score": "0", "body": "Sometimes, `lgo` returns `BufferFull` (I think). When this happens, an action is returned from `withForeignPtr` that, when called, will act on `ptr`. This means `ptr` will be used outside of the `withForeignPtr`, even though the action that uses it is lexically inside of the function passed to `withForeignPtr`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-17T21:39:00.383", "Id": "16102", "Score": "0", "body": "Oh, as you explained already. Silly me, sorry for that :)" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-16T19:09:43.837", "Id": "10079", "ParentId": "9998", "Score": "4" } } ]
{ "AcceptedAnswerId": "10079", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T21:50:29.333", "Id": "9998", "Score": "5", "Tags": [ "optimization", "strings", "haskell" ], "Title": "Optimizing ByteString escaping" }
9998
<p>I'm writing a simple text-based RPG in Java. I think it's a good exercise to practice OO and think about how objects should best interact. I'd be interested in hearing any thoughts!</p> <p>The <code>Game</code> class contains a single game:</p> <pre><code>public final class Game { private final Player player = Player.newInstance(); public void play() throws IOException { System.out.println("You are " + player + " " + player.getDescription()); Dungeon.newInstance().startQuest(player); } public static void main(String[] args) throws IOException { Game game = new Game(); game.play(); } } </code></pre> <p>Here's a simple <code>Dungeon</code> class, a collection of <code>Room</code>s laid out in the map. The player moves from room to room, encountering and battling monsters.</p> <pre><code>public final class Dungeon { private final Map&lt;Integer, Map&lt;Integer, Room&gt;&gt; map = new HashMap&lt;Integer, Map&lt;Integer, Room&gt;&gt;(); private Room currentRoom; private int currentX = 0; private int currentY = 0; private Dungeon() { } private void putRoom(int x, int y, Room room) { if (!map.containsKey(x)) { map.put(x, new HashMap&lt;Integer, Room&gt;()); } map.get(x).put(y, room); } private Room getRoom(int x, int y) { return map.get(x).get(y); } private boolean roomExists(int x, int y) { if (!map.containsKey(x)) { return false; } return map.get(x).containsKey(y); } private boolean isComplete() { return currentRoom.isBossRoom() &amp;&amp; currentRoom.isComplete(); } public void movePlayer(Player player) throws IOException { boolean northPossible = roomExists(currentX, currentY + 1); boolean southPossible = roomExists(currentX, currentY - 1); boolean eastPossible = roomExists(currentX + 1, currentY); boolean westPossible = roomExists(currentX - 1, currentY); System.out.print("Where would you like to go :"); if (northPossible) { System.out.print(" North (n)"); } if (eastPossible) { System.out.print(" East (e)"); } if (southPossible) { System.out.print(" South (s)"); } if (westPossible) { System.out.print(" West (w)"); } System.out.print(" ? "); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String direction = in.readLine(); if (direction.equals("n") &amp;&amp; northPossible) { currentY++; } else if (direction.equals("s") &amp;&amp; southPossible) { currentY--; } else if (direction.equals("e") &amp;&amp; eastPossible) { currentX++; } else if (direction.equals("w") &amp;&amp; westPossible) { currentX--; } currentRoom = getRoom(currentX, currentY); currentRoom.enter(player); } public void startQuest(Player player) throws IOException { while (player.isAlive() &amp;&amp; !isComplete()) { movePlayer(player); } if (player.isAlive()) { System.out.println(Art.CROWN); } else { System.out.println(Art.REAPER); } } public static Dungeon newInstance() { Dungeon dungeon = new Dungeon(); dungeon.putRoom(0, 0, Room.newRegularInstance()); dungeon.putRoom(-1, 1, Room.newRegularInstance()); dungeon.putRoom(0, 1, Room.newRegularInstance()); dungeon.putRoom(1, 1, Room.newRegularInstance()); dungeon.putRoom(-1, 2, Room.newRegularInstance()); dungeon.putRoom(1, 2, Room.newRegularInstance()); dungeon.putRoom(-1, 3, Room.newRegularInstance()); dungeon.putRoom(0, 3, Room.newRegularInstance()); dungeon.putRoom(1, 3, Room.newRegularInstance()); dungeon.putRoom(0, 4, Room.newBossInstance()); dungeon.currentRoom = dungeon.getRoom(0, 0); return dungeon; } } </code></pre> <p>Here's the <code>Monster</code> class:</p> <pre><code>public final class Monster { private final String name; private final String description; private int hitPoints; private final int minDamage; private final int maxDamage; private final static Random random = new Random(); private final static Set&lt;Integer&gt; monstersSeen = new HashSet&lt;Integer&gt;(); private final static int NUM_MONSTERS = 3; public static Monster newRandomInstance() { if (monstersSeen.size() == NUM_MONSTERS) { monstersSeen.clear(); } int i; do { i = random.nextInt(NUM_MONSTERS); } while (monstersSeen.contains(i)); monstersSeen.add(i); if (i == 0) { return new Monster("Harpy", Art.HARPY, 40, 8, 12); } else if (i == 1) { return new Monster("Gargoyle", Art.GARGOYLE, 26, 4, 6); } else { return new Monster("Hobgoblin", Art.HOBGOBLIN, 18, 1, 2); } } public static Monster newBossInstance() { return new Monster("Dragon", Art.DRAGON, 60, 10, 20); } private Monster(String name, String description, int hitPoints, int minDamage, int maxDamage) { this.name = name; this.description = description; this.minDamage = minDamage; this.maxDamage = maxDamage; this.hitPoints = hitPoints; } @Override public String toString() { return name; } public String getDescription() { return description; } public String getStatus() { return "Monster HP: " + hitPoints; } public int attack() { return random.nextInt(maxDamage - minDamage + 1) + minDamage; } public void defend(Player player) { int attackStrength = player.attack(); hitPoints = (hitPoints &gt; attackStrength) ? hitPoints - attackStrength : 0; System.out.printf(" %s hits %s for %d HP of damage (%s)\n", player, name, attackStrength, getStatus()); if (hitPoints == 0) { System.out.println(" " + player + " transforms the skull of " + name + " into a red pancake with his stone hammer"); } } public boolean isAlive() { return hitPoints &gt; 0; } } </code></pre> <p><code>Battle</code> class:</p> <pre><code>public final class Battle { public Battle(Player player, Monster monster) throws IOException { System.out.println("You encounter " + monster + ": " + monster.getDescription() + "\n"); System.out.println("Battle with " + monster + " starts (" + player.getStatus() + " / " + monster.getStatus() + ")"); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); while (player.isAlive() &amp;&amp; monster.isAlive()) { System.out.print("Attack (a) or heal (h)? "); String action = in.readLine(); if (action.equals("h")) { player.heal(); } else { monster.defend(player); } if (monster.isAlive()) { player.defend(monster); } } } } </code></pre> <p><code>Room</code> class:</p> <pre><code>public final class Room { private final String description; private final Monster monster; private final Boolean isBossRoom; private final static Random random = new Random(); private final static Set&lt;Integer&gt; roomsSeen = new HashSet&lt;Integer&gt;(); private final static int NUM_ROOMS = 7; private Room(String description, Monster monster, Boolean isBossRoom) { this.description = description; this.monster = monster; this.isBossRoom = isBossRoom; } public static Room newRegularInstance() { if (roomsSeen.size() == NUM_ROOMS) { roomsSeen.clear(); } int i; do { i = random.nextInt(NUM_ROOMS); } while (roomsSeen.contains(i)); roomsSeen.add(i); String roomDescription = null; if (i == 0) { roomDescription = "a fetid, dank room teeming with foul beasts"; } else if (i == 1) { roomDescription = "an endless mountain range where eagles soar looking for prey"; } else if (i == 2) { roomDescription = "a murky swamp with a foul smelling odour"; } else if (i == 3) { roomDescription = "a volcano with rivers of lava at all sides"; } else if (i == 4) { roomDescription = "a thick forest where strange voices call out from the trees high above"; } else if (i == 5) { roomDescription = "an old abandoned sailing ship, littered with the remains of some unlucky sailors"; } else if (i == 6) { roomDescription = "a cafe filled with hipster baristas who refuse to use encapsulation"; } else { } return new Room(roomDescription, Monster.newRandomInstance(), false); } public static Room newBossInstance() { return new Room("a huge cavern thick with the smell of sulfur", Monster.newBossInstance(), true); } public boolean isBossRoom() { return isBossRoom; } public boolean isComplete() { return !monster.isAlive(); } @Override public String toString() { return description; } public void enter(Player player) throws IOException { System.out.println("You are in " + description); if (monster.isAlive()) { new Battle(player, monster); } } } </code></pre> <p>And the <code>Player</code> class:</p> <pre><code>public final class Player { private final String name; private final String description; private final int maxHitPoints; private int hitPoints; private int numPotions; private final int minDamage; private final int maxDamage; private final Random random = new Random(); private Player(String name, String description, int maxHitPoints, int minDamage, int maxDamage, int numPotions) { this.name = name; this.description = description; this.maxHitPoints = maxHitPoints; this.minDamage = minDamage; this.maxDamage = maxDamage; this.numPotions = numPotions; this.hitPoints = maxHitPoints; } public int attack() { return random.nextInt(maxDamage - minDamage + 1) + minDamage; } public void defend(Monster monster) { int attackStrength = monster.attack(); hitPoints = (hitPoints &gt; attackStrength) ? hitPoints - attackStrength : 0; System.out.printf(" " + name + " is hit for %d HP of damage (%s)\n", attackStrength, getStatus()); if (hitPoints == 0) { System.out.println(" " + name + " has been defeated"); } } public void heal() { if (numPotions &gt; 0) { hitPoints = Math.min(maxHitPoints, hitPoints + 20); System.out.printf(" %s drinks healing potion (%s, %d potions left)\n", name, getStatus(), --numPotions); } else { System.out.println(" You've exhausted your potion supply!"); } } public boolean isAlive() { return hitPoints &gt; 0; } public String getStatus() { return "Player HP: " + hitPoints; } @Override public String toString() { return name; } public String getDescription() { return description; } public static Player newInstance() { return new Player("Mighty Thor", "a musclebound hulk intent on crushing all evil in his way", 40, 6, 20, 10); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T22:20:52.027", "Id": "15931", "Score": "4", "body": "You shouldn't be using `System.out.println()` directly - in fact, your back-end classes should have _absolutely no clue_ that it's a text based system. Interestingly, doing so makes a change to a graphical interface much easier, later." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-20T12:29:32.483", "Id": "16186", "Score": "0", "body": "If you're looking for some inspiration, [CoffeeMUD](http://www.zimmers.net/home/mud/) is a pretty cool open source MUD server." } ]
[ { "body": "<p><strong>IO:</strong> You use everywhere <code>System.out.println</code> and <code>System.in</code> (BTW, <code>Scanner</code> is much more convenient than a <code>Reader</code>). Even if you want to switch from console output to a simple Swing application with little more than a text area, you have to change <em>everything</em>. Same story if you want to provide a translation for your game. </p>\n\n<p>So follow the the <a href=\"http://en.wikipedia.org/wiki/Single_responsibility_principle\">Single Responsibility Principle</a>: Your model classes like <code>Player</code> and <code>Monster</code> should care about the state of the game and its transitions, and not about IO. Even if this is not a perfect separation, it's still better to send Strings to an <code>IO</code> class, and ask it for input, than doing everything locally. Then the <code>IO</code> class is in charge how to present the data. Later you might want to send just messages like <code>PlayerDied()</code> or <code>HealthDownTo(42)</code> to IO, which gets the real output from a text file or so.</p>\n\n<p><strong>Room:</strong> <code>if (i == 0) {...</code> cascades are written better using <code>switch</code>. In your case an array with all strings would be even better, you need just <code>roomDescriptions[i]</code> to get the right one. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T22:19:17.427", "Id": "10000", "ParentId": "9999", "Score": "7" } }, { "body": "<pre><code> private final Player player = Player.newInstance();\n</code></pre>\n\n<p>Function like <code>newInstance</code> are suspicious. I immeadieatly wonder why you didn't use <code>new Player</code>. In some cases you use <code>newRandomInstance</code> which I like better because it tells me what you are really up to.</p>\n\n<pre><code>public static void main(String[] args) throws IOException {\n</code></pre>\n\n<p>Having your main function throw an IOException is probably not the best idea. As it is you've got all kinds of functions that throw IOExceptions despite not really being IO related. Since there is really nothing you can do with the IOException I suggest you catch them when the happen and then rethrow them:</p>\n\n<pre><code>throw new RuntimeException(io_exception);\n</code></pre>\n\n<p>That you won't clutter the code with exceptions information you don't handle anyways.</p>\n\n<pre><code>private final Map&lt;Integer, Map&lt;Integer, Room&gt;&gt; map = new HashMap&lt;Integer, Map&lt;Integer, Room&gt;&gt;();\n</code></pre>\n\n<p>It seems to me that you'd be better off using a 2D array to hold the map rather then this. It would simplify your code in quite a few places.</p>\n\n<pre><code> System.out.print(\"Where would you like to go :\");\n if (northPossible) {\n System.out.print(\" North (n)\");\n }\n</code></pre>\n\n<p>As Landei said, you are better off keeping your input/output in separate classes from the actual game logic. </p>\n\n<pre><code>private Room currentRoom;\nprivate int currentX = 0;\nprivate int currentY = 0;\n</code></pre>\n\n<p>It seems to me that these belong as part of the Player, not the dungeon. </p>\n\n<pre><code>public void startQuest(Player player) throws IOException {\n while (player.isAlive() &amp;&amp; !isComplete()) {\n movePlayer(player);\n }\n</code></pre>\n\n<p>It's a little odd for a function named startQuest to continue on until the player dies or wins.</p>\n\n<pre><code>private final static Random random = new Random();\nprivate final static Set&lt;Integer&gt; monstersSeen = new HashSet&lt;Integer&gt;();\n</code></pre>\n\n<p>I recommend avoiding static variables. (Constants are fine). You lose some flexibility when you use statics. In your case, I think you should really put that logic in a factory class. Also, you really shouldn't have a class-specific instance of Random. You want to share a single Random amongst all your objects. </p>\n\n<pre><code> if (roomsSeen.size() == NUM_ROOMS) {\n roomsSeen.clear();\n }\n int i;\n do {\n i = random.nextInt(NUM_ROOMS);\n } while (roomsSeen.contains(i));\n roomsSeen.add(i);\n</code></pre>\n\n<p>You do this basic thing multiple times, which suggests you should think about finding a way to write one class you can use in both cases. </p>\n\n<pre><code> if (monster.isAlive()) {\n new Battle(player, monster);\n }\n</code></pre>\n\n<p>Having action occour as a side of creating an object isn't a good idea. At least have the action occur as a result of calling a method.</p>\n\n<p>The big thing here is to seperate the user interface (reading and writing to the console) from the game logic itself. The other things I point out could be improved, but that is where the biggest problems will arise.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-14T23:19:59.030", "Id": "15980", "Score": "0", "body": "Thanks! Great feedback. By the way, do you think its bad form to create factories for everything upfront? I was thinking this would make it easier later on if more complexity needs to be added to the factory, but perhaps this is overkill?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-15T03:48:00.190", "Id": "15983", "Score": "1", "body": "@padawan, I wouldn't say that you should have factories for everything. But I would say that an object shouldn't go through complex machinations to create itself. If you have to parse files, pick random numbers, etc. then I'd go for a factory. Note that this doesn't mean you should have lots of factories. In your case, I'd probably go for a single factory, a DungeonFactory. The DungeonFactory would build the Monsters/Rooms/etc and put them all together." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-15T17:07:31.870", "Id": "16019", "Score": "0", "body": "Thanks. I'm trying to understand Item 1: Consider static factory methods instead of constructors, in Effective Java. It gives some pretty solid reasons for using factory methods over constructors.\n\nSo if I understand you, you're saying that a factory class is only needed for the Dungeon. What's your view on static factory methods within the class (e.g. within Monster or Room) as a substitute for constructors? Should these always be used, or only in certain cases?\n\nThanks again!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-17T17:32:38.040", "Id": "16093", "Score": "1", "body": "@padawan, I've been trying to figure out exactly what my theory is on constructors vs static factory methods. I've come to the conclusion that I prefer very simple constructors. My constructors usually just copy the constructor parameters into fields. If I need something more complicated then I'd for for a factory or static method." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-17T02:13:54.417", "Id": "33043", "Score": "0", "body": "`Random` objects are generally static to reduce recreation of the object." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T22:55:32.927", "Id": "10002", "ParentId": "9999", "Score": "14" } }, { "body": "<p>There's nothing about Java, but pure OO principle.</p>\n\n<p>Why Player and Monster are totally different classes?</p>\n\n<p>There should be the class \"Objet\" then its descendant \"Creature\" (or whatever) then, from it, Player and Monster.</p>\n\n<pre><code> Object\n |\n |\n |\n Creature\n |\n /\\\n / \\\n / \\\n / \\\n | |\nPlayer Monster\n</code></pre>\n\n<p>Creature can move, carry stuff, have tons of properties that Player and Monster share (attack, defense, health, and so on).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T11:42:19.987", "Id": "21546", "Score": "7", "body": "Composition is usually better." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-01-31T08:38:44.107", "Id": "355569", "Score": "0", "body": "@Eva Of course. But langages like Php and Pure C dont have multiple inheritance (and dont tell me about `traits` in Php...). That's why I said \"pure OO\". But you're 100% right for langages that have multiple inheritance/composition feature." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-20T08:46:16.157", "Id": "10175", "ParentId": "9999", "Score": "1" } } ]
{ "AcceptedAnswerId": "10002", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T21:56:48.090", "Id": "9999", "Score": "15", "Tags": [ "java", "object-oriented", "role-playing-game" ], "Title": "Text-based RPG in Java" }
9999
<p>I am working on a web mapping library, that makes it possible to create a map with SVG and JavaScript. As every map shall consist of SVG and Image elements, which can be grouped in layers, which in turn can be set invisible, I need an API to reflect this functionality. I started with two classes/prototypes:</p> <pre><code>Map() // the map constructor .add(object) // method to add a layer or element Layer() // the layer constructor .add(object) // method to add an element .setVisibility(boolean) // mothod to set the visibilty </code></pre> <p>Some days later I extended the Map with a method to register event handlers that I modeled after the <a href="http://api.jquery.com/on/" rel="nofollow" title=".on() - JQuery API">Jquery on/off API</a>:</p> <pre><code>Map() .add(object) .on(events, handler) // method to register event handlers .off(events) // โ€ฆ and to unregsiter handlers </code></pre> <p>The trick with the events parameter is, that it is a string containing both an event and an optinal namespace to group the event handlers like <code>click.namespace</code></p> <p>A classmate then gave me the advice to remove the layer class completely and add "add()" and "remove()" methods that work like the on and off methods to group elements to layers. So the following API emerged:</p> <pre><code>Map() .add(namespace, object) .remove(namespace) .on(events, handler) .off(events) </code></pre> <p>What I find somehow cumbersome, is, that <em>events</em> describe both an event and an optinal namespace, whereas <em>namespace</em> only describes a namespace. So</p> <h2>The Question is:</h2> <p><em>How to design such an API in a simple, but still consistent way so that I can group elements and event handlers in a similar manner?</em></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-21T18:39:19.430", "Id": "73055", "Score": "0", "body": "This question appears to be off-topic because it is a design review and not a code review." } ]
[ { "body": "<p>Since namespaces are always optional, you can follow the common JavaScript convention and put them at the end of the arguments list:</p>\n\n<pre><code>Map()\n.add(object, namespace1)\n.remove(namespace1)\n.on(events, handler, namespace2)\n.off(events)\n.on(otherEvents, handler)\n</code></pre>\n\n<hr>\n\n<p><strike>As you say, <code>events</code> describe both an event and a namespace. More specifically, they describe an event on a namespace <em>or</em> the whole map, which is why it makes sense to add back the \"layer\" object. This is the simplest way to show the difference between \"event on a layer\" and \"event on all layers\":</p>\n\n<pre><code>var l = Layer() // the layer constructor\n.add(object) // method to add an element\n.setVisibility(boolean) // mothod to set the visibilty\n.on(\"click\", handler) // do XXX when clicking on an object of this layer\n.off(\"click\")\n\nvar m = Map() // the map constructor\n.add(l) // method to add a layer or element\n.on(\"hover\", handler) // do XXX when hovering the whole map\n</code></pre>\n\n<p>You should also wonder what you're going to do with bubbling events. If there's an event which is not handled in the layer, is it going to bubble up and be handled by the map? For all browsers? Those issues (and many more) are already covered by jQuery, which is why I don't suggest rewriting half of their event-handling code and simply use it directly. Why not writing your API as a jQuery plugin?</strike></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-14T10:14:31.593", "Id": "15943", "Score": "1", "body": "I thought of namespaces more like \"click.handler1\" or \"click.someOtherHandlers\", so that it is easier to unregister and group event handlers and not like \"click.layer1\" or \"click.layer2\" to show where the event comes from (maybe i misinterpreted that part). I do not plan to handle any events on layers, only on the map itself, an event could for example be \"pan\" or \"zoom\" (it doesn't make sense to pan a single layer). Additionally i can not rely on jQuery because jQuery doesn't have any SVG functionality at all and my library will be SVG only - I just used it as an inspiration for my API." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-14T13:41:35.183", "Id": "15948", "Score": "0", "body": "OK, I was mistaken. Are namespaces optional for objects too?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-14T14:47:10.973", "Id": "15951", "Score": "0", "body": "You mean when adding elements? Yes they should be optional, so that you can stuff elements into the map without having to group them." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-14T14:57:48.573", "Id": "15952", "Score": "0", "body": "I just encountered another problem: I wanted to get rid of the Layer.setVisibility() method, by using map.add() and map.remove() instead but that will mix up the order of the layers, due to SVG's [painter algorithm](http://en.wikipedia.org/wiki/Painter_algorithm) when setting layers invisible repeatedly." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-14T09:30:11.610", "Id": "10010", "ParentId": "10001", "Score": "2" } } ]
{ "AcceptedAnswerId": "10010", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T22:47:46.290", "Id": "10001", "Score": "6", "Tags": [ "javascript", "api" ], "Title": "Registering layers in a web mapping library. API design" }
10001
<p>Trying to implement something like <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/bb776391%28v=vs.85%29.aspx" rel="nofollow">CommandLineToArgV</a>:</p> <pre><code>template&lt;typename InIter, typename OutIter&gt; inline InIter CmdLineToArgvWUnescape(InIter begin, InIter end, OutIter target) { if (std::distance(begin, end) &lt; 2 || *begin != L'"') { // ""s are required throw MalformedEscapedSequence(); } ++begin; //Skip " std::size_t backslashCount = 0; for(; begin != end; ++begin) { switch(*begin) { case L'\\': backslashCount++; break; case L'"': if (backslashCount) { std::fill_n(target, backslashCount / 2, L'\\'); *target++ = L'"'; backslashCount = 0; } else { return ++begin; } default: if (backslashCount) { std::fill_n(target, backslashCount, L'\\'); backslashCount = 0; } *target++ = *begin; } } throw MalformedEscapedSequence(); } </code></pre>
[]
[ { "body": "<p>My one comment is add a comment on exactly what it is doing.</p>\n\n<p>Even after studying I am not 100% sure what it does (I would need some unit tests to feel I understood it).</p>\n\n<p>What I think you are trying to achieve:</p>\n\n<ul>\n<li>Convert \\\" into \"</li>\n<li>Convert \\\\\\\" into \\\"</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-14T20:05:05.640", "Id": "15969", "Score": "0", "body": "What it does is essentially the same as the MSDN article. Scroll down to `CommandLineToArgvW has a special interpretation of backslash characters...`" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-14T19:18:23.520", "Id": "10025", "ParentId": "10005", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-14T02:01:17.373", "Id": "10005", "Score": "2", "Tags": [ "c++" ], "Title": "CommandLineToArgV Unescaping" }
10005
<p><em><strong>Question:</em></strong><em>Write an algorithm in C to do integer multiplication without using multiplication nor division operators</em>.</p> <p>Could I get a critique of the doMultiplication function? I know the rest of the code has some dumb stuff in it (like using scanf), but I'm looking for feedback on my multiplication implementation. Are there any cases it won't handle? Is there anything I could possibly have done to optimize it? And lastly, is there anything that would make it more readable?</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;math.h&gt; /* Write an algorithm/code in C to do integer multiplication without using multiplication nor division operators. */ void main() { int n; int m; int result; printf("Please enter numbers to multiplye\n"); printf("First number\n"); int multiple1 = getNumberFromUser(); printf("\nSecond number\n"); int multiple2 = getNumberFromUser(); result = doMultiplication(multiple1,multiple2); printf("Result of multiplication = %d\n", result); } int getNumberFromUser() { char arg1[10]; int retry = 0; int multiple; while(retry == 0) { printf("Please enter a number:"); scanf("%s", arg1); if(isNumericInput(arg1) != 0) { char * strEnd; multiple = strtol(arg1,&amp;strEnd, 10); retry = 1; } else { printf("Bzzz wrong answer genius try a number \n"); } } return multiple; } int isNumericInput(char arg[]){ char * strEnd; int userInput = strtol(arg, &amp;strEnd, 10); return userInput; } int doMultiplication(int n, int m) { int result = 0; while(m != 0) { if((m &amp; 1) != 0) { result = result + n; } n = n &lt;&lt; 1; m = m &gt;&gt; 1; } return result; } </code></pre>
[]
[ { "body": "<p><a href=\"http://en.wikipedia.org/wiki/Multiplication_algorithm#Shift_and_add\" rel=\"nofollow\">Your algorithm</a> is optimal for numbers that fit into a int, but a <a href=\"http://en.wikipedia.org/wiki/Multiplication_algorithm#Fast_multiplication_algorithms_for_large_inputs\" rel=\"nofollow\">lot of multiplication algorithms exist for large inputs</a>. By the way, is bit-shifting authorized? It looks a lot like a multiplication.</p>\n\n<h2>Code comments</h2>\n\n<ol>\n<li><code>strtol(3)</code> returns a <code>long int</code>, not an <code>int</code>.</li>\n<li>Tell scanf you only want 9 characters (+ <code>\\0</code>): <code>scanf(\"%9s\", arg1);</code> if you want to avoid a buffer overflow.</li>\n<li>You should test the return of <code>scanf</code>.</li>\n<li>Calling <code>strtol(3)</code> twice is surprising. Why don't you store the return value of <code>isNumericInput</code>?</li>\n<li>You could print errors on the standard error stream: <code>fprintf(stderr, \"Bzzz wrong!\\n\");</code></li>\n<li><code>((m &amp; 1) != 0)</code> -> <code>(m &amp; 1 != 0)</code> -> <code>(m % 2 != 0)</code> -> <code>(m % 2)</code>.</li>\n<li>Typo: it's multiply, not multiplye.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-14T09:44:17.073", "Id": "15937", "Score": "0", "body": "#6 would be better to be just `m & 1`, since bit-fiddling will be faster than a full modulus operation (although GCC seems to compile them to the same code) and testing `!= 0` is pointless in C (any non-zero value is already considered \"true\")." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-14T09:48:54.660", "Id": "15939", "Score": "2", "body": "Yes, GCC and any reasonable compiler will optimize it, so it's pointless to use bit-shifting. It's the same for `/ 2`, but since he can't do \"multiplication/division\"... Thanks for the `!= 0`, I'll edit." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-14T08:47:51.260", "Id": "10008", "ParentId": "10006", "Score": "3" } }, { "body": "<p>Basically your algorithm looks correct, however:</p>\n\n<ol>\n<li>You should use unsigned ints or have some treatment for the signs, otherwise I guess (didn't check it though) that your results for negative numbers will be wrong</li>\n<li>Don't test for 0 explicitly, i.e. just write <code>while(m)</code> and <code>if(m &amp; 1)</code></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-14T09:23:00.683", "Id": "10009", "ParentId": "10006", "Score": "4" } }, { "body": "<blockquote>\n<pre><code>void main()\n</code></pre>\n</blockquote>\n\n<p><code>== inf. pain.</code></p>\n\n<p>I die a little every time I see that... It's <i><b>int</b> main()</i>, thank you very much!</p>\n\n<blockquote>\n <p>if(isNumericInput(arg1) != 0)</p>\n</blockquote>\n\n<p>The name <i>isNumericInput()</i> is poorly chosen, as the function doesn't really return what the name implies, i.e. a true/false value. I think that's why you made a small logical bug here.</p>\n\n<p>The return value of <i>isNumericInput()</i> is the actual parsed number, which can be 0, if either arg1 isn't a number at all <b>or if arg1 is \"0\"</b>, a perfectly fine number contrary to what your program claims.</p>\n\n<p>If you did make a proper <i>isNumericInput()</i>, I would suggest re-writing the check as</p>\n\n<pre><code>if(!isNumericInput(arg1))\n</code></pre>\n\n<p>as that can more easily be read as \"if not numeric, ...\" compared to your version, which reads more like \"if numeric NOT!, ...\" or \"if numeric not false, ...\".</p>\n\n<p>Instead of first reading a string and then parsing that string (twice), I think it would be better to just let <i>scanf()</i> read an integer.</p>\n\n<p>Maybe something like this:</p>\n\n<pre><code>int getNumberFromUser()\n{\n int number; /*\n * You call it \"multiple\", but at this point in the code,\n * it's just a number. This function doesn't care what you\n * use the number for later on.\n */\n\n int items;\n\n do\n {\n printf(\"Please enter a number:\");\n\n items=scanf(\"%d\",&amp;number); /* Return number of items read. */\n\n if(items!=1) /* If we didn't read a number... */\n fprintf(stderr,\"Bzzz wrong answer genius try a number \\n\");\n }\n while(items!=1); /* Loop until we get a number */\n\n /*\n * In this case, \"items\" will always be either 0 or 1, so here the two\n * checks could have been replaced with either (items==0) or (!items),\n * but IMHO it feels more logical to compare against 1 in this case.\n */\n\n return(number);\n}\n</code></pre>\n\n<p>and drop <i>isNumericInput()</i> as it isn't used anymore.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-05T06:11:20.633", "Id": "10637", "ParentId": "10006", "Score": "3" } }, { "body": "<p>While others have mentioned that your code is technically correct, it could be made much simpler to understand and read. Don't try to be too clever, let the complier optimize. As someone else mentioned, using bitshifting could be construed as multiplication because, well, it kind of is.</p>\n\n<pre><code>int doMultiplication(int n, int m)\n{\n int result = 0;\n while(m)\n {\n result += n;\n m--;\n }\n return result;\n}\n</code></pre>\n\n<p>One thing yours (and mine) doesn't support is negative numbers. If you need to support negative numbers, here's one solution:</p>\n\n<pre><code>int doMultiplication(int n, int m)\n{\n /* This first part is if you need to handle negative numbers */\n int n_is_negative = (n &lt; 0);\n int m_is_negative = (m &lt; 0);\n int result_is_negative = (n_is_negative != m_is_negative); /* Only if the signs are different is the result negative */\n n = (n &lt; 0 ? -n : n); /* use abs() if you can for readability sake */\n m = (m &lt; 0 ? -m : m);\n\n int result = 0;\n while(m)\n {\n result += n;\n m--;\n }\n if(result_is_negative)\n result = -result;\n return result;\n}\n</code></pre>\n\n<p>Granted, this uses the negation operator (<code>-</code>), which is itself a form of multiplication, but it is the simplest way to negate a number.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-08-04T09:46:32.677", "Id": "257463", "Score": "0", "body": "-1 Do you realise that your algorithm takes O(m) time while the OP's algorithm takes O(log m)?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-06T19:06:30.613", "Id": "10664", "ParentId": "10006", "Score": "1" } } ]
{ "AcceptedAnswerId": "10009", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-14T07:21:04.017", "Id": "10006", "Score": "4", "Tags": [ "optimization", "c" ], "Title": "Binary Multiplication in C" }
10006
<p>Basically, I'm comparably new to Haskell, which means lacking both knowledge of advanced principles, available libraries and, maybe, some syntax.</p> <p>For educational purposes I hacked together a code implementing Stam-style fluid dynamics solver. For now the code is running in constant space and linear time, which is exactly what's needed. But feeling remains that code I wrote is rather ugly.</p> <p>I have serious concerns about whether this code is possible to read at all, but hope that somebody could point out most obvious idiosyncrasies.</p> <pre><code>import Data.Array.Unboxed import Data.List import Text.Printf n = 20 timeStep = 0.1 numSteps = 100 indicies = [[0..n + 1], [1..n], [2..n-1]] type Matrix = UArray (Int, Int) Float data Bound = XHard | YHard | Soft data State = State !Matrix !Matrix !Matrix applyNTimes :: Int -&gt; (a -&gt; a) -&gt; a -&gt; a applyNTimes times f val = foldl' (\m i -&gt; f m) val [1..times] showMatrix :: Matrix -&gt; String showMatrix m = foldl (++) "" [showRow m i ++ "\n" | i &lt;- head indicies] where showRow m i = foldl (++) "" [printf "%.3f " (m ! (i, j)) | j &lt;- head indicies] showState :: State -&gt; String showState (State u v d) = showMatrix d createMatrix :: [Int] -&gt; ((Int, Int) -&gt; Float) -&gt; Matrix createMatrix ind f = array ((0, 0), (n + 1, n + 1)) [((i, j), f (i, j)) | j &lt;- ind, i &lt;- ind] // [(ix, 0) | ix &lt;- other] where other = [(i, j) | i &lt;- head indicies, j &lt;- head indicies] \\ [(i, j) | i &lt;- ind, j &lt;- ind] zeroMatrix :: Matrix zeroMatrix = createMatrix (head indicies) (\ (i, j) -&gt; 0.0) add :: Matrix -&gt; Matrix -&gt; Matrix add a b = createMatrix (head indicies) (add_cell a b) where add_cell a b ix = a ! ix + b ! ix addPecularSource :: State -&gt; State addPecularSource (State u v d) = State u v (d `add` createMatrix (head indicies) spike) where spike ix = if ix == (n `div` 2, n `div` 2) then 0.1 else 0.0 advance :: State -&gt; State advance s = solveDensity . addPecularSource . solveVelocity $ s main :: IO() main = putStrLn . showState . applyNTimes numSteps advance $ State z z z where z = zeroMatrix solveDensity :: State -&gt; State solveDensity (State u v d) = State u v d' where d' = advect Soft (diffuse d diffusion) u v where diffusion = 0.0 :: Float setCorners :: Matrix -&gt; Matrix setCorners a = a // [((n + 1, n + 1), (a ! (n , n + 1) + a ! (n + 1, n)) / 2), ((n + 1, 0), (a ! (n , 0) + a ! (n + 1, 1)) / 2), ((0, n + 1), (a ! (0, n) + a ! (1, n + 1)) / 2), ((0, 0), (a ! (1 , 0) + a ! (0, 1)) / 2)] diffuse :: Matrix -&gt; Float -&gt; Matrix diffuse c0 diff = linearSolver c0 a (1 + 4 * a) where a = timeStep * diff * fromIntegral n * fromIntegral n setBoundary :: Bound -&gt; Matrix -&gt; Matrix setBoundary b m = setCorners (setSides b m) setSides :: Bound -&gt; Matrix -&gt; Matrix setSides XHard m = setSides Soft m // ([((0, i), - m ! (0, i)) | i &lt;- indicies !! 1] ++ [((n + 1, i), - m ! (n + 1, i)) | i &lt;- indicies !! 1]) setSides YHard m = setSides Soft m // ([((i, 0), - m ! (i, 0)) | i &lt;- indicies !! 1] ++ [((i, n + 1), - m ! (i, n + 1)) | i &lt;- indicies !! 1]) setSides Soft m = m // ([((0, i), m ! (1, i)) | i &lt;- indicies !! 1] ++ [((n + 1, i), m ! (n, i)) | i &lt;- indicies !! 1] ++ [((i, 0), m ! (i, 1)) | i &lt;- indicies !! 1] ++ [((i, n + 1), m ! (i, n)) | i &lt;- indicies !! 1]) linearSolver :: Matrix -&gt; Float -&gt; Float -&gt; Matrix linearSolver x0 a c = applyNTimes 20 (iterFun x0 a c) zeroMatrix where iterFun x0 a c m = setBoundary Soft (createMatrix (indicies !! 1) (update m x0 a c) ) where update m x0 a c (i, j) = (a * (m ! (i - 1, j) + m ! (i + 1, j) + m ! (i, j - 1) + m ! (i, j + 1)) + x0 ! (i, j)) / c curl :: Matrix -&gt; Matrix -&gt; Matrix curl u v = createMatrix (indicies !! 1) gen where gen (i, j) = (u ! (i, j + 1) - u ! (i, j - 1) - v ! (i + 1, j) + v ! (i - 1, j)) / 2 archCell :: Matrix -&gt; Float -&gt; Float -&gt; (Int, Int) -&gt; Float archCell d gravity push (i, j) = gravity * d ! (i, j) + push * (d ! (i, j) - ambient d) where ambient d = sum [d ! (i, j) | i &lt;- indicies !! 1, j &lt;- indicies !! 1] archimedes :: Matrix -&gt; Matrix archimedes d = createMatrix (head indicies) (archCell d gravity push) where (gravity, push) = (0.001 :: Float, 0.005 :: Float) solveVelocity :: State -&gt; State solveVelocity (State u v d) = State u' v' d where (u', v') = project (advect YHard uProjected uProjected vProjected) (advect XHard vProjected uProjected vProjected) where (uProjected, vProjected) = project uDiffused vDiffused where (uDiffused, vDiffused) = (diffuse uVorticityConfined viscosity, diffuse (vVorticityConfined `add` archimedes d) viscosity) where ((uVorticityConfined, vVorticityConfined), viscosity) = (vorticityConfimentForce u v, 0.0) advectCell :: Matrix -&gt; Matrix -&gt; Matrix -&gt; (Int, Int) -&gt; Float advectCell d0 du dv (i, j) = s0 * t0 * d0 ! (floor x, floor y) + s0 * t1 * d0 ! (floor x, floor y + 1) + s1 * t0 * d0 ! (floor x + 1, floor y) + s1 * t1 * d0 ! (floor x + 1, floor y + 1) where (s0, t0, s1, t1, x, y) = (1.0 - x' + xx, 1.0 - y' + yy, x' - xx, y' - yy, x', y') where (x', y', xx, yy) = (x, y, fromIntegral (floor x), fromIntegral (floor y)) where (x, y) = (sort [0.5 + fromIntegral n, 0.5, fromIntegral i - dt0 * du ! (i, j)] !! 1, sort [0.5 + fromIntegral n, 0.5, fromIntegral j - dt0 * dv ! (i, j)] !! 1) where dt0 = timeStep * fromIntegral n advect :: Bound -&gt; Matrix -&gt; Matrix -&gt; Matrix -&gt; Matrix advect b d0 du dv = setBoundary b (createMatrix (indicies !! 1) (advectCell d0 du dv)) projectCellX :: Matrix -&gt; Matrix -&gt; (Int, Int) -&gt; Float projectCellX x p (i, j) = x ! (i, j) - 0.5 * fromIntegral n * (p!(i + 1, j) - p!(i - 1, j)) projectCellY :: Matrix -&gt; Matrix -&gt; (Int, Int) -&gt; Float projectCellY y p (i, j) = y ! (i, j) - 0.5 * fromIntegral n * (p!(i, j + 1) - p!(i, j - 1)) project :: Matrix -&gt; Matrix -&gt; (Matrix, Matrix) project x y = (setBoundary YHard x', setBoundary XHard y') where (x', y') = (createMatrix (indicies !! 1) (projectCellX x p), createMatrix (indicies !! 1) (projectCellY y p)) where p = linearSolver (setBoundary Soft diverg) 1 4 where diverg = createMatrix (indicies !! 1) (computeDiv x y) where computeDiv x y (i, j) = -0.5 * (x ! (i + 1, j) - x ! (i - 1, j) + y ! (i, j + 1) - y ! (i, j - 1)) / fromIntegral n dwdx :: Matrix -&gt; (Int, Int) -&gt; Float dwdx c (i, j) = (abs (c ! (i + 1, j)) - abs (c ! (i - 1, j))) / 2 dwdy :: Matrix -&gt; (Int, Int) -&gt; Float dwdy c (i, j) = (abs (c ! (i, j + 1)) - abs (c ! (i, j - 1))) / 2 len :: Matrix -&gt; (Int, Int) -&gt; Float len c (i, j) = sqrt(dwdx c (i, j) * dwdx c (i, j) + dwdy c (i, j) * dwdy c (i, j)) + eps where eps = 1e-6 funX :: Matrix -&gt; (Int, Int) -&gt; Float funX c (i, j) = - c ! (i, j) * dwdy c (i, j) / len c (i, j) funY :: Matrix -&gt; (Int, Int) -&gt; Float funY c (i, j) = c ! (i, j) * dwdx c (i, j) / len c (i, j) vorticityConfimentForce :: Matrix -&gt; Matrix -&gt; (Matrix, Matrix) vorticityConfimentForce u v = (createMatrix (indicies !! 2) (funX (curl u v)), createMatrix (indicies !! 2) (funY (curl u v))) </code></pre> <p>GHC 6.12.3 was used. Bang-patterns were added via <code>-XBangPatterns</code>.</p> <p>My question is: how to change this code to be more comprehensible and idiomatic?</p>
[]
[ { "body": "<p>Get rid of all the cascading <code>where</code> clauses, e.g.</p>\n\n<pre><code>project x y = (setBoundary YHard x', setBoundary XHard y')\n where (x', y') = (createMatrix (indicies !! 1) (projectCellX x p), createMatrix (indicies !! 1) (projectCellY y p))\n where p = linearSolver (setBoundary Soft diverg) 1 4\n where diverg = createMatrix (indicies !! 1) (computeDiv x y)\n where computeDiv x y (i, j) = -0.5 * (x ! (i + 1, j) - x ! (i - 1, j) + y ! (i, j + 1) - y ! (i, j - 1)) / fromIntegral n\n</code></pre>\n\n<p>All of those can be in a single <code>where</code> block, and every declaration in a <code>let</code> or <code>where</code> block are in scope in the other declarations in that block.</p>\n\n<p>Then I would run <a href=\"http://community.haskell.org/~ndm/hlint/\" rel=\"nofollow\">hlint</a> on your code and take a look at what it suggests. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-15T14:51:23.340", "Id": "16013", "Score": "0", "body": "Thanks, I've misunderstood how where works in general. Also, I've ran hlint." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-14T15:00:24.780", "Id": "10014", "ParentId": "10012", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-14T07:03:38.140", "Id": "10012", "Score": "2", "Tags": [ "haskell" ], "Title": "How to make following CFD program more idiomatic?" }
10012
<p>Nothing too special here, just a bunch of stuff. Please tell me if you would've done something different.</p> <pre><code>&lt;?php /** * SQL_Helper are functions which help with... SQL... :) * * @package SQL_Helper * @author Itai Sagi * @version 1.0 * SQL Helper functions * Assumption: a global PDO $db is active; */ class SQL_Helper{ // this function escapes and trims a string for insertion to SQL Database static public function escapeSQLStatement($string){ return mysql_real_escape_string(trim($string)); } // this function takes a query and returns a result_array if query returned results, false otherwise. static public function result_array($query){ global $db; $result = array(); foreach ($db-&gt;query($query) as $row){ $result[] = $row; } if (!empty($result)){ return $result; } return false; } } /** * This is the description for the class below. * * @package User * @author Itai Sagi * @version 1.0 * Basic User class * */ class User{ // class constructor which accepts a user_id as an optional parameter, // so you won't have to use the setUser() method. function __construct($user_id = null){ $this -&gt; userID = $user_id; } /** * function setUser($id); * This function sets the user_id for the class * Parameters: int $user_id, assuming a valid $user_id; * return values: the class itself. **/ function setUser($user_id){ $this -&gt; userID = $user_id; return $this; } } /** * @package User * @subpackage Contacts * @author Itai Sagi * @version 1.0 * The following class handles Contacts of a user. * Usage example: * searching user's contacts: * $contacts = new Contacts(); * $foundContacts = $contacts -&gt; setUser(76) -&gt; searchContactsByName('John'); * * getting contacts whose birthdays are up to 3 days from now: * please note that here, the user is still set to '76'. * $upcomingBirthdays = $contacts -&gt; upcomingBirthdays(3); * **/ class Contacts extends User{ function __construct($user_id = null){ parent::__construct($user_id); } /** * function: searchContactsByName($string); * This function searches the user's contacts for users whose name contain $string; * parameters: String $string - the name to search for * return values: an array containing the user's contacts which were found or FALSE if none were found or $id wasn't set **/ function searchContactByName($string){ if ($this -&gt; userID){ $string = SQL_Helper::escapeSQLStatement($string); $query = "SELECT lname, fname, email FROM contacts c JOIN users u ON u.id = c.contact_id WHERE c.id = '$this-&gt;userID' AND (lname LIKE '%$string%' OR fname LIKE '%$string%')"; return $SQL_Helper::result_array($query); } return false; } /** * function: upcomingBirthdays($daysInterval); * This function searches the user's contacts for users whose birthday is in the upcoming $daysInterval; * parameters: int $daysInterval - the amount of days to get the birthdays * return values: an array containing the user's contacts which were found or FALSE if none were found or $userID wasn't set **/ function upcomingBirthdays($daysInterval){ if ($this -&gt; userID){ $query = "SELECT lname, fname, email, birthday FROM contacts c JOIN users u ON u.id = c.contact_id WHERE c.id = $this-&gt;userID AND FLOOR( ( UNIX_TIMESTAMP(CONCAT( YEAR(CURDATE()) + (DATE_FORMAT(p.bday, '%m-%d') &lt; DATE_FORMAT(CURDATE(), '%m-%d')), DATE_FORMAT(p.day, '-%m-%d'))) - UNIX_TIMESTAMP(CURDATE())) / 86400) &lt; $daysInterval"; return $SQL_Helper::result_array($query); } return false; } } /** * @package User * @subpackage Messages * @author Itai Sagi * @version 1.0 * The following class handles the messages of a user * Usage examples: * * send a new message: * $message = new Messages(); * if ($message -&gt; setUser(65) -&gt; sendMessage("Hello, how are you?", 12)){ * echo "Message sent successfuly"; * } * else{ * echo "Message delivery failed"; * } * * getting an a list of all the messages: * $messages = new Messages(); * $messageArr = $messages -&gt; setUser(65) -&gt; getMessages(); * foreach ($messageArr as $m){ * // do something. * } * **/ class Messages extends User{ function __construct($user_id = null){ parent::__construct($user_id); } /** * function: getMessages(); * This function returns an array of all the messages a user recieved * return values: an array containing the messages or FALSE on failure / no messages. **/ function getMessages(){ if ($this -&gt; userID){ $query = "SELECT * FROM messages m JOIN users u ON u.id = m.from_id WHERE m.user_id = $this-&gt;userID ORDER BY send_time ASC"; return SQL_Helper::result_array($query); } return false; } /** * function: sendMessage($message, $recipientID); * This function "sends" a message from $this-&gt;userID to $recipientID * parameters: $message - the message content, $recipientID - the target user id who should get the message * return values: the message_id if successful or FALSE on failure **/ function sendMessage($message, $recipientID){ if ($this -&gt; userID){ $message = SQL_Helper::escapeSQLStatement($message); $query = "INSERT INTO messages (message_text, user_id, from_id, send_time) VALUES ('$message', $recipientID, $this-&gt;userID, NOW())"; if ($db -&gt; query ($query)){ return $db -&gt; lastInsertId(); }; } return false; } /** * function: searchInMessages($string) * This function searches all the messages of a user for the text $string * parameters: $string - the text to look for * return values: an array containing the messages or FALSE on failure / no messages found. **/ function searchInMessages($string){ if ($this -&gt; userID){ // Please note that because there's a full text index on the column, we aren't performing a full // table scan by using (LIKE '%$text') $string = SQL_Helper::escapeSQLStatement($string); $query = "SELECT * FROM messages m JOIN users u ON u.id = m.from_id WHERE m.user_id = $this-&gt;userID and m.message_text LIKE '$string%' ORDER BY send_time ASC"; return SQL_Helper::result_array($query); } return false; } } ?&gt; </code></pre>
[]
[ { "body": "<p>To be honest, if I were an employer I wouldn't read past the first class, which contains <code>static</code>, <code>global</code> and use of the deprecated <code>mysql_*</code>. They should be avoided, especially <code>mysql_*</code> which should be replaced by <code>mysqli</code> or PDO.</p>\n\n<p>All of your classes are tightly coupled to SQL_Helper due to the static functions. If you passed in the SQL_Helper into each class (dependency injection) in the constructor, you could remove this tight coupling.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-14T17:47:19.370", "Id": "15957", "Score": "0", "body": "the $global was an assumption given by the employer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-14T18:55:04.007", "Id": "15963", "Score": "0", "body": "@ItaiSagi I believe they're OK in this context, but it's generally a good idea to try avoiding such things. For example, regarding the global, it's easy to use the Singleton pattern which does essentially the same thing but with better encapsulation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-15T03:52:43.023", "Id": "15985", "Score": "2", "body": "@Cygal The singleton pattern unnecessarily limits you to having only 1 database. It is better to just create one and pass it in where it is needed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-15T08:12:30.750", "Id": "15996", "Score": "0", "body": "You don't need multiple databases. One database per model is clearly enough. The Singleton pattern was originally designed to manage a pool of connections to a database, but it also works fine for a single connection. And it's not mandatory at all and can be implemented in various ways. A global, `Zend_Registry`, CodeIgniter's [database configuration](http://codeigniter.com/user_guide/database/configuration.html), and so on." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-16T11:30:22.210", "Id": "16051", "Score": "0", "body": "I agree with Paul. A classical singleton is almost as bad as a global variable. Both databases and configurations should not be singletons. Just create a single instance and pass it into the class that needs it, instead of having the class ask a global variable for the singleton instance." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-14T17:14:24.030", "Id": "10018", "ParentId": "10015", "Score": "11" } }, { "body": "<p><code>SQL_Helper::result_array()</code> should return an empty array if the database returned an empty result set. In most cases, it is not an error condition when no records, that match your query, exist in a database.</p>\n\n<p>You use inconsistent naming conventions. Rename method <code>result_array()</code> to <code>getResults()</code> or similar, so that it is named using the same naming convention as used by the methods in your other classes.</p>\n\n<p>It seems strange that the classes <code>Contacts</code> and <code>Messages</code> inherit from class <code>User</code>. Inheritance usually signals a relationship of <em>is a</em>. But a contacts is not a user; a user <em>has</em> contacts.</p>\n\n<p>You assume a valid user in <code>User::setUser</code>. As a result, there is the risk of a SQL injection if the developer who uses the <code>User</code> class does not guarantee this precondition.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-14T23:54:09.240", "Id": "10032", "ParentId": "10015", "Score": "7" } }, { "body": "<p><em>Disclaimer: I am not a php developer</em> </p>\n\n<p>Other posts already mentioned good points as far as specifics about SQL and php and some problems with your inheritance structure. I am going to talk more about your <strong>craftsmanship</strong> in this post. </p>\n\n<blockquote>\n <p>\"SQL_Helper are functions which help with... SQL... :)\"</p>\n</blockquote>\n\n<p>This is like going to an interview with your shirt untucked and instead of properly shaking hands you greet them with 'yo bro'. Simply unprofessional. Won't get you hired. </p>\n\n<p>Anyways... onward...</p>\n\n<h2>Documentation</h2>\n\n<p>Your documentation is messy. Most <strong>great developers care about how their code and documentation\nlooks</strong>. <strong>They treat writing them as craft</strong>. You want the look/layout to be pleasing to the eye and the contents to be pleasing to the brain. \nThis means you need to keep things consistent looking and to the point. </p>\n\n<ul>\n<li>Capitalize all your sentences. </li>\n<li>You should stick with <code>/** */</code> for method/class level documentation and use <code>//</code> only for one-liners inside methods. </li>\n<li>Try to avoid using 'this function' when you write about the function. For example, I would rewrite <code>// this function escapes and trims a string for insertion to SQL Database</code> to <code>/** Escapes and trims a string */</code> or <code>/** Prepares a string to be used in an SQL statement */</code> (but I do not want to get caught too much in the semantics since I do not know much php...)</li>\n<li>If you absolutely have to use <code>@package</code>, <code>@autho</code>r and <code>@version</code> attributes, those should be the last thing in your documentation. They do not help the user whatsoever with using or maintaining \nyour class. The most important things should usually go on the top. Some places you have important information both above and below and sometimes only below. </li>\n<li>I am unsure about your duplicated method signatures in your documentation (Example: <code>* function setUser($id);</code>) I am positive your documenation tool extracts the signature automatically from the source itself, so this is just redundant. </li>\n</ul>\n\n<h2>Code</h2>\n\n<ul>\n<li>You do not have a <code>userID</code> attribute on your <code>User</code> class. I do not know if this is standard procedure for php but even if it runs in its current form, you should specify the attributes for your classes and those should usually be private. (Standard OOP here, \"hide your privates\")</li>\n<li><p>Minimize your API. You should probably choose to go with the constructor or the setter\nin the <code>User</code> class. I personally would go with the constructor. So code can be more terse by saying </p>\n\n<p>$contact= new Contact(72);</p>\n\n<p>$contact->searchContactByName('John');</p></li>\n<li><p>You should also not allow a null user when you are constructing one, so you do not have to worry about logic like this everywhere: </p>\n\n<p>if ($this -> userID){\n ...\n}\nreturn false;</p></li>\n</ul>\n\n<p>If your User class enforces the assumption that a userId cannot be null, all that code can be eliminated. </p>\n\n<ul>\n<li>Be more creative when choosing method names. Your class name already gives semantics to most of your methods. Fo example, in <code>SQL_Helper::escapeSQLStatement()</code> the 'SQL' is redundant. Why not <code>SQL_Helper::escapeStatement()</code>? </li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-23T17:44:45.310", "Id": "16389", "Score": "2", "body": "`@package` `@author` `@params`, etc are very useful when working with an IDE that pickup on these." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-15T01:25:16.710", "Id": "10033", "ParentId": "10015", "Score": "11" } }, { "body": "<p>Just another suggestion:</p>\n\n<pre><code>function __construct($user_id = null){\n $this -&gt; userID = $user_id;\n}\n</code></pre>\n\n<p>This is a huge problem to me.\nThis just means that whenever someone will try to do a request like</p>\n\n<pre><code>PDO_xx query (\"select * from XX where user_id=%1\",\n array( $user_id )\n)\n</code></pre>\n\n<p>There won't be any error, which is absolutely <strong>not acceptable</strong>.\nI always do something like this in all my classes (note that I've removed the comments but you <em>always</em> have to comment):</p>\n\n<pre><code>class User {\n\n public function __construct($user_id = false)\n {\n if (is_int($user_id)) {\n $this-&gt;setUserId($user_id);\n }\n }\n\n public function setUserId($user_id)\n {\n if (!is_int($user_id)) {\n throw new Exception(\"user_id: expected int\");\n }\n $this-&gt;userID = $user_id;\n return $this;\n }\n\n public function getUserId()\n {\n if (!isset($this-&gt;userID)) {\n throw new Exception(\"userID not set\");\n }\n return $this-&gt;userID;\n }\n}\n</code></pre>\n\n<p>And I don't know about the Php version, but if it's recent, you always have to put functions scope: <code>private</code>, <code>protected</code> or <code>public</code>.</p>\n\n<p>Another thing: note my <a href=\"http://en.wikipedia.org/wiki/Indent_style#K.26R_style\" rel=\"nofollow\">K&amp;R</a> indentation style. This may not be the best in the world, but it's very famous, and used by a lot of people (in C, but in C++, Php and also Java).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-20T08:36:08.617", "Id": "10173", "ParentId": "10015", "Score": "2" } } ]
{ "AcceptedAnswerId": "10033", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-14T15:36:44.027", "Id": "10015", "Score": "5", "Tags": [ "php", "object-oriented", "interview-questions" ], "Title": "I have a home test for job interview" }
10015
<p>I have a need to represent a finite set of discrete string values: </p> <ul> <li>When these strings are used in code, they must belong to the valid set, or serious errors (or worse) can occur. </li> <li>As "magic strings" are a terrible code smell, I want to encapsulate the strings within a non-string type, so that I can require the use of my type instead of just a string and thus enforce at compile-time that a value is given that I know will work.</li> <li>No constants; if I change the string behind the scenes I should not have to recompile all usages of my type.</li> <li>The identifiers representing the valid values should not have to have any formulaic similarity to the actual string (no Enum.ToString or similar).</li> <li>Lastly, while I want to enforce the use of my type so I can restrict values to the ones I know are valid, the type must be easily convertible to a string so that the piece of code that really needs the string doesn't have to undergo a complicated or esoteric conversion.</li> </ul> <p>What I came up with is a variation of a "multiton"; a class that cannot be instantiated in code, but has a finite number of static instances each representing a valid value of the type. They are implicitly convertible to strings and so the static members just drop in wherever a string is needed.</p> <pre><code>//abstract base; derive to create your specific set of values public abstract class StringEnum { protected StringEnum(string name) { this.name = name; } private readonly string name; public static implicit operator string(StringEnum sp) { return sp.name; } } //one possible derivation public class CommandNames:StringEnum { //unfortunately each derivation has to call back to the base constructor; //it would be nice not to have to do this, but meh protected CommandNames(string commName) : base(commName) { } //obviously the instance names don't have to match the real string value exactly public static readonly CommandNames DoSomething = new CommandNames("system638_Command_doSomething"); } //example usage public void ExecuteCommand(CommandNames name) { //assume ExecuteByName expects a string CommandExecutor.ExecuteByName(name); //the StringEnum just drops in } ... //Only one of the static instances, with string values I control, //can be passed into this function, thus safely encapsulating the inner //objects' use of "magic strings". ExecuteCommand(CommandNames.DoSomething); </code></pre> <p>Thoughts?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-15T18:53:22.827", "Id": "16021", "Score": "0", "body": "Doesn't this break your requirement for โ€œno constantsโ€?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-17T16:20:35.773", "Id": "16087", "Score": "0", "body": "@KeithS, any feedback on the suggested answers or comments?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-03T16:09:25.317", "Id": "26277", "Score": "0", "body": "@svick - There is a big difference between readonly and const in .NET. A readonly variable is basically a normal field variable with a few extra compile-time and runtime rules. Objects/assemblies that need it get it the same way they would a mutable field. A const is a value written into the manifest of any assembly that uses it, and all usages of the constant refer to their own assembly's manifest. So, constants require a recompile of any code that uses it, not just the one that declares it in source. That's why I want to avoid constants." } ]
[ { "body": "<p>A few things don't add up for me regarding your usage. You want compile time absolution, but dynamic values while stating the critical nature of its use. </p>\n\n<p>One option:\n You can just take care of this by having objects with inheritance structures and loading your \"dynamic\" values from an application configuration or db. Just have 3 layers of inheritance 1) StringEnum 2) Enum Declaration (like System638) and 3) actual values. Just wire up the inheritance. Mostly likely though, interfaces would be more appropriate for restrictions at the 1 &amp; 2 layers.</p>\n\n<p>Recommended (assuming the distributed smell of the use case):\n Build your functional class and bind it to a single DB table that ensures the integrity you are looking for. Just cache the values in memory for performance needs.</p>\n\n<p>Recommended (given the critical nature of its use)\n Find a different way to design the system so that you can fully embed what you need in code. For example, a web service. Even if you need a local presence you can utilize a web service to control the pieces you need.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-17T17:29:24.707", "Id": "16092", "Score": "0", "body": "Well, just for more specific reference, this is basically a wrapper for SQL stored procedures. You can pass the \"command\" which represents the SP into the Repository, and the repository can then drop it into the ADO.NET connection. That's the basis of the code smell; having to specify the procedure to use as a string is a necessary evil I'm trying to mitigate by forcing the use of a \"safe\" list of procedures." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-17T19:38:00.053", "Id": "16098", "Score": "0", "body": "Thank you for the clarification and feedback KeithS. What about utilizing an EF entity model and specifying the stored procs straight on it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-26T14:33:15.513", "Id": "16494", "Score": "0", "body": "Currently I'm using NHibernate, abstracted behind a basic Repository pattern. While NH does allow for the specification of SPs for create/update/delete, I need a little more control than that for my particular use case. My ideal scenario would be to not use SPs at all, but the data model precedes my development work by some years." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-14T18:46:50.063", "Id": "10022", "ParentId": "10016", "Score": "2" } }, { "body": "<p><strong>KISS!</strong> You are over-complicating things. Keep strings as strings. Keep the strings as readonly, not const. Generate the code at build time, possibly using a custom build task, which itself can be compiled in the same build. Here is a quick Python script to give you an idea:</p>\n\n<pre><code># Python script to generate your code\nprint('public static class CommandNames')\nprint('{')\nfor name, value in open('commands.txt').readlines():\n print(' public static readonly string {0} = \"{1}\";'.format(name, value))\nprint('}')\n</code></pre>\n\n<p>You do not have to stay in Python as I mentioned previously. Powershell or a custom build task will do.</p>\n\n<p><strong>EDIT:</strong> There is a more idiomatic way to generate code with Visual Studio -</p>\n\n<p><a href=\"http://www.hanselman.com/blog/T4TextTemplateTransformationToolkitCodeGenerationBestKeptVisualStudioSecret.aspx\" rel=\"nofollow\">http://www.hanselman.com/blog/T4TextTemplateTransformationToolkitCodeGenerationBestKeptVisualStudioSecret.aspx</a></p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ee847423.aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/ee847423.aspx</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-15T10:10:31.957", "Id": "16002", "Score": "0", "body": "-1: what about writing code `ExecuteCommand(CommandNames.DoSomething);`, does this still allow IDE auto-completion, or is one supposed to \"just know\" which values to use and ignore both autocomplete and JIT error-detection? Somehow I doubt that the IDE (let's say Visual Studio) would be able to adapt to a dynamic approach such as this; or would it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-15T13:48:09.040", "Id": "16008", "Score": "1", "body": "@ANeves, auto-generated code is used all the time in large software projects. Visual Studio generates code for accessing embedded Resources, project settings, etc. The question is whether this auto-complete will be fully available before you try to compile it. Well, let's not put a horse before a carriage - add the class in, build once, and then this will become a fully fledged class that you can use auto-complete on. I am not sure what you mean by a JIT-error detection. This class will act as of correctly written by a human. With the right project dependencies it will compile in 1st pass." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-16T09:56:12.600", "Id": "16046", "Score": "0", "body": "UGH, what was I thinking?!? Somehow I oversought that the class would of course be included in the project... my apologies; everything works as expected. What I meant by \"JIT error detection\" is that the IDE shows code errors as one types." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-16T09:59:06.060", "Id": "16047", "Score": "0", "body": "You are missing a close parenthesis on the second line, and you have the wrong curly bracket on the last line. It's completely unimportant, but if you corrected these I could remove my stupid -1. :/" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-14T19:01:55.443", "Id": "10024", "ParentId": "10016", "Score": "0" } } ]
{ "AcceptedAnswerId": "10022", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-14T16:00:48.430", "Id": "10016", "Score": "4", "Tags": [ "c#", "strings" ], "Title": "\"String Enum\" implementation - comments?" }
10016
<p>Here is a simple plugin I have written for a jQuery dropdown effect. Simple show / hide (although open classes may be better).</p> <p>When you click the HTML the event searches the whole DOM for a specific class and then hides it (or removes the open class), even if the dropdown is already close.</p> <p>Is there a way to only apply the events to open dropdowns somehow?</p> <pre><code>$.fn.dropdown = function () { return this.each(function () { // Initial varaibles var $this = $(this), $toggle = $this.find('.dropdown-toggle'), $dropdown = $this.find('.dropdown-menu'); // When clicking a dropdown toggle $toggle.click( function(e){ // Stop the default behaviour e.preventDefault(); // Clear any open dropdowns clearDrops(); // Stop the event from bubbling up the DOM tree e.stopPropagation(); // Toggle the dropdown $dropdown.toggle(); }); // Clear the dropdowns var clearDrops = function () { // Search the entire DOM for dropdowns &amp; hide them // THERE MUST BE A BETTER WAY $('.dropdown-menu').hide(); }; // Trigger the closing of dropdowns when clicking on the HTML $('html').bind('click', clearDrops); }); }; $('.dropdown').dropdown(); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-15T21:04:34.667", "Id": "16025", "Score": "0", "body": "Why `e.stopPropagation()`? Do you really want this not to prograte up the dom tree?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-16T10:55:07.813", "Id": "16049", "Score": "0", "body": "The reason is so I can have an event listener on the $('html') and close the dropdown when clicking anywhere other than the toggle (which stops the click event from bubbling)." } ]
[ { "body": "<p>Comments:</p>\n\n<ul>\n<li>Don't use the name 'dropdown' that has a very high probability for naming collisions with other libraries.</li>\n<li>I get that you might want to do stuff as a learning experience but you are recreating something that already exists (as a matter of fact a lot of versions of this widget exist). You might want to check out how something like <a href=\"http://harvesthq.github.com/chosen/\" rel=\"nofollow\">chosen</a> works.</li>\n<li>In a similar vein, this ain't gonna work with keyboard input. Maybe you don't need it, but people would expect a dropdown widget to work with keyboard input</li>\n<li>This seems to require that a certain html structure exists. Someone using this without that knowledge will get confusing and silent failures. The way that jquery ui widgets usually handle this is to hide the initial element and then use jquery.after() to create the expected elements right after it</li>\n<li>Actually you really should use the <a href=\"http://wiki.jqueryui.com/w/page/12138135/Widget%20factory\" rel=\"nofollow\">jquery ui widget factory</a> that is a better fit for this then just a bare jquery plugin. (Jquery plugins generally are better for adding behaviors, JqueryUi Widget Factory is the preferred way to create enhanced controls)</li>\n<li>Are you sure you want to only close dropdowns on a click event? That seems far too simplistic. What if someone opens your dropdown and uses the tab key to tab to other fields? Usually something like this will close when focus is lost (I believe that is the <code>blur</code> event)</li>\n<li>I'm not sure if everything is a child of the html element - detached pop-up dialogs made via jquery ui for example. (not sure about this one)</li>\n<li>You do not need to stop propogation nor clearMenus when the toggle is clicked. The click will propagate up to the html element and close it then.</li>\n<li>You will bind the clearDrops function to the html element's click event as many times as there are controls on the page - you only need it once. Do a check or unbind.</li>\n<li>Is scanning the whole DOM really a problem? The scan only happens when the user interacts with the page, she will have to click on things very quickly indeed for this to be a real preformance problem.</li>\n</ul>\n\n<p>A direct answer to your question: Just remember what dropdown controls have been initialized and hide those.</p>\n\n<pre><code>( function($) {\n var initializedDropdowns = $();\n\n $.fn.dropdown = function () {\n\n return this.each(function () {\n\n var $this = $(this),\n\n ...\n initializedDropdowns.add($this)\n ...\n var clearDrops = function () {\n initializedDropdowns.hide();\n };\n ...\n });\n\n };\n} )(jQuery)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-16T10:59:28.527", "Id": "16050", "Score": "0", "body": "Wow, quite the answer. Thanks. Yes I am aware this has been done many times but I couldn't find one that did exactly what I required. Also a lot of the existing plugins (like chosen) seem to offer way more functionality than I actually require.\n\nI hadn't considered the tab effect or keyboard navigation so thank you for that (not even Twitter Bootstrap does this).\n\nA very well formed answer, not only answering my question but educating me in the process. This is why I love this community." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-15T21:28:08.473", "Id": "10053", "ParentId": "10019", "Score": "1" } } ]
{ "AcceptedAnswerId": "10053", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-14T17:15:24.867", "Id": "10019", "Score": "2", "Tags": [ "javascript", "jquery", "plugin" ], "Title": "jQuery dropdown plugin to prevent scanning the whole DOM on every click" }
10019
<p>Is this the way PHP developers write PHP or is echoing the html the preferred method?</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;/head&gt; &lt;body&gt; &lt;?php require_once 'db_connect.php'; session_start(); $result = mysql_query("SELECT * FROM products"); ?&gt; &lt;table border=1&gt; &lt;th&gt; Product ID &lt;/th&gt; &lt;th&gt; Name &lt;/th&gt; &lt;th&gt; Description &lt;/th&gt; &lt;th&gt; Price &lt;/th&gt; &lt;th&gt; Image &lt;/th&gt; &lt;th colspan=2&gt; Action &lt;/th&gt; &lt;?php while($row = mysql_fetch_array($result)) { ?&gt; &lt;tr&gt; &lt;td&gt; &lt;?php echo $row['p_id']; ?&gt; &lt;/td&gt; &lt;td&gt; &lt;?php echo $row['p_name']; ?&gt; &lt;/td&gt; &lt;td&gt; &lt;?php echo $row['p_description']; ?&gt; &lt;/td&gt; &lt;td&gt; &lt;?php echo $row['p_price']; ?&gt; &lt;/td&gt; &lt;td&gt; &lt;?php echo $row['p_image_path']; ?&gt; &lt;/td&gt; &lt;td&gt; edit &lt;/td&gt; &lt;td&gt; delete &lt;/td&gt; &lt;/tr&gt; &lt;?php } ?&gt; &lt;/table&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-14T18:16:43.203", "Id": "15958", "Score": "1", "body": "If this was JSP I'd say absolutely not. You'd use the Java Standard Tag Library. I'm not sure if there is an equivalent for PHP." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-14T18:56:33.233", "Id": "60769", "Score": "0", "body": "I would suggest a framework or if it's just a simple site use a template library to separate as much as possible the logic from the view." } ]
[ { "body": "<p>In <strong>small scripts</strong>, it's OK. PHP has features to make this easier:</p>\n\n<ul>\n<li><code>&lt;?= $var ?&gt;</code> is equivalent to <code>&lt;?php echo $var ?&gt;</code> (such short tags should not be used at the beginning of the document).</li>\n<li><code>if (condition):</code> and <code>endif;</code> is equivalent to <code>if (condition) {</code> and <code>}</code>. (This <a href=\"http://php.net/manual/en/control-structures.alternative-syntax.php\" rel=\"nofollow\">alternative syntax</a> allows you to mark clearly the end of ifs and loops)</li>\n</ul>\n\n<p>PHP is at its core a templating language, which is why it works so well, and even though you could implement something else, it would provide no benefit. For larger programs, you would however separate concerns and use a framework encouraging you to have a view whose only role is to display HTML (<a href=\"http://codeigniter.com/\" rel=\"nofollow\">CodeIgniter</a> is a good example).</p>\n\n<p>Finally, don't use <code>mysql_*</code>, it's not secure! Consider using prepared statement in mysqli or PDO.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-14T18:54:07.777", "Id": "15962", "Score": "0", "body": "PHP in the beginning was a templating language. NOW it's nothing of the sort. Please stop saying stuff like this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-14T18:57:07.757", "Id": "15964", "Score": "1", "body": "It's not *a templating language*, but a lot of features help doing that. Templating code in PHP only serve to limit the power of templates, and frameworks such as CodeIgniter don't try to provide a templating language: you're encouraged to simply use PHP. So yes, at its *core*, it's a templating language." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-14T18:59:24.913", "Id": "15965", "Score": "0", "body": "Another way to see it is to say that the subset of PHP I showed in my answer is a useful templating language, and no templating tool would make it better (except at limiting feature abuse)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-14T22:07:12.210", "Id": "15970", "Score": "0", "body": "I think he means php is an embedded language." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-14T22:22:51.973", "Id": "15972", "Score": "1", "body": "According to PHP manual the mysql_* functions are not deprecated. Though there exists the *improved* mysqli, I'd say it's actually a worse API than the older one." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-15T08:16:32.367", "Id": "15997", "Score": "1", "body": "I think this advice is mostly about prepared statements, which allow you to write queries that are more secure." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-14T18:26:34.090", "Id": "10021", "ParentId": "10020", "Score": "1" } }, { "body": "<p>A few points: </p>\n\n<p>Put the session_start() and as much of processing as possible on top of the file, <strong>before any output</strong>. This will be useful for emitting http-headers.</p>\n\n<p>When using a database: don't forget to handle <strong>exceptions</strong>.</p>\n\n<p>When using a database: don't forget to handle <strong>charsets</strong>. </p>\n\n<p>When selecting from the database: always <strong>limit</strong> your results. Add pagination of some kind.</p>\n\n<p>Do not use mysql_*, use a db library that offers <strong>prepared statements</strong> and is as db-independent as possible. I would recommend <strong>PDO</strong>. I would also recommend getting the data from the db as objects. If necessary you can define a class to hold some methods you need for these objects.</p>\n\n<p>I cuncur with Cygal: using php as the templating language is quite ok. See Wordpress for an example where this is used extensively in themes.</p>\n\n<p>Try to write your HTML in a compact, <strong>readable</strong> way. No matter what you use for templating: HTML is an important part of your code, and should be just as readable as any other code you write.</p>\n\n<p>Output <strong>valid HTML</strong>. Don't forget question marks around attribute values, don't forget -Tags. </p>\n\n<pre><code> &lt;?php\n\n session_start();\n include \"config.php\";\n if( ! $DB_NAME ) die('please create config.php, define $DB_NAME, $DB_USER, $DB_PASS there');\n\n try {\n\n $dbh = new PDO(\"mysql:dbname=$DB_NAME\", $DB_USER, $DB_PASS);\n $dbh-&gt;exec('SET CHARACTER SET utf8') ;\n\n $result = $dbh-&gt;query(\"SELECT * FROM products LIMIT 0,20\");\n $products = $result-&gt;fetchAll(PDO::FETCH_OBJ);\n\n } catch( Exception $e ) {\n\n error_log( $e-&gt;getMessage() . \" \". $e-&gt;getTraceAsString() );\n include(\"500-failwhale.php\");\n exit;\n }\n ?&gt;\n\n &lt;!DOCTYPE html&gt;\n &lt;html&gt;\n &lt;head&gt;\n &lt;title&gt;Products&lt;/title&gt;\n &lt;meta charset=\"utf-8\"&gt;\n &lt;/head&gt;\n &lt;body&gt;\n\n &lt;table class=\"with_border\"&gt;\n &lt;tr&gt;\n &lt;th&gt;Product ID &lt;/th&gt; \n &lt;th&gt;Name &lt;/th&gt; \n &lt;th&gt;Description &lt;/th&gt; \n &lt;th&gt;Price &lt;/th&gt; \n &lt;th&gt;Image &lt;/th&gt; \n &lt;th colspan=\"2\"&gt; Action &lt;/th&gt; \n &lt;/tr&gt;\n &lt;?php foreach($products as $p) : ?&gt;\n &lt;tr&gt;\n &lt;td&gt;&lt;?= $p-&gt;p_id ?&gt;&lt;/td&gt;\n &lt;td&gt;&lt;?= $p-&gt;p_name ?&gt;&lt;/td&gt;\n &lt;td&gt;&lt;?= $p-&gt;p_description ?&gt;&lt;/td&gt;\n &lt;td&gt;&lt;?= $p-&gt;p_price ?&gt;&lt;/td&gt;\n &lt;td&gt;&lt;?php if ( $p-&gt;p_image_path ) : ?&gt;\n &lt;img src=\"&lt;?= $p-&gt;p_image_path ?&gt;\" alt=\"&lt;?= $p-&gt;p_name ?&gt;\"&gt;\n &lt;?php endif; ?&gt;&lt;/td&gt;\n &lt;td&gt;edit&lt;/td&gt;\n &lt;td&gt;delete&lt;/td&gt;\n &lt;/tr&gt;\n &lt;?php endforeach; ?&gt;\n\n &lt;/table&gt;\n\n &lt;/body&gt;\n &lt;/html&gt;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-15T23:27:36.833", "Id": "10057", "ParentId": "10020", "Score": "3" } }, { "body": "<blockquote>\n <p>Is this the way PHP developers write PHP or is echoing the html the preferred method?</p>\n</blockquote>\n\n<p>In my opinion, neither are.\nThe first and most important thing to learn about writing good PHP code is that you must separate the code that gathers data from the code that outputs it.</p>\n\n<p>In your sample code this means that you don't call your data extracting function and display what you get, but you stuff everything in an array and later display its contents. This is really important: even if you write everything in one script, the two pieces of your code should be completely separated so that it could be possible to split them in two files with close to no changes.</p>\n\n<p>This means that you can change how you display your data without touching how you get them, or you can change the source of your data and keep the output exactly as it is (so long as you follow some conventions regarding variable names and data formats).</p>\n\n<p>As already mentioned, you can't call <code>session_start()</code> after output has already being sent (your output being the first lines of HTML) as starting a session implies setting headers and you can't do that once they have already been sent.</p>\n\n<p>Also I would advice <strong>against</strong> the use of short open tags (<code>&lt;?= $var ?&gt;</code>) @Cygal suggests, as they are not recommended and by default disabled on many hosting services.</p>\n\n<p>Regarding the interface to the database, while in simple scripts it can be okay, I think it's useful to skip <code>mysql_*</code> functions in favor of the PDO interface which gives you a lot of advantages (most notably prepared statements) at the little cost of learning its syntax.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-16T13:56:13.457", "Id": "10067", "ParentId": "10020", "Score": "0" } }, { "body": "<p>I would recommend to change the while loop, so it will handle any rows:</p>\n\n<pre><code>while($row = mysql_fetch_array($result))\n{\n echo '&lt;tr&gt;'\n foreach ($row as $key =&gt; $value) {\n echo '&lt;td&gt;' . $value . '&lt;/td&gt;'\n }\n echo '&lt;td&gt; edit &lt;/td&gt; &lt;td&gt; delete &lt;/td&gt; &lt;/tr&gt;'\n}\n</code></pre>\n\n<p>and if you do not want to output all values from the row, but just a subset, or if you want particular order in output it is better to modify your SQL query as appropriate.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-16T14:26:23.047", "Id": "10069", "ParentId": "10020", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-14T18:03:23.260", "Id": "10020", "Score": "2", "Tags": [ "php", "html" ], "Title": "Is this an acceptable way of writing PHP code(in scriptlets)" }
10020
<pre><code>public class BuscaDiretaBusiness { PortalIOEntities portalIO = new PortalIOEntities(); public IQueryable CarregaAlias(out int ItemsCount) { var query = from a in portalIO.DO_CadernoBuscaDiretaAlias select new { a.CDP_ID, a.CDA_Alias, a.DO_CadernoDeParaBuscaDireta.CDP_NomeCaderno }; ItemsCount = query.Count(); return query; } } </code></pre> <p>Will it make two selects on DataBase?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-14T19:37:48.520", "Id": "15968", "Score": "6", "body": "Why not just return the IQueryable. Do you need to pass in an out parameter? And yes, that is the way to get count of items" } ]
[ { "body": "<p>You're fine. It will only make 1 query.</p>\n\n<p>Plus dreza is right, don't pass back \"count\" through the out parameter. It isn't needed. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-14T19:57:50.070", "Id": "10029", "ParentId": "10026", "Score": "3" } }, { "body": "<p>Typically that's the correct way to get a count, yes. Linq2sql and Linq2Nh for instance will see the Count operator and create a COUNT(*) query at TSQL level. So it'll hit the db once when .Count() is called on the IQueryable, returning a single row containing the count.</p>\n\n<p>Note that it'd hit the db again if you call .Count() again. Your method appears to have two responsibilities at present - I'd just return the required IQueryable and call the .Count() on it elsewhere. Then you can still easily grab the IQueryable if you actually need to enumerate the results later</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-15T10:43:08.380", "Id": "10041", "ParentId": "10026", "Score": "1" } }, { "body": "<p>That method will only hit the DB once, with a query like <code>SELECT COUNT(*) โ€ฆ</code>. But if you try to enumerate the resulting <code>IQueryable</code> in any way (like calling <code>ToArray()</code> on it or using it in a <code>foreach</code>), it will make another DB query.</p>\n\n<p>You should probably only return the <code>IQueryable</code>. If the consumer needs all the items, it will call <code>ToArray()</code> or similar, which will make one DB query and then look at the <code>Length</code> of the result (which of course won't make another query). If the consumer needs only part of the result (e.g. it will call <code>Take(100)</code>) and it also needs the total count, it will call <code>Count()</code> itself. This will mean there will be two queries, but I think it can't be done differently.</p>\n\n<p>Also, you probably should not be returning a collection of an anonymous type from a method, because it's hard to use.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-15T19:00:38.463", "Id": "10048", "ParentId": "10026", "Score": "11" } } ]
{ "AcceptedAnswerId": "10048", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-14T19:24:40.500", "Id": "10026", "Score": "5", "Tags": [ "c#", ".net", "linq" ], "Title": "Is it a good way to get Count on Linq?" }
10026
<p>I'm trying to reflect a ray of a triangle using <a href="http://processing.org/" rel="nofollow noreferrer">Processing</a> and not sure I got the code right. I'm using two bits of pseudo code from two locations:</p> <ol> <li>Intersection of a Line with a Plane from <a href="http://paulbourke.net/geometry/planeline/" rel="nofollow noreferrer">Paul Bourke's site</a>.</li> <li>Reflecting a vector from <a href="http://www.3dkingdoms.com/weekly/weekly.php?a=2" rel="nofollow noreferrer">3DKingdoms</a> site.</li> </ol> <p>Here's my code so far:</p> <pre><code>PVector[] face = new PVector[3]; float ai = TWO_PI/3;//angle increment float r = 300;//overall radius float ro = 150;//random offset PVector n;//normal Ray r1; void setup(){ size(500,500,P3D); for(int i = 0 ; i &lt; 3; i++) face[i] = new PVector(cos(ai * i) * r + random(ro),random(-50,50),sin(ai * i) * r + random(ro)); r1 = new Ray(new PVector(-100,-200,-300),new PVector(100,200,300)); } void draw(){ background(255); lights(); translate(width/2, height/2,-500); rotateX(map(mouseY,0,height,-PI,PI)); rotateY(map(mouseX,0,width,-PI,PI)); //draw plane beginShape(TRIANGLES); for(PVector p : face) vertex(p.x,p.y,p.z); endShape(); //normals PVector c = new PVector();//centroid for(PVector p : face) c.add(p); c.div(3.0); PVector cb = PVector.sub(face[2],face[1]); PVector ab = PVector.sub(face[0],face[1]); n = cb.cross(ab);//compute normal line(c.x,c.y,c.z,n.x,n.y,n.z);//draw normal pushStyle(); //http://paulbourke.net/geometry/planeline/ //line to plane intersection u = N dot ( P3 - P1 ) / N dot (P2 - P1), P = P1 + u (P2-P1), where P1,P2 are on the line and P3 is a point on the plane PVector P2SubP1 = PVector.sub(r1.end,r1.start); PVector P3SubP1 = PVector.sub(face[0],r1.start); float u = n.dot(P3SubP1) / n.dot(P2SubP1); PVector P = PVector.add(r1.start,PVector.mult(P2SubP1,u)); strokeWeight(5); point(P.x,P.y,P.z);//point of ray-plane intersection //vector reflecting http://www.3dkingdoms.com/weekly/weekly.php?a=2 //R = 2*(V dot N)*N - V //Vnew = -2*(V dot N)*N + V //PVector V = PVector.sub(r1.start,r1.end); PVector V = PVector.sub(r1.start,P); PVector R = PVector.sub(PVector.mult(n,3 * (V.dot(n))),V); strokeWeight(1); stroke(0,192,0); line(P.x,P.y,P.z,R.x,R.y,R.z); stroke(192,0,0); line(r1.start.x,r1.start.y,r1.start.z,P.x,P.y,P.z); stroke(0,0,192); line(P.x,P.y,P.z,r1.end.x,r1.end.y,r1.end.z); popStyle(); } void keyPressed(){ setup(); }//reset class Ray{ PVector start = new PVector(),end = new PVector(); Ray(PVector s,PVector e){ start = s ; end = e; } } </code></pre> <p>I've tried to keep it simple and comment it. Still, the reflected vector (drawn in green) doesn't seem to be quite right:</p> <p><img src="https://i.stack.imgur.com/DrK7C.png" alt="reflect 1"> <img src="https://i.stack.imgur.com/I3ddY.png" alt="reflect 2"></p> <p>I'm not sure if the reflected vector should meet the normal. Should I normalize/scale some vectors at some point? </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-15T09:53:22.837", "Id": "16000", "Score": "0", "body": "It definitely looks wrong, but it could be due to 3D perspective. The reflected vector only meets a normal (I guess you mean the one raising from the centre of the shape) by coincidence. 3dkingdoms having picked an example so close to 45ยฐ is an unfortunate decision, makes it hard to see what is supposed to happen." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-15T09:57:08.213", "Id": "16001", "Score": "0", "body": "Are you confident about the mathematical formulas being right? I tried looking at it, but it's been a while since I thought about vectors and don't want to get it wrong... so I'll pass. In 2D, a ray with incidence angle of Nยฐ reflects with a (180-N)ยฐ angle: it is mirrored through a perpendicular to the reflector line, this perpendicular raising from the point of incidence. I think the 3D version can be reduced to a 2D problem if you constrain it to the plane including the ray and the normal raising from the incidence point." } ]
[ { "body": "<p>Turns out I needed to normalize the normal first:</p>\n\n<pre><code>n.normalize();\n</code></pre>\n\n<p>full code for reference:</p>\n\n<pre><code>PVector[] face = new PVector[3];\nfloat ai = TWO_PI/3;//angle increment\nfloat r = 300;//overall radius\nfloat ro = 150;//random offset\n\nPVector n;//normal\nRay r1;\n\nvoid setup() {\n size(500, 500, P3D);\n for (int i = 0 ; i &lt; 3; i++) face[i] = new PVector(cos(ai * i) * r + random(ro), random(-50, 50), sin(ai * i) * r + random(ro));\n r1 = new Ray(new PVector(-100, -200, -300), new PVector(100, 200, 300));\n}\nvoid draw() {\n background(255);\n lights();\n translate(width/2, height/2, -500);\n rotateX(map(mouseY, 0, height, -PI, PI));\n rotateY(map(mouseX, 0, width, -PI, PI));\n //draw plane\n beginShape(TRIANGLES);\n for (PVector p : face) vertex(p.x, p.y, p.z);\n endShape();\n //normals\n PVector c = new PVector();//centroid\n for (PVector p : face) c.add(p);\n c.div(3.0);\n PVector cb = PVector.sub(face[2], face[1]);\n PVector ab = PVector.sub(face[0], face[1]);\n n = cb.cross(ab);//compute normal\n n.normalize();\n line(c.x, c.y, c.z, n.x, n.y, n.z);//draw normal\n\n pushStyle();\n //http://paulbourke.net/geometry/planeline/\n //line to plane intersection u = N dot ( P3 - P1 ) / N dot (P2 - P1), P = P1 + u (P2-P1), where P1,P2 are on the line and P3 is a point on the plane\n PVector P2SubP1 = PVector.sub(r1.end, r1.start);\n PVector P3SubP1 = PVector.sub(face[0], r1.start);\n float u = n.dot(P3SubP1) / n.dot(P2SubP1);\n PVector P = PVector.add(r1.start, PVector.mult(P2SubP1, u));\n strokeWeight(5);\n point(P.x, P.y, P.z);//point of ray-plane intersection\n\n //vector reflecting http://www.3dkingdoms.com/weekly/weekly.php?a=2\n //R = 2*(V dot N)*N - V\n //Vnew = -2*(V dot N)*N + V\n //PVector V = PVector.sub(r1.start,r1.end);\n PVector V = PVector.sub(r1.start, P);\n PVector R = PVector.sub(PVector.mult(n, 2 * (V.dot(n))), V);\n strokeWeight(1);\n stroke(0, 192, 0);\n line(P.x, P.y, P.z, R.x, R.y, R.z);\n stroke(192, 0, 0);\n line(r1.start.x, r1.start.y, r1.start.z, P.x, P.y, P.z);\n stroke(0, 0, 192);\n line(P.x, P.y, P.z, r1.end.x, r1.end.y, r1.end.z);\n popStyle();\n}\nvoid keyPressed() { \n setup();\n}//reset\nclass Ray {\n PVector start = new PVector(), end = new PVector();\n Ray(PVector s, PVector e) { \n start = s ; \n end = e;\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-27T20:45:05.753", "Id": "10381", "ParentId": "10028", "Score": "4" } } ]
{ "AcceptedAnswerId": "10381", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-14T19:36:06.430", "Id": "10028", "Score": "3", "Tags": [ "computational-geometry", "processing", "raytracing" ], "Title": "Ray reflection with a triangle" }
10028
<p>I am a moderately new Scala developer working mostly by myself, so I don't have anyone to tell me what I'm doing wrong (except that the system mostly does work, so it can't be too awful). I would appreciate some feedback on how to make better use of Scala as well as any comments about obvious performance issues.</p> <p>The class below is part of our utility library. It's part of our OSGi-like infrastructure. I didn't use OSGi because the web application is hosted on a Tomcat server but I liked many of the ideas behind it, so I've incorporated them into my own library.</p> <pre><code>package edu.stsci.efl.ml import scala.collection.mutable.{HashSet, Stack, HashMap} import scala.xml.Node import java.util.Date /** * Provides a container for services that are being provided by various modules. * * The default context can be had from the ModuleLoader object. * * Services are accessed by the class of the trait that they implement. For example, * logging services implement LoggerFactoryService so to get access the service, call * getService(classOf[LoggerFactoryService]) to find the service that was defined in * the ModuleLoader configuration file. */ class EFLContext(val name: String) { private var modules: HashMap[String, EFLModule] = new HashMap[String, EFLModule] private val shutdownList: Stack[EFLModule] = new Stack[EFLModule] private val importList: Stack[EFLModule] = new Stack[EFLModule] private val services = new HashSet[Object] private var myDependencies: List[EFLContext] = null private var myDependents: List[EFLContext] = null /** * Used in testing to verify that the correct number of modules have been loaded. */ def getModuleCount = modules.size /** * Use by the ModuleLoader to pass a module definition from the XML configuration file. */ def load(moduleDefinition: Node) { val moduleName = (moduleDefinition \ "@name").toString() val className = (moduleDefinition \ "@class").toString() try { val rawClass = Class.forName(className) val moduleClass = rawClass.asSubclass(classOf[EFLModule]) val instance = moduleClass.newInstance instance.start(this, moduleDefinition) shutdownList.push(instance) modules.put(moduleName, instance) } catch { case e: Exception =&gt; { println("Failed to initialize module. Error:") e.printStackTrace() throw new EFLInitializationFailure(moduleDefinition.toString(), e) } } } /** * */ def resolveImport(data: Node) { val contextName = getAttribute(data, "context") val name = getAttribute(data, "name") val module = { val context = ModuleLoader.getContext(contextName) if (context == null) null else { val result = context.modules.getOrElse(name, null) if (result != null) addDependency(context) result } } if (module == null) throw new IllegalArgumentException("Unable to resolve import of module '" + name + "' in context '" + contextName + "'.") module.addContext(this) importList.push(module) modules.put(name, module) } def getAttribute(data: Node, name: String): String = { val attribute = data.attribute(name) if (attribute.isEmpty) throw new IllegalArgumentException("Failed to specify attribute " + name + " in import.") attribute.head.toString() } /** * Used by modules at application startup to announce services that they are providing. */ def addService(service: Object) { services += service } /** * */ def addDependency(fLContext: EFLContext) { myDependencies match { case null =&gt; myDependencies = List[EFLContext](fLContext) case _ =&gt; myDependencies = myDependencies :+ fLContext } fLContext.addDependent(this) } /** * */ def addDependent(fLContext: EFLContext) { myDependents match { case null =&gt; myDependents = List[EFLContext](fLContext) case _ =&gt; myDependents = myDependents :+ fLContext } } def hasDependents: Boolean = (myDependents != null) def removeDependency(context: EFLContext) { myDependencies = myDependencies.filterNot((c: EFLContext) =&gt; c == context) if (myDependencies.isEmpty) myDependencies = null context.removeDependent(this) } def removeDependent(context: EFLContext) { myDependents = myDependents.filterNot((c: EFLContext) =&gt; c == context) if (myDependents.isEmpty) myDependents = null } /** * Used by modules at application shutdown to terminate services. */ def removeService(service: Object) = { services -= service } /** * Called by the ModuleLoader at application shutdown so that loaded modules can be stopped. */ def shutdown() { if (modules == null) throw new RuntimeException("Attempt to shutdown context that was already shutdown.") if (hasDependents) throw new RuntimeException("Attempt to shutdown context with loaded dependent contexts.") while (!importList.isEmpty) { val next = importList.pop() next.removeContext(this) } while (!shutdownList.isEmpty) { val next = shutdownList.pop() next.stop(this) } modules.clear() if (services.size &gt; 0) { println("Improper cleanup: " + services.size + " services still registered.") services.foreach((s) =&gt; println(s)) } modules = null while (myDependencies != null) { val next = myDependencies.head removeDependency(next) } } /** Search for a given service by the class/trait the service implements/extends. * * @param serviceClass The class of a service that is needed. * @return Option[A] 'Some' of the given type, or 'None' if no service object extending that type is registered. */ def findService[A](serviceClass: Class[A]): Option[A] = { services.find(serviceClass.isInstance).asInstanceOf[Option[A]] } /** Search for a given service by the class/trait the service implements/extends. * * @return Service of the given type, or null if no service object extending that type is registered. */ @Deprecated def getService[A](serviceClass: Class[A]): A = { val temp = services.find(serviceClass.isInstance) if (temp == None) { null.asInstanceOf[A] } else { temp.get.asInstanceOf[A] } } } </code></pre>
[]
[ { "body": "<p><strong>Some words at beginning:</strong> I have never used OSGI, so I can't say if the tips below may all work in your context. If they do not, than keep them in the back of your head and use them when you can.</p>\n\n<hr>\n\n<p>One of the most important rules is to avoid mutable state if possible. This will result in more type-safe and easier to read code. This is not always possible but most times it is.</p>\n\n<hr>\n\n<p>Never use null if you don't have to use it. Use <code>Option</code> type instead or use empty collections.</p>\n\n<pre><code>private var myDependencies: List[EFLContext] = null\n// =&gt;\nprivate var myDependencies: List[EFLContext] = Nil\n</code></pre>\n\n<p>Now you don't have to pattern match against null any more:</p>\n\n<pre><code>def addDependency(fLContext: EFLContext) {\n myDependencies match {\n case null =&gt; myDependencies = List[EFLContext](fLContext)\n case _ =&gt; myDependencies = myDependencies :+ fLContext\n }\n fLContext.addDependent(this)\n}\n// =&gt;\ndef addDependency(fLContext: EFLContext) {\n myDependencies +:= flContext\n fLContext addDependent this\n}\n</code></pre>\n\n<p>Here, never append to a List, this is inefficient (O(n)). Instead use prepending (O(1)). If you have to prepend elements, than use an <code>IndexedSeq</code>. If you want you can use operator notation.</p>\n\n<hr>\n\n<p>In Scala everything returns a value, thus there is no need to mark a method that it returns a value:</p>\n\n<pre><code>def getModuleCount = modules.size\n// =&gt;\ndef moduleCount = modules.size\n</code></pre>\n\n<hr>\n\n<p>method <code>-=</code> is deprecated. Use <code>filterNot</code> instead.</p>\n\n<hr>\n\n<p>Scala has some nice methods defined in Predef. One of them can check input params:</p>\n\n<pre><code>if (modules == null) throw new RuntimeException(\"Attempt to shutdown context that was already shutdown.\")\n// =&gt;\nrequire(modules.nonEmpty, \"Attempt to shutdown context that was already shutdown.\")\n</code></pre>\n\n<hr>\n\n<p>Don't traverse through the elements of a collection with a while-loop. Instead use higher-order functions (foreach instead of while-loop). Furthermore in Scala there is no need to explicitly use a Stack. A List is already a Stack (when you prepend elements what you should do)!</p>\n\n<pre><code>while (!importList.isEmpty) {\n val next = importList.pop()\n next.removeContext(this)\n}\n// =&gt;\nimportList foreach { _ removeContext this }\nimportList = Nil\n</code></pre>\n\n<hr>\n\n<p>Pattern match Options:</p>\n\n<pre><code>if (opt.isDefined) ...\nelse opt.get ...\n\nopt match {\n case None =&gt; ...\n case Some(o) =&gt; o ...\n}\n</code></pre>\n\n<hr>\n\n<p>Use homogeneous types in collections and not <code>Object</code> if possible.</p>\n\n<pre><code>private val services = new HashSet[Object]\n// =&gt;\nval services1 = new HashSet[Type1]\nval servicesN = new HashSet[TypeN]\n</code></pre>\n\n<p>If you do so there is no need for casts any more like in your method <code>findService</code>. Of course you should choose better names for the variables than I did.</p>\n\n<hr>\n\n<p>To easily come from null to <code>Option</code> you can use its apply method:</p>\n\n<pre><code>Option(null) // =&gt; None\nOption(non_null_value) // =&gt; Some(non_null_value)\n</code></pre>\n\n<p>No need to use curly brackets in a case-block:</p>\n\n<pre><code>case _ =&gt; {\n a\n b\n}\n// =&gt;\ncase _ =&gt;\n a\n b\n</code></pre>\n\n<p>You can use Option in method <code>resolveImport</code>:</p>\n\n<pre><code>def resolveImport(data: Node) {\n val contextName = getAttribute(data, \"context\")\n val name = getAttribute(data, \"name\")\n val context = Option(ModuleLoader.getContext(contextName))\n val result = context flatMap { _.modules get name }\n result match {\n case None =&gt;\n throw new IllegalArgumentException(\"Unable to resolve import of module '\"+name+\"' in context '\"+contextName+\"'.\") \n case Some(module) =&gt;\n this addDependency module\n module addContext this\n importList push module\n modules += name -&gt; module\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-16T13:48:44.700", "Id": "16052", "Score": "0", "body": "Lots of good stuff! The comment about services won't work because no two services are of the same type - a context is sort of a phone directory where objects that provide a given service can be found by objects that need that particular service. I already knew that curly braces were not needed in case blocks - as a matter of personal taste I find adding them makes the structure clearer. Thank you!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-16T13:42:12.883", "Id": "10066", "ParentId": "10030", "Score": "10" } } ]
{ "AcceptedAnswerId": "10066", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-14T20:24:35.743", "Id": "10030", "Score": "10", "Tags": [ "scala", "library" ], "Title": "OSGi-like infrastructure" }
10030
<p>This is supposed to be strict ANSI C89 pedantic code. It should extract <code>word1</code>, <code>word2</code> and <code>word3</code> from a string formatted [ word1 ] word2 [ word3 ] and return failure in any other format.</p> <p>It seems to work, but it seems so ugly. No need to comment about the fact <code>GetTokenBetweenSquareBraces</code> and <code>GetTokenBtweenOpositeSquareBraces</code> are duplicates.</p> <p>I would love some tips on how to clean this up.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &lt;ctype.h&gt; char * TrimWhiteSpaces(char *str) { char *out = str; int i; int len = strlen(str); for (i=0; i&lt;len &amp;&amp; isspace(str[i]); i++, out++); /*scan forward*/ for (i=len-1; i&gt;=0 &amp;&amp; isspace(str[i]); str[i]=0, i--);/*scan backward*/ return out; } char * GetTokenBetweenSquareBraces(char * input, char **output, int * output_size) { char *p = TrimWhiteSpaces(input); *output_size=0; if (p[0] == '[') { *output = TrimWhiteSpaces(p + 1); do { (*output_size)++; }while((*output)[*output_size] != ']' &amp;&amp; isalnum((*output)[*output_size])); } else { return NULL; } return (*output) + *output_size; } char * GetTokenBtweenOpositeSquareBraces(char * input, char **output, int * output_size) { char *p = TrimWhiteSpaces(input); *output_size=0; if (p[0] == ']') { *output = TrimWhiteSpaces(p + 1); do { (*output_size)++; }while((*output)[*output_size] != '[' &amp;&amp; isalnum((*output)[*output_size])); } else { return NULL; } return (*output) + *output_size; } int GetWords(char * str,char * word1,char * word2,char * word3) { char * next=NULL,*output=NULL; int outputsize; printf ("\nSplitting string \"%s\" into tokens:\n",str); next = GetTokenBetweenSquareBraces (str,&amp;output,&amp;outputsize); strncpy(word1,output,outputsize); word1[outputsize] = '\0'; strcpy(word1,TrimWhiteSpaces(word1)); if(!next) return 0; next = GetTokenBtweenOpositeSquareBraces (next,&amp;output,&amp;outputsize); strncpy(word2,output,outputsize); word2[outputsize] = '\0'; strcpy(word2,TrimWhiteSpaces(word2)); if(!next) return 0; next = GetTokenBetweenSquareBraces (next,&amp;output,&amp;outputsize); strncpy(word3,output,outputsize); word3[outputsize] = '\0'; strcpy(word3,TrimWhiteSpaces(word3)); if(!next) return 0; return 1; } void TestGetWords(char * str ) { char word1[20],word2[20],word3[20]; if (GetWords(str,word1,word2,word3)) { printf("|%s|%s|%s|\n",word1,word2,word3); } else { printf("3ViLLLL\n"); } } int main (void) { char str[] ="[ hello ] gfd [ hello2 ] "; char str2[] ="[ hello [ gfd [ hello2 ] "; char str3[] ="the wie321vg42g42g!@#"; char str4[] ="][123[]23][231["; TestGetWords(str); TestGetWords(str2); TestGetWords(str3); TestGetWords(str4); getchar(); return 1; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-14T22:10:13.440", "Id": "15971", "Score": "0", "body": "First off fix your indentation. Markdown engine doesn't like tabs - replace them with spaces." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-14T22:27:36.557", "Id": "15976", "Score": "0", "body": "@LokiAstari: it looks like you replaced his original code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-14T22:34:16.580", "Id": "15978", "Score": "0", "body": "Opps. Sorry. Fixed my screw up I hope. I got the code from the article on meta. fixed the tab problem and put it back. If this is not correct I am sorry, but I can't seem to rollback a version." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-14T22:39:24.470", "Id": "15979", "Score": "0", "body": "@LokiAstari: Yep, looks a lot better." } ]
[ { "body": "<pre><code>#include &lt;stdio.h&gt;\n#include &lt;string.h&gt;\n#include &lt;ctype.h&gt;\n\nchar * TrimWhiteSpaces(char *str) {\n char *out = str;\n int i;\n int len = strlen(str);\n for (i=0; i&lt;len &amp;&amp; isspace(str[i]); i++, out++); /*scan forward*/\n</code></pre>\n\n<p>I'd at least have a body with a comment in it here. Its easy to miss that semicolon. I don't think you need the <code>i &lt; len</code> test. The 0 at the end of the string should fail the <code>isspace</code> test and so you don't need to check for the length as well. It also doesn't really make sense to keep track of <code>i</code>. Instead, just use <code>out</code>.</p>\n\n<pre><code> for (i=len-1; i&gt;=0 &amp;&amp; isspace(str[i]); str[i]=0, i--);/*scan backward*/\n</code></pre>\n\n<p>It isn't really necessary to set all those spaces to 0. Overall, you are doing to much work in that one line. You should at least only do the 0 setting inside the loop body because it has nothing to do with the loop control.</p>\n\n<pre><code> return out;\n</code></pre>\n\n<p>Generally, its best to either modify your parameters or return new ones. Don't do both. Here you return a new string pointer and modify the original string. </p>\n\n<pre><code>}\nchar * GetTokenBetweenSquareBraces(char * input, char **output, int * output_size) {\n char *p = TrimWhiteSpaces(input);\n *output_size=0;\n if (p[0] == '[')\n {\n *output = TrimWhiteSpaces(p + 1);\n do \n { \n (*output_size)++; \n }while((*output)[*output_size] != ']' &amp;&amp; isalnum((*output)[*output_size]));\n</code></pre>\n\n<p><code>]</code> isn't a number or a letter. You don't need both of these tests. </p>\n\n<pre><code> }\n else\n {\n return NULL;\n }\n return (*output) + *output_size;\n}\n\nchar * GetTokenBtweenOpositeSquareBraces(char * input, char **output, int * output_size) {\n char *p = TrimWhiteSpaces(input);\n *output_size=0;\n if (p[0] == ']')\n {\n *output = TrimWhiteSpaces(p + 1);\n do \n { \n (*output_size)++; \n }while((*output)[*output_size] != '[' &amp;&amp; isalnum((*output)[*output_size]));\n }\n else\n {\n return NULL;\n }\n return (*output) + *output_size;\n}\n</code></pre>\n\n<p>Deja Vu! This is almost exactly the same as the previous function. Only the bracket directions have been reversed. It seems that you should be able to share that code.</p>\n\n<pre><code>int GetWords(char * str,char * word1,char * word2,char * word3)\n{\n char * next=NULL,*output=NULL;\n\n int outputsize;\n printf (\"\\nSplitting string \\\"%s\\\" into tokens:\\n\",str);\n</code></pre>\n\n<p>Generally I recommend against having your working functions doing any output. Also odd choice of where to put newlines.</p>\n\n<pre><code> next = GetTokenBetweenSquareBraces (str,&amp;output,&amp;outputsize);\n strncpy(word1,output,outputsize);\n word1[outputsize] = '\\0';\n strcpy(word1,TrimWhiteSpaces(word1));\n</code></pre>\n\n<p>Why are you trimming whitespace here? Didn't you already do that. You are doing a lot of work to copy the text. Maybe that's something that GetTokenBetweenSquareBraces should have done?</p>\n\n<pre><code> if(!next) return 0;\n\n next = GetTokenBtweenOpositeSquareBraces (next,&amp;output,&amp;outputsize);\n strncpy(word2,output,outputsize);\n word2[outputsize] = '\\0';\n strcpy(word2,TrimWhiteSpaces(word2));\n\n if(!next) return 0;\n</code></pre>\n\n<p>Deja Vu! </p>\n\n<pre><code> next = GetTokenBetweenSquareBraces (next,&amp;output,&amp;outputsize);\n strncpy(word3,output,outputsize);\n word3[outputsize] = '\\0';\n strcpy(word3,TrimWhiteSpaces(word3));\n\n if(!next) return 0;\n</code></pre>\n\n<p>Deja Vu! </p>\n\n<pre><code> return 1;\n}\nvoid TestGetWords(char * str )\n{\n char word1[20],word2[20],word3[20];\n</code></pre>\n\n<p>Your code isn't careful to make sure that you don't overflow these variables. You may want to do something about that</p>\n\n<pre><code> if (GetWords(str,word1,word2,word3))\n {\n printf(\"|%s|%s|%s|\\n\",word1,word2,word3);\n }\n else\n {\n printf(\"3ViLLLL\\n\");\n }\n\n}\nint main (void)\n{\n char str[] =\"[ hello ] gfd [ hello2 ] \";\n char str2[] =\"[ hello [ gfd [ hello2 ] \";\n char str3[] =\"the wie321vg42g42g!@#\";\n char str4[] =\"][123[]23][231[\";\n\n TestGetWords(str);\n TestGetWords(str2);\n TestGetWords(str3);\n TestGetWords(str4);\n</code></pre>\n\n<p>For purposes of automated testing, its actually better if you provide the correct answer and check against that in code. That way the program will tell you when its wrong.</p>\n\n<pre><code> getchar();\n return 1;\n</code></pre>\n\n<p>0 is used to indicate a successful program run.</p>\n\n<pre><code>}\n</code></pre>\n\n<p>Overall, your program is ugly because you are using the wrong vocabulary. You've taken the vocabulary as given instead of defining the vocabulary that made the task easy to describe.\nHere is my approach to your problem</p>\n\n<pre><code>char * Whitespace(char * str)\n/*\nThis function return the `str` pointer incremented past any whitespace.\n*/\n{\n /* when an error occurs, we return NULL.\n If an error has already occurred, just pass it on */\n if(!str) return str;\n\n while(isspace(*str))\n {\n str++;\n }\n return str;\n}\n\nchar * Character(char * str, char c)\n/*\nThis function tries to match a specific character.\nIt returns `str` incremented past the character\nor NULL if the character was not found\n*/\n{\n if(!str) return str;\n /* Eat any whitespace before the character */ \n str = Whitespace(str);\n\n if(c != *str)\n {\n return NULL;\n }\n else\n {\n return str + 1;\n }\n}\n\nchar * Word(char * str, char * word)\n/*\nThis function reads a sequence of numbers and letter into word\nand then returns a pointer to the position after the word\n*/\n{\n /* Handle errors and whitespace */\n if(!str) return str;\n str = Whitespace(str);\n\n /* copy characters */\n while(isalnum(*str))\n {\n *word++ = *str++;\n }\n *word = 0; /* don't forget null!*/\n return str;\n}\n\n\nint GetWords(char * str,char * word1,char * word2,char * word3)\n{\n str = Character(str, '[');\n str = Word(str, word1);\n str = Character(str, ']');\n str = Word(str, word2);\n str = Character(str, '[');\n str = Word(str, word3);\n str = Character(str, ']');\n str = Character(str, '\\0');\n return str != NULL;\n}\n</code></pre>\n\n<p>What I've done (or tried to do) is write the Character, Whitespace, and Word functions such that they are really very simple. If you understand <code>char *</code> you shouldn't have any trouble with them. But these simple tools combine very nicely to allow a straightforward implementation of your parser. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-15T09:45:02.083", "Id": "15999", "Score": "0", "body": "+1 for \"Generally I recommend against having your working functions doing any output\". Also, very nice and clean solution." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-15T02:59:40.307", "Id": "10036", "ParentId": "10031", "Score": "5" } }, { "body": "<p>This is perhaps a little less ugly, but string handling is never going to be pretty in C.</p>\n\n<pre><code>static const char * skip_space(const char *s)\n{\n return s + strspn(s, \" \");\n}\n\nstatic const char * skip_bracket(const char * s, int bracket)\n{\n s = skip_space(s);\n if (*s != bracket)\n return NULL;\n\n return skip_space(++s);\n}\n\nstatic const char * skip_word(const char * s)\n{\n return s + strcspn(s, \" []\");\n}\n\nstatic const char * copy_word(char *w, const char *s, size_t size)\n{\n const char * end = skip_word(s);\n size_t len = end - s;\n if (len &gt;= size) /* silently truncate word to buffer size */\n len = size - 1;\n\n memcpy(w, s, len);\n w[len] = '\\0';\n return skip_space(end);\n}\n\nstatic int get_words(const char *s, char *w1, char *w2, char *w3, size_t size)\n{\n if ((s = skip_bracket(s, '[')) == NULL)\n return 0;\n\n s = copy_word(w1, s, size);\n\n if ((s = skip_bracket(s, ']')) == NULL)\n return 0;\n\n s = copy_word(w2, s, size);\n\n if ((s = skip_bracket(s, '[')) == NULL)\n return 0;\n\n s = copy_word(w3, s, size);\n\n if ((s = skip_bracket(s, ']')) == NULL)\n return 0;\n\n return 1;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-21T18:11:27.757", "Id": "10225", "ParentId": "10031", "Score": "2" } }, { "body": "<p>You can use a state machine to complete this task,</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;string.h&gt;\nvoid Tokenize(char* s)\n{\n// the following array return new state based on current state and current scanned char\n // Input: * [ ] space Print Tokenize Current State Expression \n/*Next state:*/char StateArray[12][3][4] = {{{11,1,11,0} ,{0,0,0,0},{0,0,0,0} }, //0 {space}*{[}\n {{2,11,11,1} ,{1,0,0,0},{0,0,0,0}}, //1 {space}*{char}\n {{2,11,4,3} ,{1,0,0,0},{0,0,1,0}}, //2 {char}*{space}?{]}\n {{11,11,4,3} ,{0,0,0,0},{0,0,1,0}}, //3 {space}*{]}\n {{5,11,11,4} ,{1,0,0,0},{0,0,0,0}}, //4 {space)*{char}\n {{5,7,11,6} ,{1,0,0,0},{0,1,0,0}}, //5 {char}*{space}?{[}\n {{11,7,11,6} ,{0,0,0,0},{0,1,0,0}}, //6 {space}*{[}\n {{8,11,11,7} ,{1,0,0,0},{0,0,0,0}}, //7 {space}*{char}\n {{8,11,10,9} ,{1,0,0,0},{0,0,1,0}}, //8 {char}*{space}?{]}\n {{11,11,10,9} ,{0,0,0,0},{0,0,1,0}}, //9 {space}*{]}\n {{11,11,11,10} ,{0,0,0,0},{0,0,0,0}}, //10 {space}*\n {{11,11,11,11} ,{0,0,0,0},{0,0,0,0}}\n };\nchar state=0;\nint len = strlen(s);\nfor(int i =0;i&lt;len;i++)\n{\n if(StateArray[state][1][(s[i]^91)? ((s[i]^93)?((s[i]^32)? 0:3):2):1])\n printf(\"%c\",s[i]);\nif(StateArray[state][2][(s[i]^91)? ((s[i]^93)?((s[i]^32)? 0:3):2):1])\n printf(\"\\n\");\n state=StateArray[state][0][(s[i]^91)? ((s[i]^93)?((s[i]^32)? 0:3):2):1];\n switch(state)\n {\n case 11:\n printf(\"Error at column %d\",i);\n case 10:\n if(i==len-1)\n {\n printf(\"\\nParsing completed\");\n }\n}\n}\n}\nint main(void)\n{ \n char* s= \" [ word1 ] word2word [ 3 ] \"; // test string\n Tokenize(s);\n} \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-28T14:57:33.367", "Id": "136385", "Score": "1", "body": "Hi, and welcome to Code Review. This code is not really a review. Rather, it is an alternate way of doing things with little explanation as to what it does, why it works, and why it is better than the original. Additionally, I look through it and worry about missing braces, fall-through case-statements, and obscure bitwise manipulations that are not documented. Please consider adding detail as to why this is better, and what it solves differently to the OP, and why those choices make for better code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-06-08T20:37:47.143", "Id": "245163", "Score": "0", "body": "Did you create this by hand or is there some tool involved? I like the concept but I'd be terrified of supporting this. There are so many magic numbers." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-28T13:55:37.163", "Id": "75047", "ParentId": "10031", "Score": "0" } } ]
{ "AcceptedAnswerId": "10036", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-14T20:30:47.173", "Id": "10031", "Score": "4", "Tags": [ "c", "strings", "parsing" ], "Title": "String parsing in C" }
10031
<p>I have a type that receives serial data over a pipe:</p> <pre><code>struct Packet : Base { // Base is POD, too int foo; char data[]; }; </code></pre> <p>In the context, where I instantiate <code>Packet</code>, I already know how large this particular packet will be, so I write:</p> <pre><code>size_t const size = sizeof(Packet) + dataLength; std::auto_ptr&lt;Base&gt; p(new((void*)(new char[size])) Packet()); // note that it will be deleted via 'delete' </code></pre> <p>Is this a sensible way of doing this, or is there a more idiomatic way?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-15T04:48:09.483", "Id": "15987", "Score": "0", "body": "In my opinion this approach makes a lot more sense in C than it does in C++. I've seen it more often in projects which choose to do C rather than C++. (In fact AFAIK this is standardized in C99 but not C++.) C++ has higher level data structures like `vector` and also inheritance, both of which can be applied to this and similar problems." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-15T04:58:47.363", "Id": "15988", "Score": "0", "body": "I think we need to move this question to SO and get more eyes on it. But it is not how I would do it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-15T05:02:03.417", "Id": "15990", "Score": "0", "body": "@LokiAstari, Stack Overflow isn't going to like how subjective this one is." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-15T06:30:51.263", "Id": "15993", "Score": "0", "body": "To clarify, it must be done like this, because `Packet` must be POD." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-15T12:02:15.940", "Id": "16003", "Score": "0", "body": "@LokiAstari How do you feel this is off topic for here?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-15T12:05:37.193", "Id": "16004", "Score": "0", "body": "@MichaelK: It is non working code that needs a broader set of eyes to fix. But after Winston comment above. I wrote a slight [variation of the question](http://stackoverflow.com/questions/240212/what-is-the-difference-between-new-delete-and-malloc-free/240308#240308) on SO to get better feedback." } ]
[ { "body": "<p>The main thing I see wrong is that you are not accounting for <code>sizeof(foo)</code>.</p>\n\n<p>The other problem is that auto_ptr&lt;&gt; will not de-allocate the memory correctly. It calls <code>delete X</code>, but this is not legal as you did not allocate the memory with <code>new</code>. You need a custom destroy function (as you can provide to std::unique_ptr) that does the following:</p>\n\n<p>Note: Original Question was:</p>\n\n<pre><code>std::auto_ptr&lt;Base&gt; p(malloc(size)) Packet());\n</code></pre>\n\n<p>Leading to my original answer:</p>\n\n<pre><code>// Assuming Packet* packet = // stufff\n\npacket-&gt;~Packet(); // Need to call destructor\nfree(packet); // then free the memory allocated with malloc\n</code></pre>\n\n<p>Why not do this?</p>\n\n<pre><code>size_t const size = ...;\nstd::auto_ptr&lt;Base&gt; p = new Packet(size);\n</code></pre>\n\n<p>Then change packet too:</p>\n\n<pre><code>struct Packet : Base\n{\n int foo;\n std::vector&lt;char&gt; data;\n Packet(size_t size): foo(0), data(size) {}\n};\n</code></pre>\n\n<p>Edit:</p>\n\n<p>Based on the comments and the updated question:</p>\n\n<p>I posted the question here (to get more eyes on it): <a href=\"https://stackoverflow.com/q/9714359/14065\">https://stackoverflow.com/q/9714359/14065</a></p>\n\n<p>Which brought up two points:</p>\n\n<ul>\n<li>You still can use std::auto_ptr&lt;>\n\n<ul>\n<li>The memory allocated with <code>new char[size]</code> must be freed by <code>delete []</code><br>\nThis is not supported by std::auto_ptr&lt;> though you may be able to use std::unique_ptr</li>\n</ul></li>\n<li>Secondly the implementation is allowed to put a marker after the end of the object\n\n<ul>\n<li>A few other points need to be considered so please read the linked questiom.</li>\n</ul></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-15T03:35:22.897", "Id": "15982", "Score": "0", "body": "Thanks for your feedback. The Packet has to be POD because it's sent over a `pipe` to another process. Regarding `foo`, `size` is supposed to include all members of `Packet` not just `data`, so that's covered. Now, what I don't quite get is, why it is a problem do `delete` the `Packet`. Wont this exactly call the dtor and the `free` the memory?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-15T03:49:47.780", "Id": "15984", "Score": "0", "body": "See: http://stackoverflow.com/questions/240212/what-is-the-difference-between-new-delete-and-malloc-free/240308#240308 for the why delete will not work." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-15T04:36:02.870", "Id": "15986", "Score": "0", "body": "See update. It looks spooky, but should be legal and do the right thing, right?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-15T05:19:55.203", "Id": "15991", "Score": "0", "body": "@bitmask: AFAIK, doing this is only legal in C as it has special rules for a `T[]` (incomplete array type) at the end of a struct. C++ has no such special handling and thus this is not allowed." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-15T02:59:13.477", "Id": "10035", "ParentId": "10034", "Score": "3" } } ]
{ "AcceptedAnswerId": "10035", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-15T01:38:14.230", "Id": "10034", "Score": "1", "Tags": [ "c++", "memory-management" ], "Title": "Variable sized type allocation" }
10034
<p>This is a personal project of mine. I am currently in the research phase of developing my own bootloader that will be used to load a single task operating system. I am far away from the final goal, but have been trying to document my process as a reference. The content of my code documentation and code can be found at <a href="http://matthewh.me/wiki/index.php/Bootloader" rel="nofollow">Bootloader 101</a>.</p> <p>If possible I would appreciate feedback. The wiki page is open to be edited, and if you feel like you can contribute please feel free to do so. I apologize beforehand for referencing you to another page. The format of the content is important.</p> <p>First piece of code:</p> <pre><code> # Author: Matthew Hoggan # Date Created: Tuesday, Mar 6, 2012 .code16 # Tell assembler to work in 16 bit mode (directive) .section .text .globl _start # Help linker find start of program _start: movb $0x0e, %ah # Function to print a character to the screen movb $0x00, %bh # Indicate the page number movb $0x07, %bl # Text attribute mov $'A', %al # Move data into low nibble int $0x10 # Video Service Request to Bios _hang: jmp _hang .end /* linker.ld */ SECTIONS { /* Set location counter to 0x7c00 */ . = 0x7c00; .text : { *(.text) } .data : { *(.data) } .other : { FILL(0x000000) . = 0x1F2; BYTE(0x55) BYTE(0xAA) } } </code></pre> <p>Second piece of code:</p> <pre><code> # Author: Susam Pal &lt;http://susam.in/&gt; .code16 # Tell the assembler to use 16 bit instructions .section .text .globl _start _start: # Tell linker where entry point into program is mov $0xb800, %ax # 0xb800 is the start address of character buffer mov %ax, %ds # Move that address into the data segment movb $'B', %ds:0x00 # Write data directly to that buffer at 0 movb $0x1e, %ds:0x01 # Write text attributes for the text right after idle: jmp idle /* linker.ld */ SECTIONS { /* Set location counter to 0x7c00 */ . = 0x7c00; .text : { *(.text) } .data : { *(.data) } .other : { FILL(0x000000) . = 0x1ED; BYTE(0x55) BYTE(0xAA) } } </code></pre>
[]
[ { "body": "<ul>\n<li>Your code is well-commented. Other <a href=\"/questions/tagged/assembly\" class=\"post-tag\" title=\"show questions tagged &#39;assembly&#39;\" rel=\"tag\">assembly</a> answers on this site mention the importance of good comments: and yours are good.</li>\n<li>An infinite loop at the end of the program is strange; instead I would have expected a <code>ret</code> or <code>retf</code> statement to return to the O/S shell which launched this program; but maybe that's different/excusable for what may in future evolve to become a boot-loader.</li>\n<li>Writing to memory at 0xb8000 may or may not work depending on the current video mode. <a href=\"http://forum.osdev.org/viewtopic.php?f=1&amp;t=26211\" rel=\"nofollow\">Here is a thread</a> which discusses whether it's safe to assume 0xb8000 on computer startup (perhaps it is, but there are alternatives)</li>\n<li>You code would be more compact (perhaps less readable) if you initialized entire words, instead of separate instructions for each byte; for example in the first program you could initialize <code>ax</code> and <code>bx</code>; and in the second program you could write 0x1E42 into the first word of video memory.</li>\n<li><p>Using the 2nd method you'll probably start writing whole strings (not single characters) to the screen; the lods/stos/movs opcodes are useful for that. For example, you could do:</p>\n\n<pre><code>mov $0x1e, %ah # Write text attributes for the text right after\nloop:\nlodsb # load byte from ds:si and increment si\ncmp $0x00, %al # test for end-of-string\njz done\nstosw # store word (not byte) to es:di and increment di\njmp loop # loop back to load-and-then-store next byte of the string\ndone:\n</code></pre></li>\n<li><p>For this kind of reason it's unconventional of you to use the <code>ds</code> register to point to video memory; I would have expected you to use the <code>es</code> register instead.</p></li>\n<li>According to <a href=\"https://sourceware.org/binutils/docs/as/i386_002dMemory.html\" rel=\"nofollow\">the GNU Assembler manual</a> if you write <code>%ds:0x00</code> then it will emit the <code>ds</code> prefix, which is unnecessary (I think that <code>ds</code> is the default segment for memory access); perhaps (based on the manual, I don't know) the syntax without the segment prefix is something like just <code>0x00</code> or perhaps <code>0x00(,1)</code>.</li>\n</ul>\n\n<p>(I'm unable to give you feedback on the <code>linker.ld</code> section).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-25T22:23:25.550", "Id": "73795", "Score": "0", "body": "The 'test for zero' `cmp $0x00, %al` could be written more compactly using something like `or %al, %al`" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-25T21:49:19.490", "Id": "42814", "ParentId": "10037", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-15T04:50:08.653", "Id": "10037", "Score": "5", "Tags": [ "assembly" ], "Title": "The beginnings of a bootloader using GNU-based tools" }
10037
<p>This is a ( single file ) library I wrote as an helper to check arguments validity.Here below a sample usage:</p> <pre><code>public class Demo { /// &lt;summary&gt; /// Classical not null verification /// &lt;/summary&gt; /// &lt;param name="arg1"&gt;&lt;/param&gt; public void DoSomething(string arg1) { Contract.Expect(() =&gt; arg1).IsNotNull(); } /// &lt;summary&gt; /// Asserting an argument greather than another /// &lt;/summary&gt; /// &lt;param name="min"&gt;&lt;/param&gt; /// &lt;param name="max"&gt;&lt;/param&gt; public void DoSomething(int min,int max) { Contract.Expect(() =&gt; min) .IsLessThan(int.MaxValue) .Meet(a =&gt; a &lt;= max); } /// &lt;summary&gt; /// Validate an integer argument in a certain range /// &lt;/summary&gt; /// &lt;param name="arg1"&gt;&lt;/param&gt; public void DoSomething(int arg1) { Contract.Expect(() =&gt; arg1).IsGreatherThan(0) .IsLessThan(100); ; } /// &lt;summary&gt; /// Validate an array in length and asserts first element should be zero /// &lt;/summary&gt; /// &lt;param name="array"&gt;&lt;/param&gt; public void DoSomething(int[] array) { Contract.Expect(() =&gt; array).Meet(a =&gt; a.Length &gt; 0 &amp;&amp; a.First() == 0); } } </code></pre> <p>Exception message are auto generated based on the argument names, so we don't need magic strings at all. What about it ? Improvement and suggestions? <a href="https://bitbucket.org/Felice_Pollano/ncontracts/src" rel="nofollow">Entire code is hosted here</a>. </p> <p><strong>EDIT</strong> just to clarify the pourpose of the library: I'm trying to avoid code such as:</p> <pre><code>if (stringParameter == null) throw new ArgumentNullException("stringParameter"); </code></pre> <p>in which we need to write a string to specify the parameter name. This is not refactory friendly, neither DRY since you write twice "stringParameter" instead of:</p> <pre><code>Contract.Expect(() =&gt; stringParameter).IsNotNull(); </code></pre> <p>That is once, and refactor friendly ( at least in my opinion ;) ).</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-15T14:11:51.833", "Id": "16009", "Score": "1", "body": "I'm curious, why don't you use [.NET 4 Code Contracts](http://msdn.microsoft.com/en-us/library/dd287492.aspx)?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-15T14:28:07.473", "Id": "16011", "Score": "0", "body": "@Cygal they don't help to avoid typing the name of the argument as a string" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-18T02:54:00.487", "Id": "16113", "Score": "0", "body": "@Felice Pollano. please elaborate on \"they don't help avoid typing the name of the argument as a string\". I have not used the contracts enough." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-18T09:43:15.720", "Id": "16129", "Score": "0", "body": "@Leonid if I have to add into the emssage the name of the argumet, I hace to type it as a string, if I refactor, I Have to change etc etc." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-02-29T22:10:59.063", "Id": "226260", "Score": "0", "body": "This looks like a good generic implementation of a concept I have been messing around with for a little while. I think my goal is the same as yours, to have an internal validator that checks for common errors, checking arguments passed into a public-facing API. Like you, I do not like having the repetition of 'throw new ArgumentNullException(\"stringParameter\")' and 'throw new ArgumentException(String.Format(\"'{0}' is not a valid xxx.\",\"parametername\"))' at the top of all my non-private methods. If you don't object, I would like to use your Contract class in a real project." } ]
[ { "body": "<p>Felice, can you expand on what you are looking for? Are you trying to infer constraints to be applied dynamically? I looked at your link to the whole code base at bitbucket.</p>\n\n<p>First of all, nice work. Looks like you spent a good deal of time whipping that up.</p>\n\n<p>On the surface, given your demo and not knowing what exactly your intended use case is, it appears 1) that you are trying to make constraints more visually fluent (which I appreciate) and 2) it seems \"possibly\" unneeded.</p>\n\n<p>Once you further expand on your use case, I'm sure it will make more sense and I can revise my statements. However, for now let me explain item #2. 1) You can add the fluency you require by refactoring your code base into helper methods. 2) I would not really recommend throwing exceptions from what I can see. Given the code sample below (from your Contracts.cs) you are throwing an exception on something that should merely be a boolean check. As such you are altering the behavior of what you normally come to expect out of a programming language.</p>\n\n<pre><code>public IContract&lt;T&gt; IsEqual&lt;TT&gt;(TT of) where TT : T,IEquatable&lt;TT&gt;\n{\n TT actual = (TT)accessor();\n if (!actual.Equals(of))\n {\n throw new ArgumentOutOfRangeException(Name, \"Must be equal to\" + of.ToString());\n }\n return this;\n}\n</code></pre>\n\n<p>3) I would recommend watching out for \"re-inventing the language\". Sometimes it is hard to identify, but the general smell is that you try to recreate basic functionality in the toolset you already use, instead of just using what you have. This can result in double/triple programming. Let's use the demo example from above (focusing on the snippet I grabbed). You have built several methods to provided the \".IsNotNull()\" method for the Contract and are then encapsulating that (to make it more readable and fluent) into a method that just takes the parameter.</p>\n\n<pre><code>/// &lt;summary&gt;\n/// Classical not null verification\n/// &lt;/summary&gt;\n/// &lt;param name=\"arg1\"&gt;&lt;/param&gt;\npublic void DoSomething(string arg1)\n{\n Contract.Expect(() =&gt; arg1).IsNotNull();\n}\n</code></pre>\n\n<p>instead of just:</p>\n\n<pre><code>if (arg1.IsNullOrEmpty())\n</code></pre>\n\n<p>or</p>\n\n<pre><code>if (arg1.IsNullOrWhiteSpace())\n</code></pre>\n\n<p>Which are already built into the .net framework.</p>\n\n<p>I hope some/all of this helps. If you would, please further explain your use case. As for now, my recommendation would be to refactor your utility into static helper methods and not throw exceptions. For the error message part, just create helper method(s) to get the error message needed. So 1 method does the needed check and if it fails...and as a programmer you want to get the error message, you can choose to do that in a separate call.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-15T13:08:22.660", "Id": "16007", "Score": "0", "body": "thank for taking the time. I'm looking for a whole review of my code, and opinion if the library is felt as useful. The goal of the library is doing argument validation without using \"magic strrings\" This mean: throwing a proper exception if the argument does not meets some pre-condition." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-15T15:49:00.700", "Id": "16014", "Score": "0", "body": "Thanks for the clarification Felice. I have not extensively utilized .net contracts so code review wise, I would defer to a more experienced person. However, after reviewing .net contract and re-reviewing your library, I think it is a good idea you have that you are auto-replying with the correct error message instead of deferring to the user to hand type each time." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-15T16:01:31.587", "Id": "16016", "Score": "0", "body": "Thank yopu for your opinion, I've already +1 your review. I wait some other answer too before to mark as a reply." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-15T12:52:51.697", "Id": "10044", "ParentId": "10039", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-15T09:54:12.947", "Id": "10039", "Score": "3", "Tags": [ "c#" ], "Title": "An argument checking library" }
10039
<p>Is it possible to make this code more efficient &amp; elegant? </p> <pre><code>int HexToDecimal(char ch) { ch = tolower(ch); if ('a' &lt;= ch &amp;&amp; ch &lt;= 'f') { return ch - 'a' + 10; } else if ('0' &lt;= ch &amp;&amp; ch &lt;= '9') { return ch - '0'; } printf("Error\n"); return 0; } </code></pre> <p><strong>Update</strong>: Printing error could be ignored. By returning 0 I only mean to show that the input char is not a hex digit.</p>
[]
[ { "body": "<p>The first idea comming to mind is to check <code>0 &lt;= ch &lt;=9</code> before <code>tolower(ch)</code>, because if it's a digit, then you don't need to make <code>tolower</code>.</p>\n\n<p>Say, what does it means if the function returns <code>0</code>? How to determine the case \"it returns <code>0</code> because out of hex digits range\" and \"because ch is <code>0</code>\"?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-15T19:38:19.100", "Id": "16024", "Score": "0", "body": "Updated the question. By returning 0 I only mean to show that the input char was not a hex digit." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-23T16:28:09.697", "Id": "16381", "Score": "0", "body": "@Meysam, what does it return when you pass '0'?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-15T12:34:02.657", "Id": "10043", "ParentId": "10040", "Score": "2" } }, { "body": "<p>From memory (I haven't checked it) this should be the most efficient in terms of speed at the cost of a small increase in memory footprint.</p>\n\n<p>Note that it does not repeat your <code>printf(\"Error\\n\")</code> smell.</p>\n\n<pre><code>return\n\"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\" // &lt;nul&gt; ... &lt;si&gt;\n\"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\" // &lt;dle&gt; ... &lt;us&gt;\n\"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\" // ' ' ... '/'\n\"\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\x09\\x00\\x00\\x00\\x00\\x00\\x00\" // '0' ... '?'\n\"\\x00\\x0a\\x0b\\x0c\\x0d\\x0e\\x0f\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\" // '@' 'A' ... 'O'\n\"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\" // 'P' ... 'Z' ... '_'\n\"\\x00\\x0a\\x0b\\x0c\\x0d\\x0e\\x0f\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\" // '`' 'a' ... 'o'\n\"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\" // 'p' ... 'z' ... '~' &lt;del&gt;\n\"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\" /// Accented/Extended\n\"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\"\n\"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\"\n\"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\"\n\"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\"\n\"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\"\n\"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\"\n\"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\"\n[c];\n</code></pre>\n\n<p><strong>Added</strong></p>\n\n<p>Apologies for not being clear. This solution is not \"better\" than the original, just different and provably faster. I would use the originally posted code in all cases except when maximum speed is critical and only then after careful deliberation.</p>\n\n<p>I posted this for completeness, it is not elegant in any way, it is only more efficient ... almost brutally so.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-15T15:51:09.057", "Id": "16015", "Score": "0", "body": "What about endianness?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-15T16:42:11.550", "Id": "16017", "Score": "0", "body": "@Cygal: Not applicable because it is char." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-15T16:44:24.037", "Id": "16018", "Score": "1", "body": "Clever but a -1 `\\0xFF` to indicate error would have been useful so that you can check for error." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-15T17:30:21.227", "Id": "16020", "Score": "0", "body": "I wish I knew what I was looking at." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-15T19:26:06.137", "Id": "16023", "Score": "1", "body": "@RyanMiller: Its a string with 256 characters. You the use the character `c` (which has a value of 0->255) as the index into the string. It returns a character from the string. The string is carefully constructed so that character 51 in the array returns the character \\x03. Thus '3'(ie 51) when used as an index will return '\\x03' which converts to the integer 3." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-16T00:12:03.840", "Id": "16033", "Score": "0", "body": "@LokiAstari Thanks for the assist. I agree with the \\0xff point, unfortunately asker used 0." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-15T15:17:12.467", "Id": "10047", "ParentId": "10040", "Score": "3" } }, { "body": "<p>As fogbit said, first check for digits, then <code>tolower</code> if necessary. By the way, unless you wrote your own <code>tolower</code>, it should probably be <code>std::tolower</code>.</p>\n\n<p>Don't print anything on error. Either <code>assert</code> that the value is correct, return an impossible value (-1 is commonly used), or throw an exception. Printing that there was an error does not tell the rest of your program what happened.</p>\n\n<p>Finally, do you really need to write this? Are you sure your numbers won't be in the form <code>0xABCD</code>, which can be converted just fine with <code>boost::lexical_cast</code> or an <code>std::stringstream</code> wrapper?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-15T23:41:42.503", "Id": "10058", "ParentId": "10040", "Score": "1" } }, { "body": "<p>Now for elegance (forgive me ... my C is a little rusty):</p>\n\n<pre><code>static char * Hex = \"0123456789abcdef\";\nchar * found = strchr(Hex, tolower(ch));\nreturn found != null ? found - Hex: 0;\n</code></pre>\n\n<p>We search for the character in the string. If found then the value is the offset of the found character from the start of the string.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-15T23:44:16.013", "Id": "10059", "ParentId": "10040", "Score": "1" } } ]
{ "AcceptedAnswerId": "10047", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-15T10:22:39.117", "Id": "10040", "Score": "1", "Tags": [ "c++", "converting" ], "Title": "Converting hex character to decimal" }
10040
<p>I use this class for scheduling bits of work on a single thread. Work can be scheduled to be executed immediately or at a future time with the use of timers. It has many producers (the work adders) and a single consumer (the thread which executes the work).</p> <p>This class works well but I'm under no illusion that it's perfect. I'm looking for potential problems this class may exhibit especially relating to threading (dead locks etc).</p> <pre><code>internal delegate void MainLoopTask(); internal delegate object MainLoopJob(); internal static class MainLoop { private class DelegateTask { private bool _isBlocking; private Exception _storedException; private MainLoopTask _task; private MainLoopJob _job; private object _jobResult; private ManualResetEvent _handle; public DelegateTask() { } public bool IsBlocking { get { return _isBlocking; } set { _isBlocking = value; } } public Exception StoredException { get { return _storedException; } set { _storedException = value; } } public object JobResult { get { return _jobResult; } } public MainLoopTask Task { get { return _task; } set { _task = value; } } public MainLoopJob Job { get { return _job; } set { _job = value; } } public ManualResetEvent WaitHandle { get { if (_handle == null) _handle = new ManualResetEvent(false); return _handle; } } public void Execute() { try { if (_task != null) _task(); if (_job != null) _jobResult = _job(); } catch (Exception ex) { _storedException = ex; if (!_isBlocking) throw; } finally { if (_isBlocking) _handle.Set(); } } } private class TaskInfo { public Timer timer; public DelegateTask task; } private static AutoResetEvent _handle = new AutoResetEvent(false); private static Queue&lt;DelegateTask&gt; _tasks = new Queue&lt;DelegateTask&gt;(); private static List&lt;Timer&gt; _timers = new List&lt;Timer&gt;(); private static volatile bool _running; private static Thread _thread; public static void Loop() { _thread = Thread.CurrentThread; _running = true; while (_running) { DelegateTask task = null; lock (_tasks) { if (_tasks.Count &gt; 0) task = _tasks.Dequeue(); } if (task == null) { _handle.WaitOne(); } else { task.Execute(); } } } public static void Quit() { _running = false; _handle.Set(); } private static void Queue(DelegateTask task) { lock (_tasks) { _tasks.Enqueue(task); _handle.Set(); } } public static void Queue(MainLoopTask task) { DelegateTask dTask = new DelegateTask(); dTask.Task = task; Queue(dTask); } public static void QueueWait(MainLoopTask task) { DelegateTask dTask = new DelegateTask(); dTask.Task = task; QueueWait(dTask); } public static object QueueWait(MainLoopJob task) { DelegateTask dTask = new DelegateTask(); dTask.Job = task; QueueWait(dTask); return dTask.JobResult; } private static void QueueWait(DelegateTask t) { t.WaitHandle.Reset(); t.IsBlocking = true; if (_thread == null || Thread.CurrentThread == _thread) t.Execute(); else Queue(t); t.WaitHandle.WaitOne(); t.WaitHandle.Close(); if (t.StoredException != null) { throw t.StoredException; } } public static void QueueTimeout(MainLoopTask task, TimeSpan timeSpan) { QueueTimeout(task, (uint)timeSpan.TotalMilliseconds); } public static void QueueTimeout(MainLoopTask task, uint milliSeconds) { if (milliSeconds &lt;= 0) Queue(task); else { DelegateTask dTask = new DelegateTask(); dTask.Task = task; TaskInfo ti = new TaskInfo(); ti.task = dTask; ti.timer = new Timer(WaitProc, ti, milliSeconds, Timeout.Infinite); lock (_timers) _timers.Add(ti.timer); } } private static void WaitProc(object state) { TaskInfo ti = (TaskInfo)state; lock (_timers) _timers.Remove(ti.timer); ti.timer.Dispose(); Queue(ti.task); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-14T07:36:17.267", "Id": "16005", "Score": "0", "body": "What version of the framework are you using, and what version of C#? (For example, you have several properties which could be automatically implemented to start with, and .NET 4 contains classes specifically designed for producer/consumer queues.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-14T07:40:20.297", "Id": "16006", "Score": "0", "body": "This is targeted for .NET 2.0 runtime although I'm compiling with 3.5 compiler. .NET 4 is not an option at the moment unfortunately." } ]
[ { "body": "<ol>\n<li><p>A slightly better way to wait for the queue to be not empty in your <code>Loop</code> method would be to use a <a href=\"http://msdn.microsoft.com/en-us/library/System.Threading.Monitor_methods%28v=vs.110%29.aspx\" rel=\"nofollow\"><code>Monitor</code></a> instead of an <code>AutoResetEvent</code>. </p>\n\n<ul>\n<li>You would get rid of <code>_handle</code></li>\n<li>Replace all occurrences of <code>_handle.Set()</code> with <code>Monitor.Pulse(_tasks)</code></li>\n<li><p>Your waiting code would look like this:</p>\n\n<pre><code> DelegateTask task;\n lock (_tasks)\n {\n while (_tasks.Count == 0)\n {\n Monitor.Wait(_tasks);\n }\n task = _tasks.Dequeue();\n }\n\n task.Execute();\n</code></pre></li>\n</ul>\n\n<p>Slightly more compact code.</p></li>\n<li><p>Your should get into the habit of creating dedicated objects for locking instead of locking on some data structure you happen to use. In your case it won't make much of a difference but you can get into deadlocks this way if you are not careful.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-27T09:12:39.823", "Id": "36191", "ParentId": "10042", "Score": "2" } }, { "body": "<p>I don't really like the nested classes, it makes the code hard to understand since, reading it quickly, I have a hard time telling which code is in which class. Also, in C# you have auto properties, meaning you can replace </p>\n\n<pre><code>private bool _isBlocking;\npublic bool IsBlocking\n{\n get { return _isBlocking; }\n set { _isBlocking = value; }\n}\n</code></pre>\n\n<p>By :</p>\n\n<pre><code>public bool IsBlocking{get;set;}\n</code></pre>\n\n<p>Which is much cleaner and it takes less space.</p>\n\n<p>Also, you have a public empty constructor, but you don't need to define it. Since you don't have any constructor overloads, you can ommit writing the default empty constructor, it will be there by... default!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-26T12:53:34.300", "Id": "63943", "ParentId": "10042", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-14T07:33:58.273", "Id": "10042", "Score": "4", "Tags": [ "c#", ".net", "multithreading" ], "Title": "Producer/Consumer queue" }
10042
<p>Is there a better way to format this code, to make it more readable?</p> <pre><code>footnotes_paragraph.xpath('./small').children.slice_before do |element| element.name == 'br' end.map do |element| Footnote.new element end.reject(:empty?) </code></pre>
[]
[ { "body": "<p>You could extract out the initial xquery part into a separate method</p>\n\n<pre><code>def small_children\n footnotes_paragraph.xpath('./small').children\nend\n</code></pre>\n\n<p>Instead of using <code>do</code> <code>end</code> you could use <code>{}</code>. Then just a little reformatting, personal preference but for long method chains I like to start each line with a <code>.methodcall</code></p>\n\n<pre><code>small_children\n .slice_before { |element| element.name == 'br' }\n .map { |element| Footnote.new element }\n .reject(:empty?)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-16T03:16:53.833", "Id": "16036", "Score": "1", "body": "I like the braces for blocks with return values ala; http://onestepback.org/index.cgi/Tech/Ruby/BraceVsDoEnd.rdoc" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-16T09:40:39.950", "Id": "16044", "Score": "0", "body": "@garrow that's an excellent standard to have. I will be adopting that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-03T21:57:56.153", "Id": "18355", "Score": "1", "body": "In MRI <= 1.8.7, you'll need a \\ on the end of each line (except the last). Ruby 1.9's parser is much better this way." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-15T14:36:11.643", "Id": "10046", "ParentId": "10045", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-15T13:42:29.047", "Id": "10045", "Score": "1", "Tags": [ "ruby" ], "Title": "Ruby blocks format" }
10045
<p>I wrote a non-blocking MySQL interface for java (wrapped around the standard mysql java connector).</p> <p>I think the code to use it looks a bit ugly however...</p> <pre><code>db.rawQuery(queries.someAlreadyPreparedStatement, (new Callback(){ public void result(ResultSet result){ while (result.next()) { //Handle each row from the result and do any processing } })); </code></pre> <p>How could this be improved? Is this as good as it gets?</p>
[]
[ { "body": "<p>This is as good as it gets in Java. The idea of callbacks are very popular, and are the foundation of functional languages. Even Javascript offers a cleaner approach, as <a href=\"http://api.jquery.com/jQuery.get/\" rel=\"nofollow\">JQuery shows</a>. Unfortunately for Java, anonymous inner classes (as you have) are the shortest way to create a function like this.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-16T22:04:12.603", "Id": "10084", "ParentId": "10051", "Score": "3" } } ]
{ "AcceptedAnswerId": "10084", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-15T20:03:02.690", "Id": "10051", "Score": "2", "Tags": [ "java", "mysql" ], "Title": "Non-Blocking MySQL queries in Java" }
10051
<p>I have created an NBT format reader (<a href="http://web.archive.org/web/20110723210920/http://www.minecraft.net/docs/NBT.txt" rel="nofollow">NBT</a> is a binary serialization format that Minecraft uses to store its data). I made a node-like class that can be a data entry or the root of a subtree (that's how NBT is defined). The public interface of it currently looks like this:</p> <pre><code>class Tag { Tag(); void read(std::istream&amp; stream); void write(std::ostream&amp; stream); void print(int indent = 0); int8_t byteValue() const; int16_t shortValue() const; int32_t intValue() const; int64_t longValue() const; float floatValue() const; double doubleValue() const; ByteArray byteArrayValue() const; IntArray intArrayValue() const; UTF8String stringValue() const; std::vector&lt;Tag&gt; children() const; UTF8String name() const; }; </code></pre> <p>Is this the right design though? Originally I wanted to do the *Value methods with templates, but the problem is that the value of a Tag is dynamic, so that does not play nicely with the compile-time genericity.</p> <p>Is it a blasphemy not to make the various types derived classes? I couldn't really take advantage of a virtual <code>value</code> method because the return types would need to differ. Is there a better way to implement a data structure like this? The aim is to make it easy to use and fast. </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-15T22:34:03.547", "Id": "16030", "Score": "0", "body": "I think its hard to judge without some idea (sample code?) of how you are going to actually use it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-15T22:39:43.913", "Id": "16031", "Score": "0", "body": "I intend create a library with it, so I can't really tell. It's more like an API designer's dilemma. It is for loading Minecraft data files which contain trees of this data structure. The average use case is to iterate over the nodes, add/remove subtrees and values. So basically everything you can imagine with a tree." } ]
[ { "body": "<p>Couple of things I noticed:</p>\n\n<p>The serialize members:</p>\n\n<pre><code>void read(std::istream&amp; stream);\nvoid write(std::ostream&amp; stream);\n</code></pre>\n\n<p>I don't particular mind them but I also would prefer to have <code>operator&lt;&lt;</code> and <code>operator&gt;&gt;</code> defined (Note you can simply make these call write/read respectively).</p>\n\n<p>With the stream iterators defined this becomes less useful.</p>\n\n<pre><code>void print(int indent = 0);\n</code></pre>\n\n<p>The following seem like very simialer.</p>\n\n<pre><code>int8_t byteValue() const;\nint16_t shortValue() const;\nint32_t intValue() const;\nint64_t longValue() const;\nfloat floatValue() const;\ndouble doubleValue() const;\nByteArray byteArrayValue() const;\nIntArray intArrayValue() const;\nUTF8String stringValue() const;\n</code></pre>\n\n<p>I think we can replace all of them with:</p>\n\n<pre><code>template&lt;typename T&gt;\nT const&amp; get() const;\n</code></pre>\n\n<p>I like this better as we do not need to guess that <code>byte</code> maps to <code>int8_t</code> or <code>short</code> maps to <code>int16_t</code> as we can explicitly get the type we want:</p>\n\n<pre><code> int8_t val = t.get&lt;int8_t&gt;();\n</code></pre>\n\n<p>But there is already something very similar defined in boost:</p>\n\n<pre><code>boost::any\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-15T23:09:21.640", "Id": "10055", "ParentId": "10054", "Score": "2" } }, { "body": "<blockquote>\n <p>Originally I wanted to do the *Value methods with templates, but the problem is that the value of a Tag is dynamic, so that does not play nicely with the compile-time genericity</p>\n</blockquote>\n\n<p>Using <code>byteValue()</code>, <code>shortValue()</code> etc doesn't solve this problem completly. Let's consider this code:</p>\n\n<pre><code>Tag t;\nt.setIntValue(10);\n//...... some time later\nuint_8 a = t.byteValue(); // Ok (1)\n//...... some more time later\nint array[10] = {/*....*/}\nt.setArray(array);\n//...calling (1) again\nuint_8 a = t.byteValue(); // ??\n</code></pre>\n\n<p>In any case you have to code convert logic, which converts value from one type to another. The only difference is form this logic are implemented - either methods like <code>byteValue()</code>, <code>shortValue()</code> or template methods.</p>\n\n<p>I don't think it's a good idea to use name-specific methods to obtain values. Template methods are looked quite more suitable.</p>\n\n<pre><code>class Tag\n{\n template&lt;typename T&gt;\n getValue() \n {/*default function\n here you can implement default convert logic. For example you can forbid convertion\n to non-specified types using boost::enable_if or you own implemented SFINAE methods\n or you can convert non-specified Types to int type.*/\n };\n\n template&lt;&gt;\n getValue()&lt;int&gt; {return to-int-converted-value}\n\n template&lt;&gt;\n getValue()&lt;ByteArray&gt; {return to-byteArray-converted-value}\n\n template&lt;&gt;\n getValue()&lt;someExoticType&gt; // this convertion might be forbid with using boost::disable_if....\n {}\n};\n</code></pre>\n\n<p>Now, client code looks like this:</p>\n\n<pre><code>Tag t;\nt.setIntValue(10);\nuint_t a = t.getValue();\nint array[10] = {/*....*/}\nt.setArray(array);\nuint_t b = t.getValue();\n\nsomeExoticType ex = t.getValue() // error, no convertion\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-16T07:50:01.463", "Id": "16041", "Score": "1", "body": "Unfortunately that will not work. `t.getValue()` The compiler does not know which version of `getValue()` to call because template resolution does not use the return type for resolution. So you must explicitly specify the template type `t.getValue<int>()`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-16T08:30:02.113", "Id": "16042", "Score": "0", "body": "@fogbit, you are right about the problems with multiple getValue methods, but I specifically took care of that by asserting the TagType (an enum) and the size of the payload. My strategy is that set will set the TagType to whatever it wants and there is only on payload member (a vector of bytes). So in your first example you will get an assertion error when you try to call byteValue() again." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-16T08:32:09.380", "Id": "16043", "Score": "0", "body": "As @Loki Astari said, automatic template parameter deduction only works on templates. I tried this and I chose the current solution because a) it's cleaner (easier to understand for other people, which is one of my intentions) b) You have to write out the type anyway." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-16T13:58:02.957", "Id": "16053", "Score": "0", "body": "@TamรกsSzelei: Sounds like you have re-invented boost::any" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-16T15:14:17.917", "Id": "16055", "Score": "0", "body": "hmm, that's not a problem to me though :) Is it possible to allow only certain types to be stored in boost::any?" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-16T07:44:56.780", "Id": "10061", "ParentId": "10054", "Score": "1" } } ]
{ "AcceptedAnswerId": "10055", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-15T22:29:48.843", "Id": "10054", "Score": "1", "Tags": [ "c++", "api" ], "Title": "Interface of a variant-like class" }
10054
<p>This is just a big HTML file that can be setup to test any RESTful API. The only change that needs to be made is updating the config array for any specific API you are developing.</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;RESTful API Debugger&lt;/title&gt; &lt;style&gt; label{ display:inline-block; width: 80px; } &lt;/style&gt; &lt;script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; config = [ {'file': 'auth.php', 'get': {'mime':false, 'vars':['em','pw']}, 'put': {'mime':false, 'vars':['em','pw','newpw']}, 'delete':{'mime':false, 'vars':[]}}, {'file': 'user.php', 'post': {'mime':false, 'vars':['fn','ln','em','pw','nn']}, 'get': {'mime':false, 'vars':['em']}, 'put': {'mime':false, 'vars':['fn','ln','em','nn']}, 'delete':{'mime':false, 'vars':['em','pw']}} ]; // Quck and dirty object dump function dump(arr,level) { var dumped_text = ""; if(!level) level = 0; //The padding given at the beginning of the line. var level_padding = ""; for(var j=0;j&lt;level+1;j++) level_padding += " "; if(typeof(arr) == 'object') { //Array/Hashes/Objects for(var item in arr) { var value = arr[item]; if(typeof(value) == 'object') { //If it is an array, dumped_text += level_padding + "'" + item + "' ...\n"; dumped_text += dump(value,level+1); } else { dumped_text += level_padding + "'" + item + "' =&gt; \"" + value + "\"\n"; } } } else { //Stings/Chars/Numbers etc. dumped_text = "===&gt;"+arr+"&lt;===("+typeof(arr)+")"; } return dumped_text; } $(document).ready(function() { // User clicked send, do the ajax $('#send').on('click', function() { var data = ''; if ($('#var1').val() != '') { if (data != '') { data += ',\n'; } else { data = '{'; } data += "'" + $('#var1').val() + "':'" + $('#val1').val() + "'"; } if ($('#var2').val() != '') { if (data != '') { data += ',\n'; } else { data = '{'; } data += "'" + $('#var2').val() + "':'" + $('#val2').val() + "'"; } if ($('#var3').val() != '') { if (data != '') { data += ',\n'; } else { data = '{'; } data += "'" + $('#var3').val() + "':'" + $('#val3').val() + "'"; } if ($('#var4').val() != '') { if (data != '') { data += ',\n'; } else { data = '{'; } data += "'" + $('#var4').val() + "':'" + $('#val4').val() + "'"; } if ($('#var5').val() != '') { if (data != '') { data += ',\n'; } else { data = '{'; } data += "'" + $('#var5').val() + "':'" + $('#val5').val() + "'"; } if ($('#var6').val() != '') { if (data != '') { data += ',\n'; } else { data = '{'; } data += "'" + $('#var6').val() + "':'" + $('#val6').val() + "'"; } if (data != '') { data += ' }'; } if (data != '') { eval('data = ' + data); } $('#results').html('Sending Request...'); $.ajax({ beforeSend: function(req) { req.setRequestHeader("Accept", ''); req.setRequestHeader("Accept", $('#type').val()); }, 'url': $('#url').val(), 'type': $('#verb').val(), 'data': data, 'mimeType': 'multipart/form-data', 'complete': function (jqXHR, textStatus) { var msg = "Data: " + dump(data); msg += "&lt;br /&gt;&lt;br /&gt;Status: " + jqXHR.status + " (" + jqXHR.statusText + " - " + textStatus + ")&lt;br /&gt;"; msg += jqXHR.getAllResponseHeaders().replace(/\n/g, "&lt;br /&gt;"); msg += "---&lt;br /&gt;" + jqXHR.responseText; $('#results').html(msg); } }); }); // User chaged url, update verbs $('#url').on('change', function() { $('#verb').html(''); for(i=0; i &lt; config.length; i++) { restType = config[i]; if(restType['file'] == $('#url').val()) { if(typeof restType['get'] != 'undefined') { $('#verb').append('&lt;option value="get"&gt;get&lt;/option&gt;'); } else { $('#verb').append('&lt;option value="get"&gt;get (-)&lt;/option&gt;'); } if(typeof restType['post'] != 'undefined') { $('#verb').append('&lt;option value="post"&gt;post&lt;/option&gt;'); } else { $('#verb').append('&lt;option value="post"&gt;post (-)&lt;/option&gt;'); } if(typeof restType['put'] != 'undefined') { $('#verb').append('&lt;option value="put"&gt;put&lt;/option&gt;'); } else { $('#verb').append('&lt;option value="put"&gt;put (-)&lt;/option&gt;'); } if(typeof restType['delete'] != 'undefined') { $('#verb').append('&lt;option value="delete"&gt;delete&lt;/option&gt;'); } else { $('#verb').append('&lt;option value="delete"&gt;delete (-)&lt;/option&gt;'); } } } $('#verb').change(); }); // User changed the verb, update variable names $('#verb').on('change', function() { $('#typelist').hide(); for(j=1; j &lt;= 6 ; j++) { $('#var' + j).val(''); $('#val' + j).val(''); } for(i=0; i &lt; config.length; i++) { restType = config[i]; if(restType['file'] == $('#url').val()) { if(restType[$('#verb').val()]['mime']) $('#typelist').show(); for(j=0; j &lt; restType[$('#verb').val()]['vars'].length; j++) { $('#var' + (j+1)).val(restType[$('#verb').val()]['vars'][j]); } } } }); // Add the pages for(i=0; i &lt; config.length; i++) { restType = config[i]; $('#url').append('&lt;option&gt;' + restType['file'] + '&lt;/option&gt;'); } $('#url').change(); }); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div&gt; &lt;label for="url"&gt;Url&lt;/label&gt; &lt;select id="url"&gt;&lt;/select&gt; &lt;/div&gt; &lt;div&gt; &lt;label for="verb"&gt;Verb&lt;/label&gt; &lt;select id="verb"&gt; &lt;option value="post"&gt;post&lt;/option&gt;&lt;option value="get"&gt;get&lt;/option&gt;&lt;option value="put"&gt;put&lt;/option&gt;&lt;option value="delete"&gt;delete&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; &lt;div id="typelist"&gt; &lt;label for="type"&gt;Responce&lt;/label&gt; &lt;select id="type"&gt; &lt;option&gt;text/plain&lt;/option&gt; &lt;option&gt;text/html&lt;/option&gt; &lt;option&gt;application/xml&lt;/option&gt; &lt;option&gt;application/json&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; &lt;div&gt; &lt;label for="var1"&gt;Variable 1:&lt;/label&gt; &lt;input id="var1" value="email" /&gt; &lt;label for="val1"&gt;Value 1:&lt;/label&gt; &lt;input id="val1" /&gt; &lt;/div&gt; &lt;div&gt; &lt;label for="var2"&gt;Variable 2:&lt;/label&gt; &lt;input id="var2" value="hash" /&gt; &lt;label for="val2"&gt;Value 2:&lt;/label&gt; &lt;input id="val2" /&gt; &lt;/div&gt; &lt;div&gt; &lt;label for="var3"&gt;Variable 3:&lt;/label&gt; &lt;input id="var3" /&gt; &lt;label for="val3"&gt;Value 3:&lt;/label&gt; &lt;input id="val3" /&gt; &lt;/div&gt; &lt;div&gt; &lt;label for="var4"&gt;Variable 4:&lt;/label&gt; &lt;input id="var4" /&gt; &lt;label for="val4"&gt;Value 4:&lt;/label&gt; &lt;input id="val4" /&gt; &lt;/div&gt; &lt;div&gt; &lt;label for="var5"&gt;Variable 5:&lt;/label&gt; &lt;input id="var5" /&gt; &lt;label for="val5"&gt;Value 5:&lt;/label&gt; &lt;input id="val5" /&gt; &lt;/div&gt; &lt;div&gt; &lt;label for="var6"&gt;Variable 6:&lt;/label&gt; &lt;input id="var6" /&gt; &lt;label for="val6"&gt;Value 6:&lt;/label&gt; &lt;input id="val6" /&gt; &lt;/div&gt; &lt;button id="send"&gt;Send&lt;/button&gt; &lt;div id="results"&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-15T23:17:03.273", "Id": "16032", "Score": "0", "body": "There is a lot of repeated code in there, you can easily clean up those ifs. Why are you using eval? There is no need for that,build the object instead of a string." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-16T00:32:23.413", "Id": "16034", "Score": "1", "body": "@epascarello: You should not answer the question in comments... why not just write up an answer?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-18T13:42:46.343", "Id": "16132", "Score": "1", "body": "Because my comment is not an answer." } ]
[ { "body": "<p>As @epascarello mentioned, there is a ton of repeated code here.</p>\n\n<p>Some pointers if you wish:</p>\n\n<p>You could consider to have the number of variables configurable. This means you can add that to your config object and then do the following in your <code>$(document).ready()</code>:<br></p>\n\n<pre><code> var template = '&lt;div&gt;' +\n '&lt;label for=\"var~\"&gt;Variable ~:&lt;/label&gt;' +\n '&lt;input id=\"var~\" value=\"email\" /&gt;' +\n '&lt;label for=\"val~\"&gt;Value ~:&lt;/label&gt;' +\n '&lt;input id=\"val~\"&gt;' +\n '&lt;/div&gt;';\n for( var i = 0 ; i &lt; config.parameterCount ; i++ ){\n $(body).append( template.replace( /~/g , i+1+\"\" );\n }\n</code></pre>\n\n<p>You could take this even further, and have the list of REST calls be a dropdown, then you could read from the config the required input fields and generate those at run time.</p>\n\n<p>The same way, you could call this function in a loop : </p>\n\n<pre><code>function parseValue( index , data )\n{\n var varId = '#var' + index;\n var valId = '#val' + index;\n\n if ($(varId).val() != '') {\n data = data ? data += ',\\n' : '{';\n data += \"'\" + $(varId).val() + \"':'\" + $(valId).val() + \"'\";\n }\n return data;\n}\n</code></pre>\n\n<p>or, since you need a data object in the data, you could have : </p>\n\n<pre><code>function parseValue( index , data )\n{\n data = data || {}\n var varId = '#var' + index;\n var valId = '#val' + index;\n\n if ($(varId).val() != '')\n data[ $(varId).val() ] = $(valId).val();\n}\n</code></pre>\n\n<p>Also the setting of the verb dropdown could be greatly improved:</p>\n\n<pre><code>function setVerbs( restType )\n{\n \"get,post,put,delete\".split(\",\").forEach( function (verb)\n {\n var absenceIndicator = restType[verb] ? \"\" : \" (-)\";\n $('#verb').append('&lt;option value=\"' + verb + '\"&gt;' + verb + absenceIndicator +'&lt;/option&gt;');\n });\n}\n</code></pre>\n\n<p><strong>JSON</strong></p>\n\n<p>Finally, I am wondering why you are not using the JSON functions that are available. You could replace the entirety of <code>dump</code> with <code>JSON.stringify</code>, you could replace your <code>eval</code> statement with <code>data = JSON.parse( data )</code>;</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-31T03:01:06.203", "Id": "40504", "ParentId": "10056", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-15T23:12:12.657", "Id": "10056", "Score": "1", "Tags": [ "javascript", "html" ], "Title": "Code review of my quick and dirty RESTful API Debugger" }
10056
<p>My goal with vervPHP was to create a framework I could create applications in very quickly, without any excessive configuration or over the top framework.</p> <p>Here's a link to the github, to see more: <a href="https://github.com/verv/vervPHP" rel="nofollow">https://github.com/verv/vervPHP</a></p> <p>And now, for some code examples to show how awesome (I think) it is:</p> <p><strong>index.php:</strong></p> <pre><code>// Start the session: session_start(); // Include the framework base: include_once('framework/verv.php'); // Start the application: $verv = new verv(); </code></pre> <p><strong>framework/verv.php</strong></p> <pre><code>class verv { // Variables: public static $db; public static $url; public static $rq = array(); public static $lang = array(); public static $page = array(); public static $config = array(); public static $commands = array(); public static $framework = array(); /** * Constructor. Do not call manually, unless your module extends verv. * * @return null * @since 1.0 */ public function __construct() { // Parse the config: self::$config = parse_ini_file('config.ini', true); // Setup Language: self::setLang(); // Connect to the database if required: self::dbConnect(); // Prepare the request: self::setRQ(); // Load the remaining framework: self::loadFramework(); // Load the appropriate module: self::loadModule(self::getCommand(0)); // Load the template: self::loadTemplate(); // And finally, render the page: self::renderPage(); } // More functions follow... </code></pre> <p>What I'm hoping from a peer review:</p> <ul> <li>How can I improve my code (generally speaking)?</li> <li>Are there any glaring security holes that I should fix?</li> <li>I'm wanting to make this open source (for all the help I recieved on SO while making it) so I need to add an open source license to it - one that allows modification (preferrably with attribution) and allows for commercial development.</li> </ul> <p>And yes, I am in the process of improving the actual documentation - it's pretty shocking (particularly the iCommand chaining) at the moment ;)</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-22T07:59:28.373", "Id": "16299", "Score": "0", "body": "vervPHP - The constructor that does it all (and you're done)" } ]
[ { "body": "<p>You are <a href=\"http://www.youtube.com/watch?v=H33vSYapNNs\" rel=\"nofollow\">on a long way to success</a>. </p>\n\n<p>Consider autoload function (better from SPL) to avoid includes, it will also force you to establish good directory structure and clear class naming convention plus more security measures.</p>\n\n<p>Why so many statics? Consider Singleton design pattern if you really need it. Btw, your class is rebuild at every page request anyway, right?</p>\n\n<p>Consider Factory design pattern, or better RAII. Why? Look at your addCommand method, for example - no measures of overwriting commands, and no control on the registerd classes in general.</p>\n\n<p>If you promptly name your registered classes \"commands\", look at Command and Chain of Responsibility patterns. Observer pattern may suite your needs as well.</p>\n\n<p>Do not forget try catch blocks: if you develop a framework, a lot of unknown persons will use it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-17T02:11:28.367", "Id": "16073", "Score": "0", "body": "Thanks for the feedback. I have a few questions of my own. 1. Could you please elaborate on Autoload? I have exactly two static includes (verv.php and verv.chain.php); everything else is included via glob - what do I get moving to autoload? Why is eight static variables so many? Is there a performance hit? To answer your question, yes, verv is created at every page call - however only one module is ever loaded after that (`verv::$rq[0]`). You suggest that I should consider several design patterns - what benefits do they bring to the party to what I'm trying to achieve here? I see no ... (cont)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-17T02:13:31.407", "Id": "16074", "Score": "0", "body": "... reason to introduce patterns and design styles 'just because that is what the industry says works'. I'm interested in producing a lightweight framework (and if my cachegrinds are anything to go by it is very quick) that allows for the rapid development of applications (which it does). I am open to improving my work (and I will add more catching and handling, thank you for pointing that out) but I need to know how and why. Thanks for the points :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-17T05:17:56.430", "Id": "16075", "Score": "0", "body": "Since you write a framework, it will grow up fast. Sooner or later you will have problems with source code management. The better and clearer for understanding the code is from very beginning, the faster you will progress." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-17T05:30:24.277", "Id": "16076", "Score": "0", "body": "You write a framework, it will grow up fast and must be robust. Sooner or later you will have problems with source code management. The better your code is from the very beginning, the faster you will progress.\nAutoload will allow you to find files using class names, so you can just `new MyClass`, or you are at risk to face include dependency problems. See `spl_autoload_register()`\nThe statics are about the style also, plus you must obey some rules and limitations with them (RTFM)\nDesign patterns are common design problems solutions, not code snipplets, you can implement them in your own way." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-20T21:22:37.623", "Id": "16215", "Score": "0", "body": "I don't think source code management is a problem. Frameworks are loaded via `glob()` (with DIR_NOSORT for speed) from the `load` folder, and any additional code is introduced at the module level. I've also read about the statics, and I'm happy with the use of them - at any point, you can see what vervPHP is doing through the use of `verv::capture(verv::$var)` which is immensely helpful when creating an application. Did this framework get loaded? What are the current commands? What is the current request? All these answers are made clear by having static variables (which are then accessed ..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-20T21:25:26.107", "Id": "16216", "Score": "0", "body": "... through the appropriate methods. I've been developing this framework for three years and have used it in my own content management system (and other applications). I'm not looking to create a one size fits all framework here - vervPHP was designed for web based applications - and that's it. Have you taken it for a spin?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-21T03:46:56.077", "Id": "16226", "Score": "0", "body": "Up to you. As a side note: in OOP, class that implements only static methods is called \"utility class\" and is equivalent to a library in procedural languages. If you prefer procedural approach - why not?\nBtw, ctor is redundand, just make something like verv::init()." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-16T12:28:07.390", "Id": "10064", "ParentId": "10060", "Score": "4" } }, { "body": "<p>This is procedural code trying to pretend that it is OO. Just stick a namespace around it and write it like the procedural code that it is:</p>\n\n<h2>framework/verv.php</h2>\n\n<pre><code>namespace verv;\n\nfunction setLang() { /* Implementation */ } \nfunction dbConnect() { /* Implementation */ }\n\nfunction main()\n{\n setLang();\n dbConnect();\n // etc\n}\n</code></pre>\n\n<h2>Usage</h2>\n\n<p><code>verv\\main();</code></p>\n\n<h2>Advantages</h2>\n\n<ul>\n<li>No more <code>static</code> and <code>self</code> littering the code.</li>\n<li>No loss in usual OO benefits like data hiding and encapsulation, while reducing keystrokes required for implementation.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-26T04:34:05.187", "Id": "16463", "Score": "0", "body": "I'm not sure why I ignored namespacing, perhaps I figured it was PHP 5.4+. Anyways, you're spot on in all your points - it's not meant to be procedural MVP OOP, just a few things to make it easier to write simple applications." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-22T07:39:36.107", "Id": "10242", "ParentId": "10060", "Score": "5" } }, { "body": "<p>From your code example I'd say you create a class with static global state that by itself is the static global context object of your framework.</p>\n\n<p>That sounds like a very poor design decision to me. All you've got are some global variables and a global function (the constructor). For that you do too much IMHO. The class is not necessary because you don't encapsulate anything.</p>\n\n<p>You can further minimize your design by just having one global variable in form of an array or object and the init function.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-22T08:29:57.493", "Id": "10243", "ParentId": "10060", "Score": "2" } }, { "body": "<p>The following bit seems far from lightweight. You're loading files the user may not even need. Autoloading would be much lighter as it would load only the files associated with the classes a user attempts to instantiate.</p>\n\n<pre><code>/**\n * Loads the remaining framework, such as databases, forms, scaffolds, etc.\n * You can add your own framework(s) by adding them to the load folder.\n * \n * @return null\n * @since 1.0; \n */\npublic static function loadFramework() {\n // Include any interfaces required:\n include_once('verv.chain.php');\n\n // Then include any other framework items:\n self::$framework = glob('framework/load/*.php', GLOB_NOSORT);\n\n foreach (self::$framework as $file) {\n include_once($file);\n }\n}\n</code></pre>\n\n<p>This bit alone will bloat your framework to the point of being unusable. I know this because I once worked at a place that did just this and it led to the framework running out of usable memory fairly easily.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-03T21:13:47.127", "Id": "16890", "Score": "0", "body": "That's where the framework resides - it loads the framework, and if the user puts any additional framework files in the same folder, they'll be loaded as well." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-03T21:20:48.207", "Id": "16891", "Score": "0", "body": "I understand what your intention is. I'm telling you that your intention is misguided and you should only load what's needed when it's needed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-04T00:22:55.667", "Id": "16902", "Score": "0", "body": "No problems. Just making sure. As per other comments, I am currently writing a refactor to use an autoloading system (as well as namespacing). I will update my question once it's complete." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-03T20:21:51.570", "Id": "10598", "ParentId": "10060", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-16T01:29:17.477", "Id": "10060", "Score": "1", "Tags": [ "php", "php5" ], "Title": "Review of my PHP framework, vervPHP" }
10060
<p>I have a blob whose format is something like:</p> <p>(id1,key1,value1)(id2,key2,value2).... </p> <p>where id is a <code>uint32_t</code>, and key and value are null-terminated strings. I am looking for an iterator-like interface that will extract records from the blob.</p> <p>This is what I have come up with:</p> <pre><code>typedef struct blob_ { uint32_t size; // length of the buffer char buf[]; }blob; typedef struct record_ { uint32_t id; // id char *key; // pointer to key in the blob char *value; // pointer to value in the blob char *next; // pointer to where the next record starts } record; static record get_next_obj(const char* begin, const char* end) { record obj; if (begin == end) { obj.id = 0; obj.key = NULL; obj.value = NULL; obj._next = NULL; } else { memcpy(&amp;obj.id, begin, sizeof(uint32_t)); begin += sizeof(uint32_t); obj.key = begin; while(begin &lt; end &amp;&amp; *begin != '\0') ++begin; ++begin; obj.value = begin; while(begin &lt; end &amp;&amp; *begin != '\0') ++begin; ++begin; obj.next = begin; } return obj; } record blob_list_next(const blob *data, const record *prev) { const char *begin, *end; begin = prev-&gt;next; end = data-&gt;buf + data-&gt;size; return get_next_obj(begin, end); } record blob_list_begin(const blob *data) { const char *begin, *end; begin = data-&gt;buf; end = data-&gt;buf + data-&gt;size; return get_next_obj(begin, end); } record blob_list_end(const blob *data) { record obj; obj.id = 0; obj.key = NULL; obj.value = NULL; obj.next = NULL; return obj; } </code></pre> <p>Then the API will be accessed with something like this:</p> <pre><code>record obj; record obj_end; // comp is a comparison operator of two record objects for (obj = blob_list_begin(data), obj_end = blob_list_end(data); comp(obj, obj_end) == false; obj = blob_list_next(data, &amp;obj)) { // access the obj } </code></pre> <p>I used return-by-value semantics because I wanted to avoid calling <code>malloc()</code>. There will be a maximum of 4096 records in a tuple.</p>
[]
[ { "body": "<p>You're just setting pointers in your function.\nIf the original data changes, you will be accessing wrong data ...</p>\n\n<pre><code>char data[] = \"\\x01\\x00\\x00\\x01key\\0value\";\np = get_next_obj(data, data + sizeof data);\nif (p.id != 16777217) /* error */;\nif (strcmp(p.key, \"key\")) /* error */;\nif (strcmp(p.value, \"value\")) /* error */;\n\nstrcpy(data, \"\\x02\\x00\\x00\\x02FOO\\x00BAR\");\nif (p.id != 16777217) /* error */; // same id as before\nif (strcmp(p.key, \"FOO\")) /* error */; // but different data!\nif (strcmp(p.value, \"BAR\")) /* error */;\n</code></pre>\n\n<p>I think you will need to <code>malloc</code> and copy ...</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-16T15:36:07.740", "Id": "16057", "Score": "0", "body": "It's not uncommon to do this while parsing a buffer though, so long as the buffer is kept unchanged until you've finished parsing it. You only need to copy when a value should live longer than that." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-16T09:49:09.073", "Id": "10063", "ParentId": "10062", "Score": "0" } }, { "body": "<p>If you're not totally wedded to emulating the STL interface, you could replace the <code>obj_end ... comp(obj, obj_end)</code> with a simple <code>is_not_end(&amp;obj)</code>. Passing both by value just to see if <code>obj</code> is filled with well-known magic values is unnecessary.</p>\n\n<p>Oh, and if your input is incorrect, you can advance off the end:</p>\n\n<pre><code> while(begin &lt; end &amp;&amp; *begin != '\\0')\n ++begin;\n\n ++begin;\n</code></pre>\n\n<p>if the loop terminates because <code>begin == end</code>, you'll still increment <code>begin</code> again.</p>\n\n<p>Other that that, it looks fine to me.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-16T15:33:57.587", "Id": "10072", "ParentId": "10062", "Score": "0" } }, { "body": "<p>Some random comments:</p>\n\n<ol>\n<li><p>The behaviour of flexible array members are defined in the C99 standard, but undefined in C90. Because of that reason, you might want to add a compiler switch guard against C90 compilers:</p>\n\n<pre><code>#if !defined __STDC_VERSION__ || (__STDC_VERSION__ &lt; 199901L)\n #error Code must be compiled as C99 or later.\n#endif\n</code></pre></li>\n<li><p>Why is the data binary data <code>char</code> and not <code>uint8_t</code>? <code>char</code> may or may not be signed, depending on the compiler.</p></li>\n<li><p>Consider inlining <code>get_next_obj()</code>. Since you return the struct by value, even good C compilers will generate a lot of overhead code from that. If you can weed out at least the internal return-by-value, the algorithm will be a bit faster.</p></li>\n<li><p>Any reason why the record objects can't hold a prev pointer? That is, why can't they be a double-linked list instead of a single linked one? And on the topic of linked lists, you may want to consider changing the type of the next pointer:</p>\n\n<pre><code>typedef struct record_ {\n uint32_t id; // id\n char *key; // pointer to key in the blob\n char *value; // pointer to value in the blob\n record_ *next; // pointer to the next record \n record_ *prev; // pointer to the previous record\n} record; \n</code></pre>\n\n<p>Or perhaps stuff all the record objects into a real linked list ADT.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-20T15:39:02.603", "Id": "10185", "ParentId": "10062", "Score": "2" } }, { "body": "<p>Is a blob meant to be portable? If so consider endianness in the id - memcpy is not enough.</p>\n\n<p>In get_next_obj:</p>\n\n<ul>\n<li><p>What if begin > end? Be defensive.</p></li>\n<li><p>Duplicate code in while loops needs extracting into a function. Consider using optimised library functions such as strchr(begin, '\\0') or strlen(input) to find the terminator and check for over-running 'end'. Your loops stop at 'end' and ignore a missing '\\0' before 'end'.</p></li>\n<li><p>You are returning non-static data 'record obj'. Better to pass-in a pointer to an empty record and return a pointer to it on success, NULL on failure (begin >= end) (instead of creating an empty object).</p></li>\n</ul>\n\n<p>Your concept of a null object (containing 0,NULLs) to be used to terminate the loop is unnecessary. What is wrong with a NULL pointer returned from get_next_obj() when begin >= end ?</p>\n\n<p>You main loop might be something like:</p>\n\n<pre><code>if (blob_list_begin(data, &amp;obj)) {\n do {\n // access the obj\n } while (blob_list_next(data, &amp;obj, &amp;obj));\n}\n</code></pre>\n\n<p>Or if you prefer:</p>\n\n<pre><code>record * pobj;\nfor (pobj = blob_list_begin(data, &amp;obj); \n pobj; \n pobj = blob_list_next(data, &amp;obj, &amp;obj)) {\n // access the obj\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-21T17:23:18.033", "Id": "10223", "ParentId": "10062", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-16T09:33:52.313", "Id": "10062", "Score": "2", "Tags": [ "c", "iterator" ], "Title": "Iterator-like interface for extracting records from a blob" }
10062
<p>I am using jQuery datepicker on 2 forms on the same page.<br> I currently am using the following code (below), but as you can see, I am using the same parameters over again (showOn, buttonImage, buttonImageOnly, dateFormat, &amp; constrainInput)</p> <p>Is there a more efficient way to do this rather then repeating myself over and over again, over 4 methods?</p> <pre><code>$('#startdate').datepicker( { showOn: 'both', buttonImage: '/assets/images/calendar_symbol.png', buttonImageOnly: true, dateFormat: 'dd/mm/yy', constrainInput: true, // All of the above is repeated again below minDate: new Date(&lt;?php echo date("Y")?&gt;, &lt;?php echo date("m")-1?&gt;, &lt;?php echo date("d")?&gt;), onClose: function() { $('#enddate').val($('#startdate').val()); } } ); $('#enddate').datepicker( { showOn: 'both', buttonImage: '/assets/images/calendar_symbol.png', buttonImageOnly: true, dateFormat: 'dd/mm/yy', constrainInput: true, // All the above repeated again.. minDate: new Date(&lt;?php echo date("Y")?&gt;, &lt;?php echo date("m")-1?&gt;, &lt;?php echo date("d")?&gt;) } ); $('#filter_startdate').datepicker( { showOn: 'both', buttonImage: '/assets/images/calendar_symbol.png', buttonImageOnly: true, dateFormat: 'dd/mm/yy', constrainInput: true,// and again... onClose: function() { $('#enddate').val($('#startdate').val()); } } ); $('#filter_enddate').datepicker( { showOn: 'both', buttonImage: '/assets/images/calendar_symbol.png', buttonImageOnly: true, dateFormat: 'dd/mm/yy', constrainInput: true // and again.... } ); </code></pre> <p>I was thinking of using a if statement to check what was clicked (<code>#startdate</code> or <code>#filter_startdate</code>), and then breaking it down like that, but unsure if this would work or how to do this.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-16T15:28:29.933", "Id": "16056", "Score": "0", "body": "You could have a `defaultOptions` object that contains all the common elements (showOn, buttonImage, buttonImageOnly, etc), then just modify it as necessary?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-20T08:50:10.817", "Id": "16185", "Score": "0", "body": "My eyes are burning!\n\nWhy do you do:\n\n `<?php echo date(\"Y\")?>, <?php echo date(\"m\")-1?>, <?php echo date(\"d\")?>`\n\ninstead of \n\n `<?php echo date(\"Y\").\",\".(date(\"m\")-1).\",\".date(\"d\"); ?>`\n?\n\nJust my 2c" } ]
[ { "body": "<p>You'll want to use <code>setDefaults</code> to clean up your code a bit. Also with a few variables you can clean it up even more.</p>\n\n<pre><code>$.datepicker.setDefaults({\n showOn: 'both',\n buttonImage: '/assets/images/calendar_symbol.png',\n buttonImageOnly: true,\n dateFormat: 'dd/mm/yy',\n constrainInput: true\n});\n\nvar minDate = new Date(\n &lt;?php echo date(\"Y\")?&gt;, \n &lt;?php echo date(\"m\")-1?&gt;, \n &lt;?php echo date(\"d\")?&gt;\n);\n\nvar setEndDate = function() {\n $('#enddate').val($('#startdate').val());\n};\n\n$('#startdate').datepicker({\n minDate: minDate ,\n onClose: setEndDate \n});\n\n$('#enddate').datepicker({\n minDate: minDate \n});\n\n$('#filter_startdate').datepicker({\n onClose: setEndDate \n});\n\n$('#filter_enddate').datepicker();\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-16T16:46:00.903", "Id": "10074", "ParentId": "10068", "Score": "5" } }, { "body": "<p>Hmm well <a href=\"https://github.com/jquery/jquery-ui/blob/master/ui/jquery.ui.datepicker.js\" rel=\"nofollow\">according to the datepicker source code</a> it doesn't use the jquery ui widget factory, which is a bit annoying because it's not standard. But global defaults should be set how ChaosPandion suggested.</p>\n\n<p>However if you don't want to do global defaults how about your own defaults object? My favorite way of doing that is with <a href=\"http://api.jquery.com/jQuery.extend/\" rel=\"nofollow\">jQuery.extend</a>.</p>\n\n<pre><code>$(function() {\nvar standardDatePicker = function(options) {\n return $.extend({\n showOn: 'both', \n buttonImage: '/assets/images/calendar_symbol.png', \n buttonImageOnly: true,\n dateFormat: 'dd/mm/yy',\n constrainInput: true, // All of the above is repeated again below\n minDate: new Date(&lt;?php echo date(\"Y\")?&gt;, &lt;?php echo date(\"m\")-1?&gt;, &lt;?php echo date(\"d\")?&gt;)\n }, options)\n}\n\n$('#startdate').datepicker(standOptions({ \n onClose: function() { \n $('#enddate').val($('#startdate').val());\n } \n}))\n\n$('#enddate').datepicker(standardOptions());\n\n})\n</code></pre>\n\n<p>By the way in javascript you place curly braces on the same line, not on a new line. This is not just a matter of style because as Douglas Crockford has pointed out over and over, placing braces on a new line can occasionally cause your program to have strange silent errors due to semi-colon insertion.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-16T17:04:48.993", "Id": "10078", "ParentId": "10068", "Score": "1" } } ]
{ "AcceptedAnswerId": "10074", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-16T13:59:23.130", "Id": "10068", "Score": "4", "Tags": [ "javascript", "jquery-ui" ], "Title": "Refactor this jQuery datepicker code to be as small as possible" }
10068
<p>I've created a set of classes thatwork together to create the html needed to display social plugins like Facebook like, google plus and twitter. At firsti defined an abstract class SocialButtonAbstract that is the base class that will be extended by the various plugins</p> <pre><code>abstract class SocialButtonAbstract { protected $settings; function __construct(array $settings = null) { $this-&gt;_mergeSettings($settings); } protected function _mergeSettings(array $settings){ if ($settings !== null){ $this-&gt;settings = array_merge($this-&gt;settings, $settings); } } abstract public function renderButton(array $settings = NULL); abstract public function renderScript(); } </code></pre> <p>This is an example of FacebookLike (i post this example because it's central to my question)</p> <pre><code>require_once 'SocialButtonAbstract.php'; Class FacebookLike extends SocialButtonAbstract{ const FB_SEND = 'fb:send'; const FB_HREF = 'fb:href'; const FB_WIDTH = 'fb:width'; const FB_LAYOUT = 'fb:layout'; const FB_SHOW_FACES = 'fb:show-faces'; const FB_ACTION = 'fb:action'; const FB_FONT = 'fb:font'; const FB_COLORSCHEME = 'fb:colorscheme'; const FB_REF = 'fb:ref'; private $_apyKey = null; protected $settings = array( self::FB_SEND =&gt; 'true',//Display button SEND self::FB_HREF =&gt; FALSE,//the URL to like. If FALSE defaults to the current page. self::FB_WIDTH =&gt; '88',// the width of the Like button. self::FB_LAYOUT =&gt; "button_count", //there are three options standard, button_count and box_count self::FB_SHOW_FACES =&gt; 'false', //specifies whether to display profile photos below the button (standard layout only) self::FB_ACTION =&gt; 'like',//the verb to display on the button. Options: 'like', 'recommend', self::FB_FONT =&gt; FALSE,//the font to display in the button. Options: 'arial', 'lucida grande', 'segoe ui', 'tahoma', 'trebuchet ms', 'verdana' self::FB_COLORSCHEME =&gt; 'light',// the color scheme for the like button. Options: 'light', 'dark' self::FB_REF =&gt; FALSE// I don't understend how this works, for now is a Todo ); public function setApiKey($apyKey){ $this-&gt;_apyKey = $apyKey; } public function renderScript(){ $apiKey = $this-&gt;_apyKey; if ($apiKey !== null){ $apiKey = "&amp;appId=$apiKey"; }else{ $apiKey = ''; } $markup = &lt;&lt;&lt;HTML &lt;div id="fb-root"&gt;&lt;/div&gt; &lt;script&gt; (function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/all.js#xfbml=1$apiKey"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); &lt;/script&gt; HTML; return $markup; } public function renderButton(array $settings = null){ $this-&gt;_mergeSettings($settings); $dataAttributes = array(); foreach ($this-&gt;settings as $attr =&gt; $value){ //Skip the values thatare FALSE, no need to render anything for them if($value === FALSE){ continue; } //convert the keys from the format fb:send to the HTML5 data-send $attr = str_replace("fb:", "data-", $attr); $dataAttributes[$attr] = $value; } $markup = "&lt;div class=\"fb-like\" "; foreach ($dataAttributes as $dataAttr =&gt; $dataValue){ $markup .= "$dataAttr=\"$dataValue\" "; } $markup .= "&gt;&lt;/div&gt;"; return $markup; } } </code></pre> <p>To display the various plugins i created a little helper class that provides the markup for the elements that surround the social buttons</p> <pre><code>class SocialPluginsHelper { const ID_OF_WRAPPER = 'id_of_wrapper'; const CLASS_OF_WRAPPERS = 'class_of_wrappers'; const HTML_BEFORE_BUTTONS = 'html_before_buttons'; const HTML_AFTER_BUTTONS = 'html_after_buttons'; const CUSTOM_PLUGIN_STYLE = 'custom_plugin_style'; const TAG_OF_WRAPPER = 'tag_of_wrapper'; const STYLE_OF_WRAPPER = 'style_of_wrapper'; function __construct(array $settings = null) { if ($settings !== null){ $this-&gt;settings = array_merge($this-&gt;settings, $settings); } } private function createStyleAttribute($style){ $customStyle = ''; if(!empty($style)){ $customStyle = "style=\"$style\""; } return $customStyle; } private $plugins = array(); private $settings = array( self::ID_OF_WRAPPER =&gt; "socialButtons",//id of the wrapper element self::TAG_OF_WRAPPER =&gt; "div",//what HTML element to use as a wrapper, either DIV or UL (if you choose DIV, alle the children will be DIV too otherwise the will be LI) self::CLASS_OF_WRAPPERS =&gt; "social",//Class of the children element self::HTML_BEFORE_BUTTONS =&gt; '',//custom HTML before the plugins self::HTML_AFTER_BUTTONS =&gt; '',//custom HTML after the plugins self::STYLE_OF_WRAPPER =&gt; '',//custom style of the main wrapping element self::CUSTOM_PLUGIN_STYLE =&gt; array()//this is some custom style thatwill be added to the elements that surround the plugins, useful to add extra width or inline options. It's //an associative array with the keys that equals the name of the classes (for example to add style to the Facebook plugin, use the key FacebookLike ); public function add(SocialButtonAbstract $plugin){ $this-&gt;plugins [] = $plugin; } public function renderAllButtons(array $pluginSettings = null){ $settings = $this-&gt;settings; $tagOfChildren = $settings[self::TAG_OF_WRAPPER] === "div" ? "div" : "li"; $tagOfWrapper = $settings[self::TAG_OF_WRAPPER]; $idOfWrapper = $settings[self::ID_OF_WRAPPER]; $htmlBeforeButtons = $settings[self::HTML_BEFORE_BUTTONS]; $classOfWrappers = $settings[self::CLASS_OF_WRAPPERS]; $htmlAfterButtons = $settings[self::HTML_AFTER_BUTTONS]; $customStyleOfWrapper = $this-&gt;createStyleAttribute($settings[self::STYLE_OF_WRAPPER]); $markup = "&lt;$tagOfWrapper $customStyleOfWrapper id=\"$idOfWrapper\"&gt;\n"; $markup .= "$htmlBeforeButtons\n"; foreach($this-&gt;plugins as $plugin){ $customSettings = isset($pluginSettings[get_class($plugin)]) &amp;&amp; is_array($pluginSettings[get_class($plugin)]) ? $pluginSettings[get_class($plugin)] : array(); $customStyle = isset($settings[self::CUSTOM_PLUGIN_STYLE][get_class($plugin)]) ? $this-&gt;createStyleAttribute($settings[self::CUSTOM_PLUGIN_STYLE][get_class($plugin)]) : ''; $markup .= "&lt;$tagOfChildren class=\"$classOfWrappers\" $customStyle&gt;".$plugin-&gt;renderButton($customSettings)."&lt;/$tagOfChildren&gt;\n"; } $markup .= "$htmlAfterButtons\n&lt;/$tagOfWrapper&gt;\n"; echo $markup; } public function renderAllScripts(){ foreach($this-&gt;plugins as $plugin){ echo $plugin-&gt;renderScript(); } } } </code></pre> <p>I also create a factory class to create instances of the plugins but it's not relevant to my question. I use the plugin like this:</p> <pre><code> //Initialize the helper with some custom markup options $socialPlugins = new SocialPluginsHelper(array( SocialPluginsHelper::HTML_AFTER_BUTTONS =&gt; '&lt;div class="clear"&gt;&lt;/div&gt;', SocialPluginsHelper::HTML_BEFORE_BUTTONS =&gt; '&lt;div class="clear"&gt;&lt;/div&gt;', SocialPluginsHelper::STYLE_OF_WRAPPER =&gt; 'margin-top:20px;', SocialPluginsHelper::CUSTOM_PLUGIN_STYLE =&gt; array( "TwitterButton" =&gt; "width:69px;", "FacebookLike" =&gt; "width:88px;") ) ); //Add the facebook plugin with some custom option $socialPlugins-&gt;add(PluginFactory::create("FacebookLike", array(FacebookLike::FB_SEND =&gt; "false"))); //Add the Twitter plugin with no custom option $socialPlugins-&gt;add(PluginFactory::create("TwitterButton")); //Add the Gplus plugin with no custom option $socialPlugins-&gt;add(PluginFactory::create("Gplus")); </code></pre> <p>Now here comes the part i'm less convinced of, if i have multiple Facebook Like button on the page i need to pass in the href to like for each plugin. for this reason, i do something like</p> <pre><code>$socialPlugins-&gt;renderAllButtons(array("FacebookLike" =&gt; array(FacebookLike::FB_HREF =&gt; $url))); </code></pre> <p>I used as a convention that i pass an array that has the name of the classes as "keys" amd an array of <code>$settings</code> as values. Whati'm askin is</p> <ul> <li>in general, do you think that my class design is correct?</li> <li>is there some design pattern i should have implemented?</li> <li>am i doing the right thing by overriding the $settings each time or should i create a new instance of the plugin every time?</li> </ul> <p>Thanks for your time</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-19T20:27:19.123", "Id": "16168", "Score": "0", "body": "Is the question too long?Should i take out the code?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-30T22:19:11.650", "Id": "16737", "Score": "1", "body": "I think this is just good code. Although I'd fix a few HTML injection problems." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-31T01:30:52.823", "Id": "16740", "Score": "0", "body": "@usr where do you think that the HTML injection problems lie?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-31T10:35:19.527", "Id": "16743", "Score": "0", "body": "\"\"$dataAttr=\\\"$dataValue\\\" \"\" Just like that. I don't know PHP but this looks unencoded to me." } ]
[ { "body": "<p>I know this is rather old, but I came across it while look through the unanswered pile and thought there were a few things I could add. Because it is so old and I'm unsure if you are still watching this, I won't go into a lot of detail. However, if you want me to, I will of course return and do a more thorough job. That being said...</p>\n\n<p><strong>Type Hinting</strong></p>\n\n<p>Type hinting forces your methods to a strict set of rules. When you say your argument is going to be an array, it MUST be an array. The only time this is \"ignored\" is when you give it a default value, such as NULL. Should you ever pass that argument, with its default value, to another method that does not expect the default value, it will produce errors. Your <code>_mergeSettings()</code> method is such. It gets its argument from the methods that call it, which have those default NULL values, but <code>_mergeSettings()</code> does not expect a NULL default. So of course, should you ever neglect to pass anything to those parent methods, <code>_mergeSettings()</code> will throw so many errors your head will spin.</p>\n\n<p><strong>Ternary Operators</strong></p>\n\n<p>Maybe you know about them. Not everyone likes them. However, I think your <code>renderScript()</code> method has a good example of where one would be acceptable. If you're not sure what they are google them, and try not to abuse them. Well abuse them so you learn how to use them, then go back and undo it all. Most people when they first learn about ternary operators use them too much and their code becomes illegible as a consequence. Just know that they are there to help not hinder, so use them only when they won't hinder your code, this means legibility too. Or just don't use them at all, many don't.</p>\n\n<pre><code>public function renderScript(){\n $apiKey = $this-&gt;_apyKey !== null ? '&amp;appId=' . $this-&gt;_apyKey : '';\n</code></pre>\n\n<p><strong>HTML Output From Methods</strong></p>\n\n<p>There are a lot of ways to go about generating HTML with PHP. Most people don't like to mix them however. As usr pointed out, it looks odd, and can confuse some people, especially those unfamiliar with PHP. I think its much cleaner to <code>include()</code> HTML when possible, or, in the case that usr is speaking of, escape to PHP from HTML rather than from PHP to HTML. So in the <code>renderButton()</code> method, I would return the <code>$dataAttributes</code> array and use that in the HTML file where you call this class and then escape into PHP when needed.</p>\n\n<pre><code>&lt;div class=\"fb-like\" &lt;?php foreach( $dataAttributes AS $dataAttr =&gt; $dataValue ) : echo \"$dataAttr=\\\"$dataValue\\\" \"; endforeach; ?&gt;&gt;&lt;/div&gt;\n</code></pre>\n\n<p>I used <code>:</code> and <code>endforeach;</code> in the above example instead of <code>{}</code> because this is how this is usually done in HTML documents. However, in this instance, it probably would be better to use the latter. Whichever improves legibility, I used the other simply to show you.</p>\n\n<p>In your <code>renderScript()</code> method I would just use an include and save that HTML to a separate file. Or at the very least, drop the variable and just return the heredoc. The <code>$markup</code> variable is otherwise unused, so unnecessary.</p>\n\n<pre><code> return &lt;&lt;&lt;HTML\n&lt;div id=\"fb-root\"&gt;&lt;/div&gt;\n&lt;script&gt;\n(function(d, s, id) {\n var js, fjs = d.getElementsByTagName(s)[0];\n if (d.getElementById(id)) return;\n js = d.createElement(s); js.id = id;\n js.src = \"//connect.facebook.net/en_US/all.js#xfbml=1$apiKey\";\n fjs.parentNode.insertBefore(js, fjs);\n}(document, 'script', 'facebook-jssdk'));\n&lt;/script&gt;\n\nHTML;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-03T22:29:53.353", "Id": "21478", "Score": "0", "body": "Thanks for reviewing this :) \nYour help is really appreciated, it's something i wrote some time ago and it was my first real \"object oriented\" approach to code, i agree on all the things you point out. \nPersonally i don't like includes because it means \"one more file to open\" but i agree with you that they would help in this case." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-03T21:21:58.690", "Id": "13293", "ParentId": "10071", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-16T15:00:43.943", "Id": "10071", "Score": "2", "Tags": [ "php", "design-patterns", "classes" ], "Title": "Set of classes for generating social plugins, is my design correct?" }
10071
<p>I'm trying to teach myself a new pattern, the command pattern, and came up with the following example. Looking for feedback.</p> <pre><code>public class BaseTool { private List&lt;ICommand&gt; CommandHistory = new List&lt;ICommand&gt;(); public string State = string.Empty; public BaseTool() { } public virtual void ExecuteCommand(ICommand cmd) { if (cmd.CanExecute(this)) { cmd.Execute(this); CommandHistory.Add(cmd); } } public string PrintHistory() { StringBuilder sb = new StringBuilder(); foreach (ICommand cmd in CommandHistory) { sb.AppendLine(cmd.ToString()); } return sb.ToString(); } } public class Tool : BaseTool { public Tool() { } } public interface ICommand { void Execute(BaseTool t); bool CanExecute(BaseTool t); } public class PowerDownCommand : ICommand { private DateTime _executeTime; public void Execute(BaseTool t) { if (!CanExecute(t)) { throw new Exception("Error turning off the tool"); } _executeTime = DateTime.Now; t.State = "OFF"; } public bool CanExecute(BaseTool t) { return (t != null); } public override string ToString() { return _executeTime.ToLongTimeString() + " : was powered down"; } } public class PowerUpCommand : ICommand { private DateTime _executeTime; public void Execute(BaseTool t) { if (!CanExecute(t)) { throw new Exception("Error turning on the tool"); } _executeTime = DateTime.Now; t.State = "ON"; } public bool CanExecute(BaseTool t) { return (t != null); } public override string ToString() { return _executeTime.ToLongTimeString() + " : was powered up"; } } class Program { static void Main(string[] args) { Tool t = new Tool(); t.ExecuteCommand(new PowerUpCommand()); Thread.Sleep(1000); t.ExecuteCommand(new PowerDownCommand()); Console.WriteLine(t.PrintHistory()); Console.Read(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-16T19:00:44.403", "Id": "16060", "Score": "0", "body": "Just curious, why do you have parentheses around (t != null)? And I'm not sure how much you gain in readability by having the CanExecute() method." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-19T04:10:14.867", "Id": "16149", "Score": "0", "body": "Zolomon - habit" } ]
[ { "body": "<p>The Command Pattern's goal is to decouple the requestor object from the object performing the request. Your example does that. </p>\n\n<p>However there is a small separation of responsibilities issue. Tool should not have to know to ask if ICommand can execute. That responsibility should be in the ICommand implementer. And because all interface members are public, <code>CanExecute()</code> should therefore be taken out of the interface.</p>\n\n<p>You should document and code for the fact that <code>ICommand.Execute()</code> throws an exception, by wrapping the call in a <code>try catch</code> block (or somewhere upstream; dependent on your big picture design). </p>\n\n<p>Finally, one of my pet peeves: the exception should give as much information as possible - like the fact that the Tool parameter was null. Use an exception appropriate for the situation: See <a href=\"http://msdn.microsoft.com/en-us/library/system.argumentexception.aspx\">ArguementException</a>. Exceptions are for developers not end users so get down and dirty with details. Hint: <code>Exception.Data</code></p>\n\n<pre><code>public interface ICommand\n{\n void Execute(BaseTool t);\n}\n\n//ICommand implementer\npublic void Execute(BaseTool t)\n{\n if (CanExecute(t))\n {\n _executeTime = DateTime.Now;\n t.State = \"OFF\";\n }else{\n throw new ArguementException(\"Error turning off the tool\"); //this message sux\n }\n}\n\n//Tool class\npublic virtual void ExecuteCommand(ICommand cmd)\n{\n try {\n cmd.Execute(this);\n CommandHistory.Add(cmd);\n }catch (Exception exception) {\n // whatever you do, do not just re-throw: \"throw exception;\".\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-18T00:55:57.467", "Id": "10108", "ParentId": "10075", "Score": "6" } } ]
{ "AcceptedAnswerId": "10108", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-16T16:48:45.137", "Id": "10075", "Score": "5", "Tags": [ "c#", "design-patterns" ], "Title": "Command Pattern" }
10075
<p>I have a class that produces a key based on the two objects passed. The key for the items passed is simply the string of the ID (a GUID) for each object. There is also a subclass that makes sure any to items are only represented once (sets).</p> <p>The classes looked like the first code block below. But then I ran into a performance problem where creating the key every time was accessed was just to slow. So I changed it such that I create the key in the constructor and store it in a member variable. But now it seems that the inheritance is overkill.</p> <p>Maybe the inheritance was always overkill but I didn't see it because I overrode an actual behavior so it seemed more OOPy? Or did it become inheritance abuse after the re-factoring? Or is it still fine but I am seeing it wrong?</p> <p>Note that the ID must be unique and is often, but not always, a GUID.</p> <pre><code>Public Interface IIdentifiable ReadOnly Property ID() As String End Interface Public Class Keyed Public Sub New(item1 As IIdentifiable, item2 As IIdentifiable) PrimaryItem = item1 SecondaryItem = item2 End Sub Public Property PrimaryItem As IIdentifiable Public Property SecondaryItem As IIdentifiable Public Overridable Function Key() As String Return PrimaryItem.ID &amp; SecondaryItem.ID End Function End Class Public Class KeyedForSet Inherits Keyed Public Sub New(item1 As IIdentifiable, item2 As IIdentifiable) MyBase.New(item1, item2) End Sub Public Overrides Function Key() As String If PrimaryItem.ID.CompareTo(SecondaryItem.ID) &gt; 0 Then Return PrimaryItem.ID &amp; SecondaryItem.ID Else Return SecondaryItem.ID &amp; PrimaryItem.ID End If End Function End Class </code></pre> <p>Second implementation for performance reason.</p> <pre><code>Public Class Keyed Public Sub New(item1 As IIdentifiable, item2 As IIdentifiable) mKey = item1.ID &amp; item2.ID PrimaryItem = item1 SecondaryItem = item2 End Sub Public Property PrimaryItem As IIdentifiable Public Property SecondaryItem As IIdentifiable Protected mKey as string Public Overridable Function Key() As String Return mKey End Function End Class Public Class KeyedForSet Inherits Keyed Public Sub New(item1 As IIdentifiable, item2 As IIdentifiable) MyBase.New(item1, item2) If PrimaryItem.ID.CompareTo(SecondaryItem.ID) &gt; 0 Then mKey = PrimaryItem.ID &amp; SecondaryItem.ID Else mKey = SecondaryItem.ID &amp; PrimaryItem.ID End If End Sub End Class </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-15T16:59:58.280", "Id": "22136", "Score": "0", "body": "If you asked me, the inheritance is not a good idea here. You're not inheriting anything but a different implementation of the `Key` function. You should make a common interface and make both classes implement it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-13T19:18:17.933", "Id": "27843", "Score": "0", "body": "FYI - your changes in the second implementation changed functionality. Prior to the change if you assign a new object to either `PrimaryItem` or `SecondaryItem` the key changed automatically. Not so with the second implementation." } ]
[ { "body": "<p>Based upon your use case, the code below is what I would recommend. I'm sorry that it is in C#, on this computer I don't have my vb.net loaded so it was easier to express in c#.</p>\n\n<p>There are 3 parts to this. The class on the bottom should address your needs (KeySet). the second class helps to make it more easily usable in your code (KeySetHelpers). The first class (MyExample) is just showing a few ways that you can utilize it. I think the direct approach is most natural.</p>\n\n<p>Regarding performance and inheritance. If you follow the process below, I don't think you need another layer of inheritance. Performance wise, I think that the collection you choose to utilize will matter more than the KeySet. Since in the end you are just utilizing strings anyway.</p>\n\n<p>One area I would recommend that you look into is the reason why you are flipping the primary/secondary keys based upon which is greater. Since you are already injecting which is the primary and which is secondary, they should most likely always have the same order when combined. Otherwise it could complicate the meaning of the key. Plus if you keep the order primary-secondary and normalize the key by stripping out anything non-alphanumeric and then adding in a parsing token like \"-\" between the too,...you wouldn't need to store the Key(composite), primary key, and secondary key. I hope this helps.</p>\n\n<pre><code>public class MyExample\n{\n public void Test()\n {\n // Junk Prep\n var primary = System.Guid.NewGuid();\n var secondary = System.Guid.NewGuid();\n var junkData = \"blah blah\";\n\n // Real usage\n var keysList = new List&lt;KeySet&gt;();\n\n keysList.Add(new KeySet(primary, secondary)); // as guid\n // or\n keysList.Add(new KeySet(primary.ToString(), secondary.ToString())); // as guid strings\n // or\n keysList.Add(primary, secondary);// direct as guid\n\n\n var keysDictionary = new Dictionary&lt;KeySet, object&gt;();\n\n keysDictionary.Add(new KeySet(primary, secondary), junkData); // as guid\n // or \n keysDictionary.Add(new KeySet(primary.ToString(), secondary.ToString()), junkData); // as guid strings\n // or\n keysDictionary.Add(primary, secondary, junkData); // direct as guid\n\n // etc.\n }\n}\n\npublic static class KeySetHelpers\n{\n #region Lists\n\n public static void Add(this List&lt;KeySet&gt; keyList, string primary, string secondary)\n {\n keyList.Add(new KeySet(primary, secondary));\n }\n\n public static void Add(this List&lt;KeySet&gt; keyList, Guid primary, Guid secondary)\n {\n keyList.Add(new KeySet(primary, secondary));\n }\n\n #endregion\n\n #region Dictionary\n\n public static void Add(this Dictionary&lt;KeySet, object&gt; keyDictionary, string primary, string secondary, object value)\n {\n keyDictionary.Add(new KeySet(primary, secondary), value);\n }\n\n public static void Add(this Dictionary&lt;KeySet, object&gt; keyDictionary, Guid primary, Guid secondary, object value)\n {\n keyDictionary.Add(new KeySet(primary, secondary), value);\n }\n\n #endregion\n}\n\n\n\npublic class KeySet : IComparable&lt;KeySet&gt;\n{\n public KeySet(Guid primary, Guid secondary) { EstablishKey(primary.ToString(), secondary.ToString()); }\n public KeySet(string primary, string secondary) { EstablishKey(primary, secondary); }\n\n #region Composite Key\n\n private void EstablishKey(string primary, string secondary)\n {\n if (string.Compare(primary, secondary) &gt; 0)\n {\n Key = primary + secondary;\n }\n else\n {\n Key = secondary + primary;\n }\n\n Primary = primary;\n Secondary = secondary;\n }\n\n public string Primary { get; private set; }\n public string Secondary { get; private set; }\n\n public string Key { get; private set; }\n\n #endregion\n\n #region Functional Overrides\n\n public override bool Equals(object obj)\n {\n return (obj is KeySet) ? Equals((KeySet)obj) : false;\n }\n\n public bool Equals(KeySet obj)\n {\n return CompareTo(obj) == 0;\n }\n\n public override int GetHashCode()\n {\n return Key.GetHashCode();\n }\n\n public override string ToString()\n {\n return Key;\n }\n\n #endregion\n\n public int CompareTo(KeySet other)\n {\n return string.Compare(Key, other.Key);\n }\n\n public static bool operator ==(KeySet obj1, KeySet obj2)\n {\n return obj1.Equals(obj2);\n }\n\n public static bool operator !=(KeySet obj1, KeySet obj2)\n {\n return !obj1.Equals(obj2);\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-17T02:05:38.760", "Id": "16072", "Score": "0", "body": "Just something to add on. Per your statement \"Note that the ID must be unique and is often, but not always, a GUID.\" Base upon your example, i would suggest normalizing to strings. Each new set of types you add on have to be hardened to ensure the object properly represents both the Equals() and GetHashCode() which can be hard if you frequently change root types." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-17T01:32:46.807", "Id": "10086", "ParentId": "10076", "Score": "1" } }, { "body": "<p>A simple and quick solution is to cache you GUID generated in your original design. Ask the cache first for the GUID corresponding to inputs, if not there then generate it and cache it :)\nYou can use Dictionary> for this, for key you can use any scheme like \"id1:id2\" string. (I assume ':' will not be part of an id ever, in case its false design your own scheme)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-15T02:52:43.603", "Id": "12607", "ParentId": "10076", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-16T16:58:47.460", "Id": "10076", "Score": "1", "Tags": [ ".net", "vb.net" ], "Title": "Inheriting needed when only difference is performed in the constructor?" }
10076
<p>I'd like this reviewed.</p> <pre><code>public sealed class FibonacciHeap&lt;TKey, TValue&gt; { readonly List&lt;Node&gt; _root = new List&lt;Node&gt;(); int _count; Node _min; public void Push(TKey key, TValue value) { Insert(new Node { Key = key, Value = value }); } public KeyValuePair&lt;TKey, TValue&gt; Peek() { if (_min == null) throw new InvalidOperationException(); return new KeyValuePair&lt;TKey,TValue&gt;(_min.Key, _min.Value); } public KeyValuePair&lt;TKey, TValue&gt; Pop() { if (_min == null) throw new InvalidOperationException(); var min = ExtractMin(); return new KeyValuePair&lt;TKey,TValue&gt;(min.Key, min.Value); } void Insert(Node node) { _count++; _root.Add(node); if (_min == null) { _min = node; } else if (Comparer&lt;TKey&gt;.Default.Compare(node.Key, _min.Key) &lt; 0) { _min = node; } } Node ExtractMin() { var result = _min; if (result == null) return null; foreach (var child in result.Children) { child.Parent = null; _root.Add(child); } _root.Remove(result); if (_root.Count == 0) { _min = null; } else { _min = _root[0]; Consolidate(); } _count--; return result; } void Consolidate() { var a = new Node[UpperBound()]; for (int i = 0; i &lt; _root.Count; i++) { var x = _root[i]; var d = x.Children.Count; while (true) { var y = a[d]; if (y == null) break; if (Comparer&lt;TKey&gt;.Default.Compare(x.Key, y.Key) &gt; 0) { var t = x; x = y; y = t; } _root.Remove(y); i--; x.AddChild(y); y.Mark = false; a[d] = null; d++; } a[d] = x; } _min = null; for (int i = 0; i &lt; a.Length; i++) { var n = a[i]; if (n == null) continue; if (_min == null) { _root.Clear(); _min = n; } else { if (Comparer&lt;TKey&gt;.Default.Compare(n.Key, _min.Key) &lt; 0) { _min = n; } } _root.Add(n); } } int UpperBound() { return (int)Math.Floor(Math.Log(_count, (1.0 + Math.Sqrt(5)) / 2.0)) + 1; } class Node { public TKey Key; public TValue Value; public Node Parent; public List&lt;Node&gt; Children = new List&lt;Node&gt;(); public bool Mark; public void AddChild(Node child) { child.Parent = this; Children.Add(child); } public override string ToString() { return string.Format("({0},{1})", Key, Value); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-16T19:04:17.427", "Id": "16061", "Score": "1", "body": "`a, x, d, y, t`: I think I would really enjoy reading your code if not for these random variable names. `i, n` are proper one-letter variable names because they are obvious, but the others are just confusing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-16T19:07:38.507", "Id": "16062", "Score": "1", "body": "@ANeves - Why don't you make your opinion more prominent by writing an answer? Keep in mind that this code has no dependencies so you can easily try it out." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-16T19:13:16.627", "Id": "16063", "Score": "0", "body": "@ANeves - By the way I would consider this a rough draft. Typically if I cannot quickly come up with a useful name I'll use a poor name and try again on a second pass." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-18T02:43:41.340", "Id": "16112", "Score": "0", "body": "Disclaimer: I gave it a superficial read without having VS2010 by my side. I second variable names, I would run StyleCop on this and listen to suggestions of it. I would rewrite one `else { if` as `elseif`. I personally would make the whole body of `public void Push(TKey key, TValue value)` a one-liner." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-18T03:11:50.120", "Id": "16114", "Score": "0", "body": "@Leonid - Write up an answer. The suggestion about the `if` is pretty good. I must have originally had some more code in there." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-19T09:37:19.590", "Id": "16155", "Score": "0", "body": "@ChaosPandion you are absolutely right in that answers should not be posted as comments. But since I do not feel confident about reviewing the actual code, I left it for someone else to address. I'll write down an answer, on style." } ]
[ { "body": "<p>Disclaimer: I will not address the actual FibonacciHeap itself, just the c# code.</p>\n\n<hr>\n\n<p>I explicitly write the <code>private</code> keyword on those methods and properties, so they are indented roughly the same as the <code>public</code> ones. A matter of preference, I guess.</p>\n\n<p>These <code>_name</code> variables are odd, I suggest using the de facto standard of PascalCase.</p>\n\n<p><code>_count</code> seems to be a duplication of <code>Root.count</code>. I would remove it.<br>\n<strong>However, ExtractMin adds items to the Root and does not increment count!</strong> This seems like a bug, but perhaps it's not. If it is, it is a strong justification for removing <code>_count</code>; if not, it could use a quick comment there to signal why <code>_count</code> is not updated.</p>\n\n<p>Because I like my variables very strongly typed, I don't like <code>var</code>. I changed most of its uses to an explicit type.</p>\n\n<p>You can if-chain if-elses better if you do not use parenthesis around the else that takes an if inside:</p>\n\n<pre><code>if (Min == null) {\n Root.Clear();\n Min = item;\n} else if (Comparer&lt;TKey&gt;.Default.Compare(item.Key, Min.Key) &lt; 0) {\n Min = item;\n} // else if() { } else if() { } etc\n</code></pre>\n\n<p>A <code>Node</code> does not seem to make sense without a <code>Key</code> and a <code>Value</code>, so I would add a constructor that takes those two.</p>\n\n<p>You overrode <code>Node.ToString</code>. I assume that was for debugging purposes? I would use the <code>DebuggerDisplay</code> attribute in the class, instead.</p>\n\n<hr>\n\n<p>Here is a proposal of reviewed code, with some highlights in comments:</p>\n\n<pre><code>public sealed class FibonacciHeap&lt;TKey, TValue&gt;\n{\n private readonly List&lt;Node&gt; Root = new List&lt;Node&gt;();\n // TODO: is this not a duplication of Root.Count? Remove it.\n private int _count;\n private Node Min;\n\n public void Push(TKey key, TValue value)\n {\n Insert(new Node(key, value));\n }\n\n public KeyValuePair&lt;TKey, TValue&gt; Peek()\n {\n if (Min == null)\n throw new InvalidOperationException();\n return new KeyValuePair&lt;TKey, TValue&gt;(Min.Key, Min.Value);\n }\n\n public KeyValuePair&lt;TKey, TValue&gt; Pop()\n {\n if (Min == null)\n throw new InvalidOperationException();\n var min = ExtractMin();\n return new KeyValuePair&lt;TKey, TValue&gt;(min.Key, min.Value);\n }\n\n private void Insert(Node node)\n {\n _count++;\n Root.Add(node);\n if (Min == null)\n {\n Min = node;\n } else if (Comparer&lt;TKey&gt;.Default.Compare(node.Key, Min.Key) &lt; 0)\n {\n Min = node;\n }\n }\n\n private Node ExtractMin()\n {\n var result = Min;\n if (result == null)\n return null;\n foreach (var child in result.Children)\n {\n child.Parent = null;\n // TODO: shouldn't _count be updated?? Same in Consolidate();\n Root.Add(child);\n }\n Root.Remove(result);\n if (Root.Count == 0)\n {\n Min = null;\n } else\n {\n Min = Root[0];\n Consolidate();\n }\n _count--;\n return result;\n }\n\n // Here be FibonacciHeap dragons.\n private void Consolidate()\n {\n var unlabeledBag = new Node[UpperBound()];\n for (int i = 0; i &lt; Root.Count; i++)\n {\n Node item = Root[i];\n int itemChildren = item.Children.Count;\n while (true)\n {\n Node child = unlabeledBag[itemChildren];\n if (child == null)\n break;\n if (Comparer&lt;TKey&gt;.Default.Compare(item.Key, child.Key) &gt; 0)\n {\n var swap = item;\n item = child;\n child = swap;\n }\n Root.Remove(child);\n i--;\n item.AddChild(child);\n child.Mark = false;\n unlabeledBag[itemChildren] = null;\n itemChildren++;\n }\n unlabeledBag[itemChildren] = item;\n }\n Min = null;\n for (int i = 0; i &lt; unlabeledBag.Length; i++)\n {\n var item = unlabeledBag[i];\n if (item == null)\n continue;\n if (Min == null)\n {\n Root.Clear();\n Min = item;\n } else if (Comparer&lt;TKey&gt;.Default.Compare(item.Key, Min.Key) &lt; 0)\n {\n Min = item;\n }\n Root.Add(item);\n }\n }\n\n private int UpperBound()\n {\n // Here be dragons.\n // Also, if _count is NOT Root.Count, it ought to at least have a more meaningful name.\n double magicValue = Math.Log(_count, (1.0 + Math.Sqrt(5)) / 2.0);\n return (int)Math.Floor(magicValue) + 1;\n }\n\n [DebuggerDisplay(\"{Key}, {Value}\")]\n private class Node\n {\n public TKey Key;\n public TValue Value;\n public Node Parent;\n public List&lt;Node&gt; Children = new List&lt;Node&gt;();\n public bool Mark;\n\n public Node(TKey key, TValue value)\n {\n Key = key;\n Value = value;\n }\n\n public void AddChild(Node child)\n {\n child.Parent = this;\n Children.Add(child);\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T21:52:02.613", "Id": "86237", "Score": "0", "body": "Prefer _camelCase for private fields. This is the OOTB standard Resharper enforces and indicates that the field is privately scoped to this instance. So, for example, extra care should be taken in case it's a backing field for a property. Using PascalCase could conflict with property refactoring, and plain camelCase you'd need to check if it's a local variable." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T13:03:40.317", "Id": "86329", "Score": "1", "body": "I really don't like those underscores in a language that is otherwise free of them. But unfortunately I have no alternative, so that is also the convention I use these days." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-19T10:30:12.863", "Id": "10145", "ParentId": "10077", "Score": "1" } } ]
{ "AcceptedAnswerId": "10145", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-16T17:00:56.890", "Id": "10077", "Score": "2", "Tags": [ "c#", "fibonacci-sequence", "heap" ], "Title": "Fibonacci heap implementation" }
10077
<p>I am trying to implement a shared cache for arrays. It must support two operations: set(owner, idx, value) and fetch(owner, idx) where <code>idx</code> is the index into the array and <code>owner</code> is an opaque handle to an owning object -- <code>fetch(owner_1, idx)</code> should return the value stored by <code>set(owner_1, idx)</code> only if the <code>owner</code> argument matches. The cache must be thread - safe but I do not want to rely on locking, i.e. mutexes. Failure in looking up cached values is fine - it is OK and expected that other threads will overwrite existing values in the shared cache, in which case <code>fetch</code> should just fail.</p> <p>So the <code>fetch</code> operation has to read the cache slot's <code>owner</code> field to check against its argument, and if it matches return the cache slot's <code>value</code> field. The problem is, without locks, another thread could overwrite one of these fields during that operation. This approach tries to get around that by assigning a <code>version</code> field to each cache slot. It only increases. The <code>fetch</code> operation reads the version (atomically) at the start of the operation and at the end; if these are not the same, something changed during the read and the result is invalid, even if the <code>owner</code> field apparently matched.</p> <p>The code below ensures that <code>version</code> is always incremented before <code>value</code> is updated, thus preventing <code>fetch</code> from returning a value from a different owner. (The functions <code>g_atomic_...</code> are provided by glib.) It "seems to work" - but can it be proven correct or incorrect?</p> <pre><code>struct _cache_slot { void* owner; gint version; gdouble value; }; struct _cache_slot cache[SIZE]; int point_cache_fetch(void *owner, gdouble* ret, gsize idx) { struct _cache_slot *slot = &amp;cache[idx]; gint version_start = g_atomic_int_get(&amp;(slot-&gt;version)); void* slot_owner = g_atomic_pointer_get(&amp;(slot-&gt;owner)); gdouble value = slot-&gt;value; gint version_finish = g_atomic_int_get(&amp;(slot-&gt;version)); if ((version_start == version_finish) &amp;&amp; (slot_owner == owner)) { *ret = value; return 1; } else { return 0; } } void point_cache_store(void *owner, gsize idx, gdouble value) { struct _cache_slot *slot = &amp;cache[idx]; g_atomic_pointer_set(&amp;(slot-&gt;owner), NULL); slot-&gt;version++; g_atomic_pointer_set(&amp;(slot-&gt;owner), owner); slot-&gt;value = value; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-17T14:42:10.347", "Id": "16083", "Score": "0", "body": "Shouldn't `slot` be declared as a pointer? As in, `struct *slot = &cache[idx];` . That's how you're accessing it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-17T14:48:03.397", "Id": "16084", "Score": "0", "body": "Err, `struct _cache_slot *slot = &cache[idx]`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-17T14:54:51.250", "Id": "16085", "Score": "0", "body": "Also, is it possible for two different threads to call `store` with the same `owner` object?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-17T17:12:47.003", "Id": "16089", "Score": "0", "body": "@joey about `slot` not being a pointer - you're right; I am paraphrasing this code from elsewhere and made that mistake. Edited to fix" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-17T17:16:35.907", "Id": "16090", "Score": "0", "body": "This is an error: `struct slot = cache[idx];` Here you are making a copy of the cache content. Then you modify this copy in the function (you never touch the cache). Thus the cache is never updated. This means the code is non functional (do you actually have unit tests?)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-17T17:16:44.473", "Id": "16091", "Score": "0", "body": "@joey I'll have to look at the callers in more detail to see if multiple threads attempt to set the same `owner`. If not, I can see how that could simplify the problem." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-17T17:44:53.703", "Id": "16094", "Score": "0", "body": "@loki Arghh... thanks for pointing this out. Edited to fix. This code is paraphrased, not copied, from the original source (which does have tests). So the code pasted here hasn't been tested." } ]
[ { "body": "<p>It's not clear from you're post whether <code>owner</code> is unique for each thread or if two threads can call the functions with the same value of <code>owner</code>. If two threads can call the functions with the same value for <code>owner</code>, your code is incorrect.</p>\n\n<p>If one thread is executing point_catch_store() and another thread calls point_catch_fetch() while the first thread is between these two lines, you'll get the old value (from the previous owner of the entry), not the new one:</p>\n\n<pre><code>g_atomic_pointer_set(&amp;(slot-&gt;owner), owner);\nslot-&gt;value = value;\n</code></pre>\n\n<p>As far as I can tell, swapping those two lines would solve that problem.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-18T14:11:37.330", "Id": "16133", "Score": "0", "body": "The reason for setting `owner` prior to setting `value` was to ensure that `version` is incremented before `value` is updated (because g_atomic_pointer_set() acts as a memory barrier). So I'm not sure if this change wouldn't introduce a new problem..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-05T07:07:18.777", "Id": "16974", "Score": "0", "body": "@gcbenison: You're right. There still a problem after swapping those two lines. I had an idea for a solution, but while writing the solution I noticed that I had basically re-invented locking. :-/" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-18T07:33:29.537", "Id": "10117", "ParentId": "10080", "Score": "2" } }, { "body": "<p>I do not believe this can be made thread-safe without a lock. Your solution fails for example when there are simultaneously two or more writers and one or more readers. More generally, race conditions are very difficult to foresee and you (or I) cannot predict or imagine them all. Why are you avoiding locks?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-28T03:21:01.213", "Id": "16555", "Score": "0", "body": "Looking at it again, note that version++ has three parts (read, modify, write) and so can be interrupted. One can imagine a scenario where version_finish < version_start. But maybe that is unrealistic in terms of the application logic." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-28T03:27:36.353", "Id": "16557", "Score": "0", "body": "Eg. thread A starts a store(), reads version 1 but is interrupted before setting 2; threads B and C store() setting version to 2 and then 3; thread D starts to fetch, reads version 3 and then is interrupted; threads E and F store() setting version to 4,5; thread A resumes and sets version to 2. Thread C resumes reads version 2. This is a convoluted example of course :-)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-21T19:39:24.243", "Id": "10227", "ParentId": "10080", "Score": "2" } } ]
{ "AcceptedAnswerId": "10227", "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-16T19:27:44.737", "Id": "10080", "Score": "3", "Tags": [ "c", "multithreading" ], "Title": "Implementing a shared array cache without locking" }
10080
<pre><code>public sealed class SinglyLinkedList&lt;T&gt; : IEnumerable&lt;T&gt; { readonly static SinglyLinkedList&lt;T&gt; _empty = new SinglyLinkedList&lt;T&gt;(); readonly bool _isEmpty; readonly T _head; readonly SinglyLinkedList&lt;T&gt; _tail; private SinglyLinkedList() { _isEmpty = true; } private SinglyLinkedList(T head) { _isEmpty = false; _head = head; } private SinglyLinkedList(T head, SinglyLinkedList&lt;T&gt; tail) { _isEmpty = false; _head = head; _tail = tail; } public static SinglyLinkedList&lt;T&gt; Empty { get { return _empty; } } public int Count { get { var list = this; var count = 0; while (!list._isEmpty) { count++; list = list._tail; } return count; } } public bool IsEmpty { get { return _isEmpty; } } public T Head { get { if (_isEmpty) throw new InvalidOperationException("The list is empty."); return _head; } } public SinglyLinkedList&lt;T&gt; Tail { get { if (_tail == null) throw new InvalidOperationException("This list has no tail."); return _tail; } } public static SinglyLinkedList&lt;T&gt; FromEnumerable(IEnumerable&lt;T&gt; e) { if (e == null) throw new ArgumentNullException("e"); return FromArrayInternal(e.ToArray()); } public static SinglyLinkedList&lt;T&gt; FromArray(params T[] a) { if (a == null) throw new ArgumentNullException("a"); return FromArrayInternal(a); } public SinglyLinkedList&lt;T&gt; Append(T value) { var array = new T[Count + 1]; var list = this; var index = 0; while (!list._isEmpty) { array[index++] = list._head; list = list._tail; } array[index] = value; return FromArrayInternal(array); } public SinglyLinkedList&lt;T&gt; Prepend(T value) { return new SinglyLinkedList&lt;T&gt;(value, this); } public SinglyLinkedList&lt;T&gt; Insert(int index, T value) { if (index &lt; 0) throw new ArgumentOutOfRangeException("index", "Cannot be less than zero."); var count = Count; if (index &gt;= count) throw new ArgumentOutOfRangeException("index", "Cannot be greater than count."); var array = new T[Count + 1]; var list = this; var arrayIndex = 0; while (!list._isEmpty) { if (arrayIndex == index) { array[arrayIndex++] = value; } array[arrayIndex++] = list._head; list = list._tail; } return FromArrayInternal(array); } public IEnumerator&lt;T&gt; GetEnumerator() { var list = this; while (!list._isEmpty) { yield return list._head; list = list._tail; } } public override string ToString() { if (_isEmpty) return "[]"; return string.Format("[{0}...]", _head); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } static SinglyLinkedList&lt;T&gt; FromArrayInternal(T[] a) { var result = Empty; for (var i = a.Length - 1; i &gt;= 0; i--) { result = result.Prepend(a[i]); } return result; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T01:36:10.860", "Id": "67442", "Score": "1", "body": "Just want to point out that Microsoft has put out an [immutable collections library](https://www.nuget.org/packages/Microsoft.Bcl.Immutable/)" } ]
[ { "body": "<ol>\n<li>The constructor with one argument is never used and doesn't make much sense (list with a head but no tail?).</li>\n<li>You shouldn't use <code>Count</code> in your own methods unless absolutely necessary, because it's O(n). Or you should cache the result in a field.</li>\n<li>Because you use <code>Count</code> so often, your <code>Insert()</code> walks through the whole list three times! The second time it's because of completely unnecessary <code>Count</code>. You should completely rewrite it, <code>Insert()</code> can be done in O(index), which can be much better than your O(n).</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-16T22:16:54.427", "Id": "10085", "ParentId": "10083", "Score": "3" } }, { "body": "<p>You might consider separating out the functionality between the controller/iterator and the item. For example, try using something like what is below (or an alteration of it). In any linked list scenario, the item itself is the controller of before/after pointers. Since you are wanting a single linked list, you would probably be best served with having an item class. Now that you have that, you can simply implement a controller which represents the whole list and the more user friendly functionality.</p>\n\n<p>Single linked item example:</p>\n\n<pre><code>public class SingleLinkedItem&lt;T&gt;\n{\n public SingleLinkedItem(SingleLinkedList&lt;T&gt; list, SingleLinkedItem&lt;T&gt; itemBefore, T item)\n {\n if (ItemBefore.List != list)\n throw new Exception(\"Item being added must be from the same list.\");\n\n List = list;\n ItemBefore = itemBefore;\n Item = item;\n }\n\n public readonly SingleLinkedList&lt;T&gt; List;\n public SingleLinkedItem&lt;T&gt; ItemBefore { get; set; }\n public readonly T Item;\n}\n</code></pre>\n\n<p>Controller example:</p>\n\n<pre><code>public sealed class SingleLinkedList&lt;T&gt;\n{\n public SingleLinkedItem&lt;T&gt; First { get; private set; }\n public SingleLinkedItem&lt;T&gt; Last { get; private set; }\n public long Length { get; private set; }\n\n public void Add(T item)\n {\n var linkedItem = new SingleLinkedItem&lt;T&gt;(this, Last, item);\n\n Last = linkedItem;\n\n Length++;\n\n if (First == null)\n First = Last;\n }\n}\n</code></pre>\n\n<p>These examples focus on a fast append style, which also means that searching or iterating over it will always be in reverse order. If you need a fast-forward search and can sacrifice a slower append, just reverse the linked direction.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-17T17:12:52.917", "Id": "10095", "ParentId": "10083", "Score": "2" } } ]
{ "AcceptedAnswerId": "10085", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-16T21:29:15.023", "Id": "10083", "Score": "1", "Tags": [ "c#", "linked-list", "immutability" ], "Title": "Care to review my immutable singly linked list?" }
10083
<p>I'm writing an if with nested conditions and end up with this ugly if:</p> <pre><code>if( !arg || (typeof arg.search != 'undefined' &amp;&amp; typeof arg.done == 'undefined' &amp;&amp; item.attributes.text.toLowerCase().indexOf(arg.search.toLowerCase()) != -1) || typeof arg.search != 'undefined' &amp;&amp; typeof arg.done != 'undefined' &amp;&amp; (arg.done &amp;&amp; item.attributes.done) || (!arg.done &amp;&amp; !item.attributes.done) &amp;&amp; item.attributes.text.toLowerCase().indexOf(arg.search.toLowerCase()) != -1 ){ renderView(); } </code></pre> <p>This pice of code is actually working but I don't like the style of it. How can I improve this code to make it cleaner and more readable.</p> <h2>In plain English</h2> <p>if <code>arg</code> is not passed <strong>OR</strong> if <code>arg.search</code> exist but <code>arg.done</code> is not exist and there is something similar to <code>arg.search</code> in <code>item.attributes.text</code> <strong>OR</strong> if <code>arg.search</code> and <code>arg.done</code> exist and there is something similar to <code>arg.search</code> in <code>item.attributes.text</code> call that function.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-17T13:21:11.433", "Id": "16080", "Score": "0", "body": "You can get rid of the typeof checks and just check for undefined. `arg.search !== undefined`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-17T15:51:01.477", "Id": "16086", "Score": "0", "body": "@epascarello Yeah, you don't want to do that. `typeof blah == 'undefined'` will **always** work. But `blah == undefined` will only **usually** work. http://weblogs.asp.net/bleroy/archive/2006/08/02/Define-undefined.aspx" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-17T16:55:06.293", "Id": "16088", "Score": "0", "body": "@RossPatterson That's a silly reason. Your code might break if e.g. Math were redefined, but we don't worry about that. The serious reason to use typeof for testing undefined is that `typeof foo === 'undefined'` *does not throw if `foo` does not exist* and so can be used for testing. But that does not apply to property accesses, which do not throw on absence." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-18T01:50:27.940", "Id": "16110", "Score": "0", "body": "@KevinReid I wish I had a buck for every time I've found a variable called `undefined` in a JavaScript program." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-18T13:40:46.190", "Id": "16131", "Score": "0", "body": "Than redefine `undefined` yourself, it is not hard." } ]
[ { "body": "<p>Obviously there's no way I can try this out but you could organize your code in functions. Also I don't understand why this:</p>\n\n<pre><code>(arg.done &amp;&amp; item.attributes.done) || (!arg.done &amp;&amp; !item.attributes.done)\n</code></pre>\n\n<p>If both exist or don't exist seems trivial...What's the logic here?<br>\nI would do something like this:</p>\n\n<pre><code>var argExist = function () {\n\n var exist = true,\n isUdf = function (o) {\n return (typeof o === 'undefined') ? false : true;\n },\n atts = !!~item.attributes.text.toLowerCase().indexOf(arg.search.toLowerCase());\n\n if (!arg || ( !isUdf(arg.search) &amp;&amp; isUdf(arg.done) &amp;&amp; atts) ) {\n exist = false;\n }\n\n return exist;\n\n};\n\nif (!argExists()) { renderView(); }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-17T10:22:21.337", "Id": "10092", "ParentId": "10087", "Score": "3" } }, { "body": "<p>This is what comments are for. Leave the code as it is, and explain its intent with your \"In Plain English\" version. But polish it up a bit, making it less boolean-logic-y - something more like \"If we didn't get any arguments, or if we got a search that resembles this item, show it.\"</p>\n\n<p>As an aside, your English version seems wrong, which is part of the reason why the text should describe its intent, not its process. Translated to pure boolean, it reads:</p>\n\n<pre><code>!A | (B &amp; !C &amp; D) | (B &amp; C &amp; D)\n</code></pre>\n\n<p>but the code reads</p>\n\n<pre><code>!A | (!B &amp; C &amp; D) | (!B &amp; !C &amp; (E &amp; F)) | ((!E &amp; !E) &amp; D)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-17T16:15:08.967", "Id": "10094", "ParentId": "10087", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-17T04:03:18.800", "Id": "10087", "Score": "-1", "Tags": [ "javascript" ], "Title": "Rendering a view if item is done or contains a search term" }
10087
<p>I've created a functional A* implementation in C#/XNA for a game I'm working on. However, I am using rather large paths, and of course, the larger the paths are, the longer it takes to trace them. There is no way to shorten the paths (Thin Maze - Style) and I assume this is a horrid way to implement it. I followed <a href="https://web.archive.org/web/20171022224528/http://www.policyalmanac.org:80/games/aStarTutorial.htm" rel="nofollow noreferrer">a tutorial</a>, and hope I can get some help in optimizing it.</p> <pre><code> static public List&lt;Point&gt; FindPath(Point Start, Point End) { List&lt;Square&gt; Open = new List&lt;Square&gt;(); List&lt;Square&gt; Closed = new List&lt;Square&gt;(); Open.Add(new Square(Start)); Square currentSquare = Open[0]; Square PS = new Square(new Point(0, 0)); int index = 0; int Dupes = 0; while (Open.Count &gt; 0 &amp;&amp; currentSquare.Pos != End &amp;&amp; index &lt; 1000 &amp;&amp; Dupes &lt; 1) { if (currentSquare == PS) { Dupes++; } else { Dupes = 0; } index++; Open.Sort(new CompareSquareH()); currentSquare = Open[0]; Closed.Add(currentSquare); Open.Remove(currentSquare); for (int x = -1; x &lt;= 1; x++) { for (int y = -1; y &lt;= 1; y++) { if (!(x == -1 &amp;&amp; y == -1) &amp;&amp; !(x == 1 &amp;&amp; y == -1) &amp;&amp; !(x == 1 &amp;&amp; y == 1) &amp;&amp; !(x == -1 &amp;&amp; y == 1)) { if (x + currentSquare.Pos.X &gt; 0 &amp;&amp; x + currentSquare.Pos.X &lt; ED.LoadedMap.Tiles.GetLength(0) &amp;&amp; y + currentSquare.Pos.Y &gt; 0 &amp;&amp; y + currentSquare.Pos.Y &lt; ED.LoadedMap.Tiles.GetLength(1)) { if (!ED.LoadedMap.Tiles[x + currentSquare.Pos.X, y + currentSquare.Pos.Y].Solid) { bool pass = true; foreach (Square S in Closed) { if (S.Pos == new Point(currentSquare.Pos.X + x, currentSquare.Pos.Y + y)) { pass = false; break; } } if (pass) { foreach (Square S in Open) { if (S.Pos == new Point(currentSquare.Pos.X + x, currentSquare.Pos.Y + y)) { pass = false; break; } } Open.Add(new Square(new Point(currentSquare.Pos.X + x, currentSquare.Pos.Y + y), currentSquare, H(currentSquare.Pos.X + x, End.X, currentSquare.Pos.Y + y, End.Y))); } } } } } } } if (Open.Count &gt; 0 &amp;&amp; currentSquare.Pos == End &amp;&amp; index &lt; 1000) { List&lt;Point&gt; Final = new List&lt;Point&gt;(); while (currentSquare.Parent != null) { Final.Add(new Point(currentSquare.Pos.X, currentSquare.Pos.Y)); currentSquare = currentSquare.Parent; } Final.Reverse(); return Final; } else { return new List&lt;Point&gt;(); } } static public List&lt;Point&gt; FindPath(Point Start, Point End) { List&lt;Square&gt; Open = new List&lt;Square&gt;(); List&lt;Square&gt; Closed = new List&lt;Square&gt;(); Open.Add(new Square(Start)); Square currentSquare = Open[0]; Square PS = new Square(new Point(0, 0)); int index = 0; int Dupes = 0; while (Open.Count &gt; 0 &amp;&amp; currentSquare.Pos != End &amp;&amp; index &lt; 1000 &amp;&amp; Dupes &lt; 1) { if (currentSquare == PS) { Dupes++; } else { Dupes = 0; } index++; Open.Sort(new CompareSquareH()); currentSquare = Open[0]; Closed.Add(currentSquare); Open.Remove(currentSquare); for (int x = -1; x &lt;= 1; x++) { for (int y = -1; y &lt;= 1; y++) { if (!(x == -1 &amp;&amp; y == -1) &amp;&amp; !(x == 1 &amp;&amp; y == -1) &amp;&amp; !(x == 1 &amp;&amp; y == 1) &amp;&amp; !(x == -1 &amp;&amp; y == 1)) { if (x + currentSquare.Pos.X &gt; 0 &amp;&amp; x + currentSquare.Pos.X &lt; ED.LoadedMap.Tiles.GetLength(0) &amp;&amp; y + currentSquare.Pos.Y &gt; 0 &amp;&amp; y + currentSquare.Pos.Y &lt; ED.LoadedMap.Tiles.GetLength(1)) { if (!ED.LoadedMap.Tiles[x + currentSquare.Pos.X, y + currentSquare.Pos.Y].Solid) { bool pass = true; foreach (Square S in Closed) { if (S.Pos == new Point(currentSquare.Pos.X + x, currentSquare.Pos.Y + y)) { pass = false; break; } } if (pass) { foreach (Square S in Open) { if (S.Pos == new Point(currentSquare.Pos.X + x, currentSquare.Pos.Y + y)) { pass = false; break; } } Open.Add(new Square(new Point(currentSquare.Pos.X + x, currentSquare.Pos.Y + y), currentSquare, H(currentSquare.Pos.X + x, End.X, currentSquare.Pos.Y + y, End.Y))); } } } } } } } if (Open.Count &gt; 0 &amp;&amp; currentSquare.Pos == End &amp;&amp; index &lt; 1000) { List&lt;Point&gt; Final = new List&lt;Point&gt;(); while (currentSquare.Parent != null) { Final.Add(new Point(currentSquare.Pos.X, currentSquare.Pos.Y)); currentSquare = currentSquare.Parent; } Final.Reverse(); return Final; } else { return new List&lt;Point&gt;(); } } static int H(int X1, int X2, int Y1, int Y2) { return Math.Abs(X1 - X2) + Math.Abs(Y1 - Y2) + ED.LoadedMap.Tiles[X1,X2].GetCost(); } } public class Square { public Square(Point pos, Square parent, int h) { Pos = pos; Parent = parent; H = h; } public Square(Point pos) { Pos = pos; } public int H; public Point Pos; public Square Parent; } public class CompareSquareH : IComparer&lt;Square&gt; { int IComparer&lt;Square&gt;.Compare(Square x, Square y) { if (x.H &gt; y.H) { return 1; } if (x.H &lt; y.H) { return -1; } return 0; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-17T08:41:05.133", "Id": "16077", "Score": "0", "body": "Have you considered caching results for frequently used values? This is probably the easiest way to gain some performance with the least effort." } ]
[ { "body": "<p>The #1 mistake I see in new A* implementations, which is the mistake you've made, is not using a <a href=\"http://en.wikipedia.org/wiki/Priority_queue\" rel=\"nofollow\">priority queue</a> for the open set, and not using a better data structure than a list (e.g. a tree or hash map) for the closed set. That means operations like:</p>\n\n<pre><code>Open.Sort(new CompareSquareH());\ncurrentSquare = Open[0];\nClosed.Add(currentSquare);\nOpen.Remove(currentSquare);\n</code></pre>\n\n<p>Require O(n * lg n) for the sort, O(n) for the add, and O(n) for the removal. Likewise, checks like finding whether a node is in the open or closed set, for which you used:</p>\n\n<pre><code>foreach (Square S in Closed)\n</code></pre>\n\n<p>Are obviously O(n), when with other structures like a tree or hashed set they can take O(lg n) or O(1).</p>\n\n<p>This adds entire orders of magnitude to the computation time required.</p>\n\n<p>The tutorial you have found looks pretty awful (although it does mention this). I recommend instead <a href=\"http://theory.stanford.edu/~amitp/GameProgramming/\" rel=\"nofollow\">Amit's A* pages</a>, particularly <a href=\"http://theory.stanford.edu/~amitp/GameProgramming/ImplementationNotes.html#set-representation\" rel=\"nofollow\">the section on implementing the open and closed sets</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-18T09:38:28.130", "Id": "10119", "ParentId": "10088", "Score": "3" } } ]
{ "AcceptedAnswerId": "10119", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2012-03-17T04:47:11.820", "Id": "10088", "Score": "1", "Tags": [ "c#", "performance", "algorithm", "pathfinding" ], "Title": "A* Implementation results in exponential speed loss" }
10088
<p>The <a href="https://github.com/swapsmagic/CausesPuzzle/tree/0fd7fe69e0f55ee03ac16adec6a7809c4b55dfd5" rel="nofollow">"Causes" puzzle</a> is to recursively find, starting with the word "causes", the number of words that can be formed by substituting one letter.</p> <pre><code>sub addMember { my ( $self, $newMember ) = @_; my $len = length($newMember-&gt;{'_data'}); my $newMemberIndex = push(@{$self-&gt;{'_MemberList'}}, $newMember) - 1; $self-&gt;{'_MemberHash'}-&gt;{$newMember-&gt;{'_data'}} = \$newMember; #Fetch bucket of same length and check for distance my $memberList = $self-&gt;{'_Bucket'}-&gt;getBucket($len); foreach my $index (@$memberList){ if($index eq $newMemberIndex) { next; } my $memberObj = $self-&gt;{'_MemberList'}[$index]; if($self-&gt;isFriend($newMember-&gt;{'_data'}, $memberObj-&gt;{'_data'}) eq true) { $newMember-&gt;addNeighbour($index); $memberObj-&gt;addNeighbour($newMemberIndex); } } #Fetch bucket of length - 1 and check for distance $memberList = $self-&gt;{'_Bucket'}-&gt;getBucket($len-1); foreach my $index (@$memberList){ if($index eq $newMemberIndex) { next; } my $memberObj = $self-&gt;{'_MemberList'}[$index]; if($self-&gt;isFriend($newMember-&gt;{'_data'}, $memberObj-&gt;{'_data'}) eq true) { $newMember-&gt;addNeighbour($index); $memberObj-&gt;addNeighbour($newMemberIndex); } } #Fetch Bucket of length + 1 and check for distance $memberList = $self-&gt;{'_Bucket'}-&gt;getBucket($len+1); foreach my $index (@$memberList){ if($index eq $newMemberIndex) { next; } my $memberObj = $self-&gt;{'_MemberList'}-&gt;[$index]; if($self-&gt;isFriend($newMember-&gt;{'_data'}, $memberObj-&gt;{'_data'}) eq true) { $newMember-&gt;addNeighbour($index); $memberObj-&gt;addNeighbour($newMemberIndex); } } #Add to the member list $self-&gt;{_Bucket}-&gt;addToBucket($len, $newMemberIndex); } </code></pre>
[]
[ { "body": "<p>Here is one idea: You could first put the words into a hashmap, the length of them being the key. O(n)</p>\n\n<p>Then, since you are only interested in \"causes\", grab that word and make a node and remove it from the hashmap. </p>\n\n<p>Then, a recursive function</p>\n\n<ul>\n<li>adds all friends to the node that are in the hashmap (only looking at the relevant lengths)</li>\n<li>removes those from the hashmap</li>\n<li>calls itself on those new nodes</li>\n</ul>\n\n<p>The end result is the social graph of \"causes\".</p>\n\n<p>It really depends what you are interested in in improving though: For instance, one could assume the whole thing is only called once for a fixed string, or it could be called many many times for different inputs. Depending on that, one might precompute more.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-17T23:17:16.727", "Id": "10105", "ParentId": "10089", "Score": "1" } } ]
{ "AcceptedAnswerId": "10105", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-17T05:52:31.033", "Id": "10089", "Score": "1", "Tags": [ "graph", "perl", "edit-distance" ], "Title": "\"Causes\" Puzzle solution (network of words with Levenshtein distance 1)" }
10089
<p>After <a href="https://stackoverflow.com/questions/9743859/how-to-represent-class-that-contains-no-methods-only-fields">my question on StackOverflow</a>, I've written code that should create a <code>Config</code> class from an XML file. XML loading is mixed with structures declaration and break in a lot of small pieces.</p> <p>However, I'm not sure if this is bad or good. How would you refactor this? Probably some simple design pattern can be used, but again, I'm not sure that I should use design patterns for such simple things as XML loading.</p> <pre><code>using System; using System.Net; using System.Xml; namespace Fast.Config { public class Config { public Config(string configFile) { Load(configFile); } public Channel Fond { get; private set; } private void Load(string file) { XmlDocument doc = new XmlDocument(); doc.Load(file); XmlElement fondChannel = doc.SelectNodes("//channel[@id=\"FOND\"]")[0] as XmlElement; Fond = new Channel(fondChannel); } } public class Channel { public Channel(XmlElement channel) { Load(channel); } private void Load(XmlElement node) { var connections = node.SelectNodes(".//connections"); var ordersIncrementalConnection = (connections[0] as XmlElement).SelectNodes(".//connection[@id=\"OLR\"]"); OrdersIncremental = new Connection(ordersIncrementalConnection[0] as XmlElement); } public Connection OrdersIncremental { get; private set; } } public class Connection { public Connection(XmlElement connection) { Load(connection); } private void Load(XmlElement connection) { XmlElement feedA = connection.SelectNodes(".//feed[@id=\"A\"]")[0] as XmlElement; FeedA = new Feed(feedA); XmlElement feedB = connection.SelectNodes(".//feed[@id=\"B\"]")[0] as XmlElement; FeedB = new Feed(feedB); } public Feed FeedA { get; private set; } public Feed FeedB { get; private set; } } public class Feed { public Feed(XmlElement feed) { Load(feed); } private void Load(XmlElement feed) { } } } </code></pre>
[]
[ { "body": "<p>Make sure you code defensively, I see many potential null reference exceptions. Verify all inputs (what happens if you put a null value or a string like \"adsf\") in your Config constructor. What happens if you don't have a xml file in the proper configuration, what if a node is missing?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-18T09:29:50.403", "Id": "16127", "Score": "0", "body": "this code is not something i'm going to sell. this is for me and i always have well-formed xml file. however i need code that easy to support" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-17T22:37:50.170", "Id": "10102", "ParentId": "10100", "Score": "1" } }, { "body": "<p>If you choose to manually parse the Xml document for loading only, I would prefer not to use the <code>XmlDocument</code> classes. They have a performance penalty. Instead use the <code>XPathDocument</code> and the <code>XPathNavigator</code> class to navigate trough your document.</p>\n\n<pre><code> void ReadXml(XmlReader reader)\n {\n XPathDocument document = new XPathDocument( reader );\n XPathNavigator navigator = document.CreateNavigator();\n\n foreach (XPathNavigator nav in navigator.Select( \"/*/*\" ))\n {\n string keyValue = nav.GetAttribute( \"SomeAttribute\", navigator.NamespaceURI ); \n }\n }\n</code></pre>\n\n<p>Second, i would prefer not to manually parse XML at all but create strong-typed classes in your project that you can serialize and deserialize. That makes the usage of you configuration more easy.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-28T08:20:45.690", "Id": "10391", "ParentId": "10100", "Score": "4" } } ]
{ "AcceptedAnswerId": "10391", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-17T20:12:56.263", "Id": "10100", "Score": "2", "Tags": [ "c#", "xml" ], "Title": "Loading config file from XML" }
10100
<pre><code>int *getUserInput(FILE *fpin, int *elementCount) { int *userInput; // Load file into buffer int length = fileLength(fpin); char *buffer = (char *) malloc(length * sizeof(char)); int written = fread(buffer, sizeof(char), length, fpin); // Number of int's allocated in userInput int allocated = 10; *elementCount = 0; // Allocate space for the numbers userInput = (int *) malloc(allocated * sizeof(int)); // "tokenize" the buffer with " " and "\n" as delimiters char *tokenized = strtok(buffer, " \n"); while (tokenized != NULL) { if (allocated == *elementCount) { allocated *= 2; // Reallocate space based on need realloc(userInput, allocated * sizeof(int)); } // Store the number in the array userInput[(*elementCount)++] = atoi(tokenized); tokenized = strtok(NULL, " \n"); } realloc(userInput, *elementCount * sizeof(int)); free(buffer); return userInput; } </code></pre> <p>It's a function I wrote for reading in numbers from a file, delimited by a space. Curious to hear any thoughts/possible improvements.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-21T16:25:23.347", "Id": "16264", "Score": "0", "body": "note that sizeof(char) is 1 by definition and so is redundant (noise)" } ]
[ { "body": "<p>Check that malloc didn't return NULL; in general, use defensive programming; That means always assume things went wrong, and check all return values. It helps with debugging too.</p>\n\n<p>You should be aware that strtok and atoi are not safe functions for arbitrary user input. That means you are vulnerable to stack/buffer overflows. Read the man pages of the two functions carefully. Consider using \\0-safe functions instead, or at least put a \\0 at the end of the input strings.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-17T23:10:42.710", "Id": "10104", "ParentId": "10103", "Score": "2" } }, { "body": "<pre><code>int *getUserInput(FILE *fpin, int *elementCount) {\n int *userInput;\n // Load file into buffer\n int length = fileLength(fpin);\n char *buffer = (char *) malloc(length * sizeof(char));\n</code></pre>\n\n<p>You may want to check the return value of <code>malloc</code>. It could return NULL. However, many people don't because its rare and there's not a lot you can do to recover when it happens.</p>\n\n<pre><code> int written = fread(buffer, sizeof(char), length, fpin);\n</code></pre>\n\n<p>Why is your variable called <code>written</code> when you are reading? Why are you storing this in a variable and never do anything with it? You should really check the return value because it may indicate there was a problem reading the file. If you just ignore it, that'll be really confusing if it happens. Fread doesn't put the null at the end of what it reads, you need to do that manually if you are going to use string functions.</p>\n\n<pre><code> // Number of int's allocated in userInput\n int allocated = 10;\n *elementCount = 0;\n // Allocate space for the numbers\n userInput = (int *) malloc(allocated * sizeof(int));\n</code></pre>\n\n<p>In actual C, you don't need to case the return value of malloc.</p>\n\n<pre><code> // \"tokenize\" the buffer with \" \" and \"\\n\" as delimiters\n char *tokenized = strtok(buffer, \" \\n\");\n while (tokenized != NULL) {\n if (allocated == *elementCount) {\n allocated *= 2;\n // Reallocate space based on need\n realloc(userInput, allocated * sizeof(int));\n</code></pre>\n\n<p>realloc is allowed to return a new pointer, having moved your data elsewhere. But you don't look at the return value which means your code will fail.</p>\n\n<pre><code> }\n</code></pre>\n\n<p>You code is a mix on input and keep track of the array of items. I suggest splitting out the logic dealing with the list into its own function.</p>\n\n<pre><code> // Store the number in the array\n userInput[(*elementCount)++] = atoi(tokenized);\n tokenized = strtok(NULL, \" \\n\");\n }\n realloc(userInput, *elementCount * sizeof(int));\n</code></pre>\n\n<p>Again, realloc may move your pointer. You need to look at the return value. Also consider what happens if there is an allocation error?</p>\n\n<pre><code> free(buffer);\n return userInput;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-18T00:33:10.273", "Id": "10107", "ParentId": "10103", "Score": "2" } }, { "body": "<h3>Looking at the code</h3>\n\n<p>Lets make it readable by indenting more than one character! Two is acceptable but more usall is around four.</p>\n\n<p>OK we assume this is reading from some file descriptor but it is not a standard function.</p>\n\n<pre><code> int length = fileLength(fpin);\n</code></pre>\n\n<p>The worst problem with C code is that people don't check the error codes from system function calls. <strong>ALWAYS</strong> check the error code. There may not be mcuh you can do (apart from log a message). <strong>BUT</strong> it is nice to know that you crashed because you ran out of memory rather than there being a bug in your code. Since you are using functions that assume the buffer is correctly terminated I would add an extra character to the buffer and stick '\\0' into the location.</p>\n\n<pre><code> char *buffer = (char *) malloc((length+1) * sizeof(char));\n\n // Add\n if (buffer == NULL)\n { printf(stdout, \"malloc() failed\\n\";\n exit(1);\n }\n buffer[length] = '\\0'\n</code></pre>\n\n<p>The fread() function may fail you need to check the amount read is what you expected (also you should probably re-name to make it easier to understand). </p>\n\n<pre><code> int readObjects = fread(buffer, sizeof(char), length, fpin);\n\n // Add\n if (readObjects != length)\n {\n if (feof(fpin)) { /* Report unexpected EOF */ }\n if (ferror(fpin)) { /* Report ERROR */}\n }\n</code></pre>\n\n<p>The realloc() function is very often used incorrectly. It it returns NULL when it failed to re-alloc a bigger space (but then the old memory is not freed). So you must catch the result of realloc into a temporary and only swap with your buffer if non NULL. Since we don't know if the realloc will work don't update your allocated value until you know it has worked.</p>\n\n<pre><code> if (allocated == *elementCount) {\n allocated *= 2;\n // Reallocate space based on need\n realloc(userInput, allocated * sizeof(int));\n }\n\n // Should be written like this:\n\n if (allocated == *elementCount)\n {\n int* tmp = realloc(userInput, allocated * sizeof(int) * 2);\n if (tmp == NULL)\n {\n printf(\"realloc() failed\\n\";\n exit(1);\n }\n allocated *= 2;\n userInput = tmp;\n }\n</code></pre>\n\n<p>According to the documentaion atoi() has been deprecated in favor of <code>strtol()</code>, and is equivalent to <code>(int)strtol(str, (char **)NULL, 10)</code> So you should probably use that. And another point to check for errors.</p>\n\n<pre><code> userInput[(*elementCount)++] = atoi(tokenized);\n</code></pre>\n\n<h3>Technique used.</h3>\n\n<p>I would not have bothered to read the data into its own buffer (then tokenize it). The C library has a perfectly good stream reading library in scanf(). The same functionality can be achieved using:</p>\n\n<pre><code>int value;\nwhile(fscanf(fpin, \" %d\",&amp;value) == 1)\n{\n // We read a value now store it.\n}\n</code></pre>\n\n<p>Note the format string: \" %d\"<br>\nThe leading space ignores multiple (including zero) white space characters proceeding your data (Note: White space includes '\\n' so it will correctly wrap past the end of line). Then the %d will read a number from the stream. If it succeeds then it will return 1 to indicate the number of decoded '%' objects is 1.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-18T08:24:49.130", "Id": "10118", "ParentId": "10103", "Score": "2" } }, { "body": "<p><em>Please note some of the following comments might overlapp with previous posts.</em></p>\n\n<ul>\n<li><p><code>allocated</code> and <code>elementCount</code> should be unsigned type. <code>length</code> should be checked for errors - assuming that's the reason for it to be signed.</p></li>\n<li><p><code>written</code> should be size_t and is unused. It should also be checked in case file size changed.</p></li>\n<li><p>malloc return value should be checked. If allocation failed, <code>buffer</code> should neither be used nor freed.</p></li>\n<li><p>realloc does not necessarily reallocate in place. Returned pointer shoud be error checked and used if allocation succeeded</p></li>\n<li><p>if the file does not contain a terminating null character, strtok will process past the allocated buffer.</p></li>\n<li><p>if the file size is 0, the last realloc will free <code>userInput</code> and return null. <code>getUserInput()</code> would then return a freed pointer.</p></li>\n<li><p>exception handling is missing on file access</p></li>\n<li><p>potential integer overflows</p>\n\n<ul>\n<li><code>allocated *= 2</code></li>\n<li><code>realloc(userInput, allocated * sizeof(int));</code> </li>\n<li><code>userInput[(*elementCount)++] = atoi(tokenized);</code></li>\n</ul></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-27T04:54:53.333", "Id": "12103", "ParentId": "10103", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-17T22:56:16.580", "Id": "10103", "Score": "1", "Tags": [ "c" ], "Title": "Reading tokenized numbers from a file" }
10103
<p>At the moments the requirements do not need me to change this code, however I think there is something wrong with it in the fact that it seems to know too much. The code takes a memory stream which is essentially a file and uploads this to a post URL supplying the necessary credentials. It may also need to pass other form value fields which is available in the <code>NameValuecollection</code> parameter.</p> <p>For me it seems this class breaks a number of different SOLID principles so I'm looking for ways to make it better from this point of view.</p> <p>Some things I'm not so sure about and how to possibly make better are:</p> <ol> <li><p>Having it not accept credentials and be responsible for adding this to the HttpWebRequest. What happened if I wanted to change the way the credentials were used. The class would need to change for this.</p></li> <li><p>The class is responsible for building up the posted stream and also sending it. Was thinking that the sending shouldn't be a part of this process.</p></li> <li><p>What happens if I want to send multiple files. At the moment the code does not support that but I'm sure there's a way I could make it generic enough to support multiple file upload.</p></li> </ol> <p>Some things I am considering is:</p> <ol> <li><p>Passing in a wrapper class for the upload memory stream that would contain it's Stream, FileName and Content-Type. Maybe something like List.</p></li> <li><p>Having another class be responsible for the sending of the data stream, so renaming the Upload to something like GetUploadStream().</p></li> <li><p>An interface perhaps for doing the credentials, or maybe inject that into another class that is the one doing the actual upload?</p></li> </ol> <p>I don't want to make this more complex than it needs to be however to me at the moment it just feels too rigid.</p> <p>Onwards and upwards, here's the code:</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Collections.Specialized; using System.Net; using System.Globalization; namespace CDAX.Schema.Zip { public class HttpZipUpload { private ICredentials _credentials; private readonly string _boundary = ""; public HttpZipUpload(ICredentials credentials) { _boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x", NumberFormatInfo.InvariantInfo); _credentials = credentials; } public byte[] Upload(string url, MemoryStream dataStream) { return Upload(url, dataStream, new NameValueCollection()); } public byte[] Upload(string url, MemoryStream dataStream, NameValueCollection nameValues) { HttpWebRequest request = GetHttpWebRequest(url); WriteAuthenticationToRequest(request); dataStream.Position = 0; using (MemoryStream outputStream = new MemoryStream()) { WriteNameValuesToStream(outputStream, nameValues); WriteDataContentToStream(outputStream, dataStream); WriteToHttpStream(request, outputStream); } // return the response return GetHttpWebResponse(request); } private byte[] GetHttpWebResponse(HttpWebRequest request) { using (var response = request.GetResponse()) { using (var responseStream = response.GetResponseStream()) { using (var stream = new MemoryStream()) { responseStream.CopyTo(stream); return stream.ToArray(); } } } } private HttpWebRequest GetHttpWebRequest(string url) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.ContentType = string.Format("multipart/form-data; boundary={0}", _boundary); request.Method = "POST"; return request; } private void WriteAuthenticationToRequest(HttpWebRequest request) { var user = _credentials.GetCredential(request.RequestUri,"Basic"); string auth = string.Format("{0}:{1}", user.UserName, user.Password); request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(auth))); } private void WriteEndBoundaryToStream(MemoryStream stream) { WriteBoundaryToStream(stream, "--"); } private void WriteBoundaryToStream(MemoryStream stream, string endDeliminator) { WriteToStream(stream, Encoding.ASCII, string.Format("--{0}{1}", _boundary, endDeliminator)); } private void WriteDataContentToStream(MemoryStream outputStream, MemoryStream inputStream) { // write content boundary start WriteBoundaryToStream(outputStream, Environment.NewLine); string formName = "uploaded"; string fileName = "input.zip"; string contentType = "application/zip"; WriteToStream(outputStream, System.Text.Encoding.UTF8, string.Format("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"{2}", formName, fileName, Environment.NewLine)); WriteToStream(outputStream, System.Text.Encoding.UTF8, string.Format("Content-Type: {0}{1}{1}", contentType, Environment.NewLine)); byte[] buffer = new byte[inputStream.Length]; int bytesRead = 0; while ((bytesRead = inputStream.Read(buffer, 0, buffer.Length)) != 0) { outputStream.Write(buffer, 0, bytesRead); } // must include a new line before writing the end boundary WriteToStream(outputStream, Encoding.ASCII, Environment.NewLine); // make sure we end boundary now as the content is finished WriteEndBoundaryToStream(outputStream); } private void WriteNameValuesToStream(MemoryStream stream, NameValueCollection nameValues) { foreach (string name in nameValues.Keys) { WriteBoundaryToStream(stream, Environment.NewLine); WriteToStream(stream, Encoding.UTF8, string.Format("Content-Disposition: form-data; name=\"{0}\"{1}{1}", name, Environment.NewLine)); WriteToStream(stream, Encoding.UTF8, nameValues[name] + Environment.NewLine); } } private void WriteToHttpStream(HttpWebRequest request, MemoryStream outputStream) { outputStream.Position = 0; byte[] tempBuffer = new byte[outputStream.Length]; outputStream.Read(tempBuffer, 0, tempBuffer.Length); request.ContentLength = outputStream.Length; using (Stream requestStream = request.GetRequestStream()) { requestStream.Write(tempBuffer, 0, tempBuffer.Length); requestStream.Close(); } } private void WriteToStream(MemoryStream stream, Encoding encoding, string output) { byte[] headerbytes = encoding.GetBytes(output); stream.Write(headerbytes, 0, headerbytes.Length); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-18T17:08:38.597", "Id": "16140", "Score": "1", "body": "Quick small notes: See the answer to: http://stackoverflow.com/questions/2845055/getting-rid-of-nested-using-statements\nAlso in the `WriteToHttpStream`, your `using` body is too large. It only needs to wrap around a single line: `requestStream.Write`. You do not really need to explicitly `requestStream.Close`. However, `outputStream` could misbehave as well, but I suppose it is up to the caller to clean up that mess. Thirdly, run StyleCop on this, and finally - your class is relatively small. I would only start to change it if you really ARE GOING TO NEED IT. I trust you can refactor it later." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-18T20:13:09.727", "Id": "16142", "Score": "0", "body": "@Leonid Thanks for tips.I've changed the WriteToHttpStream() to your suggestion. I know I could refactor later but just looking for some code review on it now while it's fresh in my mind" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-19T20:29:55.050", "Id": "16169", "Score": "0", "body": "So I ran StyleCop over this code but didn't really come up with too much based on the configuration options I have. Good little tool though." } ]
[ { "body": "<p>The code looks ok, but indeed there are too many responsibilities in a single class, hence SRP is violated.</p>\n\n<p>For instance, you could use a decorator to add the credentials, instead of having them injected in the constructor. But this leads to <strong>your own model</strong> of HTTP request: the headers, the body, everything. Once you have the model, you can play around with it as much as you want, set everything (credentials, boundary, etc.) and eventually invoke the relevant method, which, in turn, translates your model to the .NET's HTTP request.</p>\n\n<p>So... constructing a HTTP request the SOLID way, using OOP and design patterns is not that trivial. I'd suggest you take a look at <a href=\"http://restsharp.org/\" rel=\"nofollow\">RestSharp</a>, which aims for <a href=\"http://tomayko.com/writings/rest-to-my-wife\" rel=\"nofollow\">REST</a>, but is a very versatile HTTP client in itself.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T08:01:39.183", "Id": "14887", "ParentId": "10112", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-18T03:15:27.293", "Id": "10112", "Score": "1", "Tags": [ "c#" ], "Title": "Separate responsibilities out of this class that uploads data to a post URL" }
10112
<p>How can I optimize checking a value in recursion before operating on it? I'm using <code>Array.indexOf</code> (this is Javascript)</p> <pre><code>var nums = [], lengths = []; function findNumLength(n) { //preliminary check to see if //we've done this number before var indexOf = nums.indexOf(n); if(indexOf !== -1) { return lengths[indexOf]; } function even (n2) { return n2%2===0; } if(n===1) { return 1; } if(even(n)) { l = findNumLength(n/2) + 1; if(indexOf===-1) { lengths.splice(0,0 ,l); nums.push(n); } return l; } else { l = findNumLength(3*n + 1) + 1; if(indexOf===-1){ lengths.splice(0,0,l); nums.push(n); } return l; } } </code></pre> <p>(note: I've answered my own question with one solution I've found; it is by no means the only solution (though it may be the best. I don't know). Please, still answer.)</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-18T03:55:25.563", "Id": "16115", "Score": "0", "body": "Can you include more complete code? What you have so far isn't making sense to me. You check to see if the number is in the array and if it's not, you `return 1`. If it is in the array, you add it again. Are you sure that's the logic you meant?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-18T04:01:08.500", "Id": "16116", "Score": "0", "body": "@jfriend00 the code was just a mockup; the idea is that I'm passing a number to a function and, as long as I haven't performed on that number yet, I keep going. Once I hit a number I have done before, I stop. You can see an example [here](https://gist.github.com/2067757) on lines 5-8" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-18T04:02:50.633", "Id": "16117", "Score": "0", "body": "@jfriend00 oh, my bad. Just realized I had `=== -1` instead of `!==`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-18T04:39:09.727", "Id": "16123", "Score": "0", "body": "On Code Review we expect real code, not mockups. I'd suggest posting that entire piece of code you link as a request for review. That would be more appropriate for this site." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-18T04:41:48.620", "Id": "16124", "Score": "0", "body": "@WinstonEwert i've edited in the real code; does it look okay or should I add some clarification to the question as well?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-18T05:37:38.777", "Id": "16125", "Score": "0", "body": "For completeness sake I'd probably include a link to the wikipedia page on the Collatz conjecture. But its good as is." } ]
[ { "body": "<p><code>Array.indexOf</code> loops through the entire array, which hurts speed, especially when the array gets big and the recursion enters several levels. One way to optimize would be to do:</p>\n\n<pre><code>//set up the array as normal\nvar numbers = []; \nfunction recurse(number) {\n //if numbers doesn't have an element\n //mapped to number yet, create it:\n if(!numbers[number]) numbers[number] = false; \n if(numbers[number])\n {\n return number;\n }\n //do stuff to number\n numbers[number] = true;\n recurse[modified_number];\n}\n</code></pre>\n\n<p>Also, instead of setting <code>numbers[number]</code> to false, you could set it to some useful value to help keep track.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-18T03:23:45.940", "Id": "10114", "ParentId": "10113", "Score": "0" } }, { "body": "<p>The faster way to know if a number is already in a data structure is to use an object, not an array. So, if you don't have to have the numbers in an array, then this would be a lot faster, particular when the number of items gets big because the object look up is massively faster than the linear search of <code>.indexOf()</code>:</p>\n\n<pre><code>var numbers = {};\nfunction recurse(newNumber) {\n if(newNumber in numbers) {\n return newNumber;\n }\n //do stuff to number\n numbers[newNumber] = true;\n return recurse(modified_number);\n}\n</code></pre>\n\n<p>You can then iterate through the items in <code>numbers</code> like this:</p>\n\n<pre><code>for (var num in numbers) {\n if (numbers.hasOwnProperty(num) {\n // process num here\n }\n}\n</code></pre>\n\n<p>FYI, if speed is really your goal here, recursion is not the fastest way to do this (because functions calls are kind of slow in javascript), particularly if you don't have much or any local state in the function so you could just use a <code>while</code> loop of sorts.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-18T04:25:55.690", "Id": "16118", "Score": "0", "body": "thanks! this is really interesting; do you have a link to anything on object lookup vs. linear array search? (I suppose I could always find _something_ via Google, but I prefer something someone else already read/found helpful)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-18T04:29:37.283", "Id": "16119", "Score": "1", "body": "@ThomasShields - see this jsperf: http://jsperf.com/object-index-vs-array-search that I just found with Google. The object is always faster, even if the matched array element is in the first slot of the array and this is with only 10 items in the array/object - it goes even more in favor of the object the more items there are. If you understand how an object property lookup works (via a hashtable), you would see why it's so much faster than a linear search of the array. The differences are most pronounced when the object is not in the array at all or is near the end of the array." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-18T04:34:17.583", "Id": "16120", "Score": "0", "body": "awesome; thanks. I particularly like this because it retains the logic of \"have we done x yet?\" much better than my answer did." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-18T04:34:44.797", "Id": "16121", "Score": "0", "body": "@ThomasShields - FYI, that jsperf shows the object access to be almost 10x faster for every case except the one where the object you're looking for happens to be in the first array element and then it's only a little faster. But, since that would rarely happen in the real world, the object is a lot faster on average." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-18T04:38:00.027", "Id": "16122", "Score": "0", "body": "yeah, especially since speed is only going to matter when the array gets > 10K els in size, and the event of the object being first only happens out of ~10K times." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-18T04:23:36.557", "Id": "10115", "ParentId": "10113", "Score": "2" } }, { "body": "<pre><code>var nums = [], lengths = [];\nfunction findNumLength(n) {\n</code></pre>\n\n<p>This function name would do better to actually mention collatz.</p>\n\n<pre><code> //preliminary check to see if \n //we've done this number before\n var indexOf = nums.indexOf(n);\n if(indexOf !== -1) {\n return lengths[indexOf];\n }\n</code></pre>\n\n<p><code>indexOf</code> is going to search through the entire list to find the correct number. That's going to be slow. Instead, I'd suggest that you use an array large enough each number <code>n</code> could be an index into it. Leave the default <code>undefined</code> for any entries you haven't calculated yet.</p>\n\n<pre><code> function even (n2) { return n2%2===0; }\n</code></pre>\n\n<p>Functions are going to be somewhat expensive, and you only use this one once. It might be better just to stick this in the if.</p>\n\n<pre><code> if(n===1) {\n return 1;\n }\n if(even(n)) {\n</code></pre>\n\n<p>I'd make this <code>else if</code>, just to be more explicit</p>\n\n<pre><code> l = findNumLength(n/2) + 1;\n if(indexOf===-1) { \n</code></pre>\n\n<p>If this wasn't true, we'd have returned above. So why are you testing it here?</p>\n\n<pre><code> lengths.splice(0,0 ,l);\n nums.push(n);\n</code></pre>\n\n<p>I'm not really following what you are doing here. Shouldn't you be <code>push</code>ing on both arrays?</p>\n\n<pre><code> }\n return l;\n }\n else {\n l = findNumLength(3*n + 1) + 1;\n if(indexOf===-1){\n lengths.splice(0,0,l);\n nums.push(n);\n }\n return l;\n }\n</code></pre>\n\n<p>There's a lot of common logic between both sides of the if. Most of it should be move after if and run in either case.</p>\n\n<pre><code>}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-18T13:01:07.157", "Id": "16130", "Score": "0", "body": "Thanks, great answer! I've already incorporated some of the ideas in my final version, but this is great. The reason I did `lengths.splice(0,0,1);` was that the recursion meant that lengths got added in backwards, so they didn't match up to their numbers in the `nums` array." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-18T15:34:56.757", "Id": "16137", "Score": "0", "body": "@ThomasShields, ok by why doesn't the same logic apply to nums?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-18T16:52:17.260", "Id": "16139", "Score": "0", "body": "you know what, you're right. What happened was that originally I was pushing to `nums`, then recursing, then adding to `lengths` - hence the splice, since the recursion happened first. Eventually I rewrote it to push to both arrays. Apparently I posted a sort of hybrid between the two versions. Either way, you're right: thanks for catching that." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-18T05:47:08.563", "Id": "10116", "ParentId": "10113", "Score": "1" } } ]
{ "AcceptedAnswerId": "10116", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-18T03:21:40.280", "Id": "10113", "Score": "1", "Tags": [ "javascript", "optimization", "array" ], "Title": "Optimize Array.indexOf" }
10113
<p>For anyone familiar with the UVa Programming Challenges website, I have started experimenting with some of the basic challenges. I was hoping to get critique for the code I wrote for <a href="http://uva.onlinejudge.org/index.php?option=com_onlinejudge&amp;Itemid=8&amp;category=3&amp;page=show_problem&amp;problem=36" rel="nofollow">"The 3n+1 Problem" (Problem ID 100)</a>.</p> <p>The run-time for this submission was 0.040 and my best submission was only 0.036. Looking at the scoreboard I have seen that many people have attained 0.000 runtime scores. I would really like some feedback for any/all of the following:</p> <ul> <li>My choice of "algorithm"</li> <li>C++ Implementation [code (re-)structure]</li> <li>How did others attain the amazing runtime scores? Math trick(s) ? </li> </ul> <p>To help with code readability: My code calculates the length of a sequence with <code>compute()</code> and stores the result in a table (vector of sequence lengths which is indexed by the value).</p> <p>Along the way, any intermediate values encountered are saved on a temporary 'stack', and when the final result is computed, all the values in the list are also entered into the table. For example, for <code>compute(8)</code> the sequence becomes <code>8 4 2 1</code>. </p> <p>So, <code>table[8] = 4; table[4] = 3; table[2] = 2;</code> At the beginning of <code>compute()</code>, any nonzero value in the table causes it to return the length immediately.</p> <p>Besides reducing table size, and using a loop/goto instead of recursion, I can't think of a way to improve my current approach. For curious readers, before I implemented the intermediate value stack, my best run-time of 0.036 was from using this table approach but 'seeding' the table with values 1 to 200 before accepting user input, a la <code>start(1,200)</code>.</p> <p>Thanks!</p> <pre><code>/// The 3n+1 Problem // Consider the following algorithm to generate a sequence of // numbers. Start with an integer n. If n is even, divide by 2. If n // is odd, multiply by 3 and add 1. Repeat this process with the new // value of n, terminating when n = 1. For example, the following // sequence of numbers will be generated for n = 22: // // 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1 // // It is conjectured (but not yet proven) that this algorithm will // terminate at n = 1 for every integer n. Still, the conjecture holds // for all integers up to at least 1, 000, 000. For an input n, the // cycle-length of n is the number of numbers generated up to and // including the 1. In the example above, the cycle length of 22 is // 16. Given any two numbers i and j, you are to determine the maximum // cycle length over all numbers between i and j, including both // endpoints. // // Input // // The input will consist of a series of pairs of integers i and j, // one pair of integers per line. All integers will be less than // 1,000,000 and greater than 0. // // Output // // For each pair of input integers i and j, output i, j in the same // order in which they appeared in the input and then the maximum // cycle length for integers between and including i and j. These // three numbers should be separated by one space, with all three // numbers on one line and with one line of output for each line of // input. #include &lt;iostream&gt; #include &lt;vector&gt; template&lt;typename T = int&gt; class BlackBox { public: BlackBox(T maxsize) : tablesize_(maxsize) { table_ = std::vector&lt;T&gt;(maxsize, 0); // Seed the table for values 0 and 1 // Note: 0 treated as odd=&gt; 0: 3*(0) + 1 =&gt; 1 // Sequence 0 1 =&gt; length = 2 table_[0] = 2; table_[1] = 1; } ~BlackBox() { } void print() { std::cout &lt;&lt; current_ &lt;&lt; " "; } void printn() { std::cout &lt;&lt; "\n"; } // compute the length of the sequence started from 'current' if not // found in the table, we will compute the sequence storing each // value on a 'stack' so we can update it along with the final value // sequence S=&gt; // compute(S[0]) =&gt; length(S) // compute(S[1]) =&gt; length(S) - 1 // ... // compute(S[n-1]) =&gt; 1 std::size_t compute(T current) { std::size_t count = 0; if (current &lt; tablesize_ &amp;&amp; table_[current]) { //std::cout &lt;&lt; "=&gt; " &lt;&lt; current &lt;&lt; " "; return table_[current]; } // Not in table, increment operation count and // perform at least one operation stack_.push_back(current); count++; //std::cout &lt;&lt; current &lt;&lt; " "; // Detect odd (1s bit) if ((current &amp; 0x01)) { // odd // 3n+1 current = 3 * current + 1; //std::cout &lt;&lt; current &lt;&lt; " "; // After performing an expensive 3n+1 operation // the number will always be even, so increase // count and perform divide by two operation stack_.push_back(current); count++; } // even // divide by two current = current &gt;&gt; 1; return ( count + compute(current) ); } // if compute() put anything on the stack, we will update the table // containing the sequence lengths // compute(index]) = table[index] void update_table() { T thecount = count_; typename std::vector&lt;T&gt;::iterator it = stack_.begin(); typename std::vector&lt;T&gt;::iterator it_end = stack_.end(); for ( ; it != it_end; it++) { T index = *it; if (index &lt; tablesize_) table_[index] = thecount; thecount--; } } // find the longest sequence over the range [start, end] void start(T start, T end) { T index; maxcount_ = 0; if (end &lt; start) { std::swap(start, end); } for (index = start; index &lt;= end; index++) { current_ = index; count_ = 1; stack_.clear(); count_ = compute(index); if (!stack_.empty()) update_table(); if (count_ &gt; maxcount_) maxcount_ = count_; } } std::size_t max() { return maxcount_; } protected: private: std::vector&lt;T&gt; table_; std::vector&lt;T&gt; stack_; std::size_t tablesize_; T input_; T current_; std::size_t count_; std::size_t maxcount_; }; // usage: ./100 // // on each line enter a range, n m // where 0 &lt;= n,m &lt;= tablesize // the output will be // n m MAXSEQLENGTH int main(int argc, char *argv[]) { // Table size for tracking (FULL SIZE) long long const tablesize = 1000000; // TODO: // Could consider splitting the table in half since // for even_num/2 =&gt; odd num // the sequence length is given by: // table[even_num] = table[even_num/2] + 1 // Potentially good idea? BlackBox&lt;long long&gt; box(tablesize); long long start; long long end; while (std::cin &gt;&gt; start &gt;&gt; end) { box.start(start, end); std::cout &lt;&lt; start &lt;&lt; " " &lt;&lt; end &lt;&lt; " " &lt;&lt; box.max() &lt;&lt; "\n"; } return 0; } </code></pre>
[]
[ { "body": "<p>This is overly confusing, and things are obscurely named. This is a one-off for a programming contest thingy, so it doesn't seem like it's that important. But I find that organizing my code well helps me think. You might find that's true of you.</p>\n\n<p>Also, you have several fixed sized tables that are very huge. Quite likely unnecessarily so as the short cycle lengths for large numbers indicate that most sequences converge rather rapidly on a common chain. Lastly, you keep a stack of values when no such stack is necessary because the problem description doesn't require you to print out what the chains are. And even if it did, a very slight tweak to the table contents would allow you to easily print out the chains by just following pointers with no stack necessary.</p>\n\n<p>There are other details that seem minor but are actually a big deal. For example, you create an empty vector, then assign it a very large table. This will create two copies of the very large table, and throw away the (rather minimal admittedly) work done to create the empty vector. Since this last is a very specific coding flaw, here's how it would be fixed:</p>\n\n<pre><code> BlackBox(T maxsize) : table_(maxsize, 0), tablsize_(maxsize)\n {\n // Seed the table for values 0 and 1\n // Note: 0 treated as odd=&gt; 0: 3*(0) + 1 =&gt; 1\n // Sequence 0 1 =&gt; length = 2\n table_[0] = 2;\n table_[1] = 1;\n }\n</code></pre>\n\n<p>Lastly, your organization is very confused. You make one class responsible for too many things. There is no need for one class to both handle finding the max value in a range and to compute the cycle lengths.</p>\n\n<p>But, while these issues are important, I can't see that fixing them is going to shave more than about 20% off your time. :-/</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-20T06:41:27.430", "Id": "16181", "Score": "0", "body": "Thanks for your comments; I've reorganized my class to perform only cycle length computation and eliminated the erroneous copy of a large vector. This alone shaved a small amount of time off - to 0.024" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-20T06:49:49.880", "Id": "16182", "Score": "0", "body": "You understand why I use the stack though, right? When length computation finishes, every intermediate 'element' in the chain will be added to the table - not just the value we were hunting for. If I don't maintain that stack of intermediate elements of the 'chain' then i run the risk of performing the same subchain computation twice. Could you explain your comment in more detail about tweaking table contents?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-20T15:44:49.423", "Id": "16193", "Score": "0", "body": "@assem: Now I see. You use it to do something you could do with recursion. Are you sure that's more efficient than recursion? Recursion has a bad rap with regards to efficiency." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-21T06:48:33.203", "Id": "16228", "Score": "0", "body": "@assem - There is a cheater way to do part of it. `__builtin_ctz` can count the number of trailing 0 bits in one instruction. This enables you to shift them all out (dividing by a power of 2) in another. And if you analyze the graph carefully, there are a small number of choke points that a significant number of paths pass through." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-28T07:05:37.270", "Id": "16561", "Score": "0", "body": "Thanks for the tips; I can't seem to get it below 0.020, but I am happy with the current solution. I'll edit my original post to show before and after code! :)" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-18T17:17:17.603", "Id": "10127", "ParentId": "10120", "Score": "1" } } ]
{ "AcceptedAnswerId": "10127", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-18T10:35:45.923", "Id": "10120", "Score": "3", "Tags": [ "c++", "algorithm" ], "Title": "UVa Challenge Problem: 3n+1" }
10120
<p>Inspired by <a href="https://stackoverflow.com/questions/9742725/solving-google-code-jams-minimum-scalar-product-in-haskell">a Stack Overflow question</a>, I decided to practice my Haskell by taking a crack at the <a href="http://code.google.com/codejam/contest/32016/dashboard" rel="nofollow noreferrer">Google Code Jam's Minimum Scalar Product problem</a>:</p> <blockquote> <p>Given two vectors \$\mathbf{v_1}=(x_1,x_2,\ldots,x_n)\$ and \$\mathbf{v_2}=(y_1,y_2,\ldots,y_n)\$. If you could permute the coordinates of each vector, what is the minimum scalar product \$\mathbf{v_1} \cdot \mathbf{v_2}\$?</p> <p>Constraints:<br> \$100 \le n \le 800\$<br> \$-100000 \le x_i, y_i \le 100000\$</p> </blockquote> <p>I'm not claiming any algorithmic awesomeness (this is just a reference implementation for checking correctness later).</p> <p>This is my first time using <code>Vector</code>s and the <code>ST</code> monad, so what I really want is a sanity check that I'm using both correctly, and that I'm using the correct tools for the job.</p> <pre><code>module MinimumScalarProduct where import Control.Monad (replicateM, forM_, (&gt;=&gt;)) import Control.Monad.ST (runST, ST) import Data.Vector (thaw, fromList, MVector, Vector, zipWith, foldl', length, (!)) import Data.Vector.Generic.Mutable (read, swap) import Prelude hiding (read, zipWith, length) -- sequnce of transpoitions to yield all permutations of n elts -- http://en.wikipedia.org/wiki/Steinhaus-Johnson-Trotter_algorithm transpositions :: Int -&gt; [(Int, Int)] transpositions n = runST $ do -- p maps index to element p &lt;- thaw $ fromList [0 .. n-1] -- q maps element to index q &lt;- thaw $ fromList [0 .. n-1] -- let the prefixes define themselves recursively foldr ((&gt;=&gt;) . extend p q) return [2..n] [] extend :: MVector s Int -&gt; MVector s Int -&gt; Int -&gt; [(Int,Int)] -&gt; ST s [(Int,Int)] extend p q n ts = fmap ((ts++) . concat) . replicateM (n-1) $ do -- replace the element in the (n-1)'th position with its predecessor a &lt;- read p (n-1) i &lt;- read q (a-1) swap p (n-1) i swap q a (a-1) -- replay the earlier transpositions forM_ ts $ \(m,j) -&gt; do b &lt;- read p m c &lt;- read p j swap p m j swap q b c return $ (n-1,i) : ts -- reference implementation, takes O(n!) msp :: Vector Int -&gt; Vector Int -&gt; Int msp u v | length u /= length v = 0 msp u v = runST $ do let x = foldl' (+) 0 $ zipWith (*) u v let n = length u u' &lt;- thaw u -- check each permutation of u' let steps = map (adjust u' v) $ transpositions n fmap minimum . sequence $ scanl (&gt;&gt;=) (return x) steps -- adjust the current scalar product for the transposition of u adjust :: MVector s Int -&gt; Vector Int -&gt; (Int, Int) -&gt; Int -&gt; ST s Int adjust u v (i,j) x = do a &lt;- read u i b &lt;- read u j let c = v ! i let d = v ! j swap u i j return $ x - (a*c + b*d) + (a*d + b*c) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-02-21T14:26:42.323", "Id": "147825", "Score": "5", "body": "You do know that this problem can be solved by just sorting the vectors? Why do it in such a complicated way when it's just a reference implementation, what's wrong with Data.List.permutations?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-02-21T15:30:44.440", "Id": "147835", "Score": "1", "body": "Hjulle: it's been three years, but I think I was trying to minimize the work to compute the product for all the permutations by walking through them in transposition order. So it's O(1) work per vector product, rather than O(n), making the total algorithm O(n!) rather than O(n*n!). In retrospect, perhaps not a great savings." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-28T12:13:17.347", "Id": "173203", "Score": "2", "body": "@Hjulle For such a public challenge I'd suggest to update your comment not to disclose the solution as it ruins the challenge for others as well as for the OP. It'd be better to review the OP's code wrt to the idea (s)he's expressing, perhaps just mentioning something like \"Note that there is a much more asymptotically efficient algorithm\" and give the OP (and others) a chance to find it on their own." } ]
[ { "body": "<p>Somewhat old question, but still it's a pity it hasn't been answered :). Putting aside the asymptotically better solution suggested in the comments, and focusing just on the code:</p>\n\n<p>Pluses: Top-level types for all funtcions, that's very good, as well as comments. The code shows good understanding of various Haskell functions and idioms.</p>\n\n<p>My most general comment is that there is disproportion between code verbosity and complexity. Usually more complex code should be more verbose and more descriptive. Visually, most of the code is just simple read/write/swap ST operations, but the important part is squeezed into not-so-easy-to-understand and uncommon combinations of folds/scans/sequence/>=>/>>= etc. I'd probably separate the simple parts (read/swap) into helper functions and expand/simplify the complex parts a bit.</p>\n\n<p>Function <code>adjust</code> somewhat mixes pure and mutable approaches. While it mutates its first argument, it keeps the scalar product pure and passes it as an argument in and out. This is somewhat confusing and complicates the computation of the minimum (<code>scanl</code> with <code>&gt;&gt;=</code>). If the product were a ST variable too, the code gets simpler (untested):</p>\n\n<pre><code>adjust :: MVector s Int -&gt; Vector Int -&gt; STRef s Int -&gt; (Int, Int) -&gt; ST s Int\n...\nmsp = ...\n x &lt;- newSTRef $ foldl' (+) 0 $ zipWith (*) u v\n fmap minimum . traverse (adjust u' v x) . transpositions $ n\n</code></pre>\n\n<p>Alternatively you could even keep the result in an ST variable.</p>\n\n<p>Also <code>foldr</code> with <code>&gt;=&gt;</code> can be replaced with <code>foldM</code> (untested):</p>\n\n<pre><code>foldM (flip $ extend p q) [] [2..n]\n</code></pre>\n\n<p>(Then it'd make sense to refactor the type of <code>extend</code> to get rid of the <code>flip</code>.)</p>\n\n<p>Some questions:</p>\n\n<ul>\n<li>Is replaying all <code>ts</code> in <code>extend</code> necessary? As it's executed repeatedly, it'd make sense to compute the combined permutation of <code>ts</code> separately or once and then just apply it.</li>\n<li>Which variant of the algorithm is actually used? Using two vectors doesn't seem to match anything in the linked Wikipedia article. While the general idea of the algorithm is clear, it'd be easier for someone not familiar with it to get more precise guidelines.</li>\n</ul>\n\n<p>Nit: The order of functions is somewhat unnatural: <code>transpositions</code> uses <code>extend</code>, <code>msp</code> uses <code>transpositions</code> and <code>adjust</code>. There is no visible order in this. One good option is that functions are always defined before being used (with the obvious exception of mutually-recursive functions). Or the other way around - the main/exported functions are first and helper functions follow. Or, separate functions into (possibly nested) <a href=\"https://www.haskell.org/haddock/doc/html/ch03s04.html\" rel=\"noreferrer\">sections</a>, then ordering of functions doesn't really matter, ordering of sections becomes important.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-07-15T20:01:17.607", "Id": "135024", "ParentId": "10123", "Score": "5" } } ]
{ "AcceptedAnswerId": "135024", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-18T12:06:23.123", "Id": "10123", "Score": "41", "Tags": [ "programming-challenge", "haskell", "combinatorics", "computational-geometry", "monads" ], "Title": "Finding minimum scalar product using ST Monad" }
10123
<p>Source XML (since I haven't bothered with a schema):</p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;ContactDetails&gt; &lt;Names&gt; &lt;FullName&gt; Nicholas Example &lt;/FullName&gt; &lt;AltName context="Nickname"&gt; Nick &lt;/AltName&gt; &lt;AltName context="Online"&gt; oxinabox &lt;/AltName&gt; &lt;/Names&gt; &lt;Phones&gt; &lt;Phone context="Mobile"&gt;04 1234 1234&lt;/Phone&gt; &lt;/Phones&gt; &lt;Addresses&gt; &lt;Address context="Semester"&gt; Contrived Apartments &lt;number&gt; 5 &lt;/number&gt; &lt;street&gt;Some Rd&lt;/street&gt; &lt;town&gt;Newtown&lt;/town&gt; &lt;state&gt;ST&lt;/state&gt; &lt;/Address&gt; &lt;/Addresses&gt; &lt;Emails&gt; &lt;Email context="Work"&gt;examplen@work.com&lt;/Email&gt; &lt;Email context="Personal"&gt;nick99@ManMail.com&lt;/Email&gt; &lt;/Emails&gt; &lt;Websites&gt; &lt;Website&gt;http://www.a2b3c4.com&lt;/Website&gt; &lt;/Websites&gt; &lt;Banking&gt; &lt;BankAccount context="Everyday" Name="Nicholas Example" BSB="123 123" AccountNumber="111 222 333" /&gt; &lt;/Banking&gt; &lt;/ContactDetails&gt; </code></pre> <p>and here is the actual XSLT I would like a review of. It is supposed to turn the XML in to a human readable flat file (and does except for addresses which I am still working on):</p> <pre><code>&lt;?xml version="1.0" ?&gt; &lt;xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fn="http://www.w3.org/2005/xpath-functions" &gt; &lt;xsl:output method="text" omit-xml-declaration="yes" indent="no" media-type="text/plain"/&gt; &lt;xsl:strip-space elements="*"/&gt; &lt;xsl:template match="ContactDetails"&gt; &lt;xsl:apply-templates/&gt; &lt;/xsl:template&gt; &lt;xsl:template match="Names"&gt; &lt;xsl:value-of select="FullName"/&gt; &lt;xsl:for-each select="AltName"&gt; &lt;xsl:text&gt; AKA &lt;/xsl:text&gt;&lt;xsl:value-of select="normalize-space(.)"/&gt; &lt;/xsl:for-each&gt; &lt;xsl:text&gt; &lt;/xsl:text&gt; &lt;/xsl:template&gt; &lt;xsl:template match="//Phone"&gt; &lt;xsl:text&gt; Ph (&lt;/xsl:text&gt;&lt;xsl:value-of select="@context"/&gt; &lt;xsl:text&gt;): &lt;/xsl:text&gt; &lt;xsl:value-of select = "."/&gt; &lt;/xsl:template&gt; &lt;xsl:template match="//Email"&gt; &lt;xsl:text&gt; Email (&lt;/xsl:text&gt;&lt;xsl:value-of select="@context"/&gt; &lt;xsl:text&gt;): &lt;/xsl:text&gt; &lt;xsl:value-of select = "."/&gt; &lt;/xsl:template&gt; &lt;xsl:template match="//Website"&gt; &lt;xsl:text&gt; Website: &lt;/xsl:text&gt; &lt;xsl:value-of select = "."/&gt; &lt;/xsl:template&gt; &lt;xsl:template match="//Address"&gt; &lt;!-- &lt;xsl:value-of select ="."/&gt; &lt;xsl:for-each select="*"&gt; &lt;xsl:value-of select = "."/&gt; &lt;xsl:if test="fn:name(.)=town"&gt; &lt;xsl:text&gt;, &lt;/xsl:text&gt; &lt;/xsl:if&gt; &lt;/xsl:for-each&gt; --&gt; &lt;/xsl:template&gt; &lt;xsl:template match="Banking"&gt; &lt;xsl:text&gt; Bank Details: ------------ &lt;/xsl:text&gt; &lt;xsl:for-each select="BankAccount"&gt; &lt;xsl:value-of select="@context"/&gt; &lt;xsl:text&gt; Account: &lt;/xsl:text&gt; &lt;xsl:value-of select="@BSB"/&gt;-&lt;xsl:value-of select="@AccountNumber"/&gt; &lt;/xsl:for-each&gt; &lt;/xsl:template&gt; &lt;/xsl:stylesheet&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-18T15:45:09.077", "Id": "16138", "Score": "2", "body": "I tend to like email addresses in `First Last <name@place.domain>` format. It lets me easily select just the name. And if I select the whole thing their name shows up in the outgoing email and my mail software will remember them by their name." } ]
[ { "body": "<pre><code>&lt;xsl:output\n method=\"text\"\n omit-xml-declaration=\"yes\"\n indent=\"no\"\n media-type=\"text/plain\"/&gt; \n</code></pre>\n\n<p>Consider using XSLT 2.0, which can't hurt but could help if you need a XSLT 2.0 function in the future. Also note that you don't need <code>omit-output-declaration</code> since you're outputing text. Ditto for <code>indent</code>.</p>\n\n<pre><code>&lt;xsl:template match=\"ContactDetails\"&gt;\n &lt;xsl:apply-templates/&gt;\n&lt;/xsl:template&gt;\n</code></pre>\n\n<p>This is the default template for every element, which means it's not needed.</p>\n\n<pre><code>&lt;xsl:template match=\"//Email\"&gt;\n</code></pre>\n\n<p>Why the <code>//</code>? It makes more sense without it, eg. <code>match=\"Email\"</code>. This applies to all your templates.</p>\n\n<pre><code> &lt;xsl:text&gt;\nPh (&lt;/xsl:text&gt;&lt;xsl:value-of select=\"@context\"/&gt; &lt;xsl:text&gt;): &lt;/xsl:text&gt;\n &lt;xsl:value-of select = \".\"/&gt;\n</code></pre>\n\n<p>You're using <code>xsl:text</code> too much. This could become:</p>\n\n<pre><code>Ph (&lt;xsl:value-of select=\"@context\"/&gt;): &lt;xsl:value-of select = \".\"/&gt;\n</code></pre>\n\n<p>Besides, I'm not sure <code>context</code> is a good choice for an attribute name. \"Context node\" already has a specific meaning in <a href=\"http://www.w3.org/TR/xslt20/\" rel=\"nofollow\">XSLT</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-18T23:40:56.533", "Id": "16146", "Score": "0", "body": "When shound/shouldn't I use `xsl:text`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-19T07:19:12.000", "Id": "16153", "Score": "0", "body": "I personally only use it to introduce `\\n` to my output." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-19T11:51:20.273", "Id": "16157", "Score": "0", "body": "It seems ifiremoveany of the xsl:text tags I start seeing strange new lines next to every piece of text I put in" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-02-10T14:47:37.170", "Id": "145079", "Score": "0", "body": "XSLT 2.0 engines are is so incredibly rare. To my knowledge the only freeone is Saxon." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-18T21:33:53.623", "Id": "10132", "ParentId": "10125", "Score": "3" } }, { "body": "<p>you should really work on the indentation of your code, there is nothing worse than trying to read code that isn't properly indented.</p>\n\n<p><strong>Your indentation</strong></p>\n\n<pre><code>&lt;xsl:template match=\"Names\"&gt;\n&lt;xsl:value-of select=\"FullName\"/&gt;\n&lt;xsl:for-each select=\"AltName\"&gt; \n &lt;xsl:text&gt; AKA &lt;/xsl:text&gt;&lt;xsl:value-of select=\"normalize-space(.)\"/&gt;\n &lt;/xsl:for-each&gt;\n &lt;xsl:text&gt;\n &lt;/xsl:text&gt;\n&lt;/xsl:template&gt;\n</code></pre>\n\n<p><strong>What it should look like</strong></p>\n\n<pre><code>&lt;xsl:template match=\"Names\"&gt;\n &lt;xsl:value-of select=\"FullName\"/&gt;\n &lt;xsl:for-each select=\"AltName\"&gt; \n &lt;xsl:text&gt; AKA &lt;/xsl:text&gt;\n &lt;xsl:value-of select=\"normalize-space(.)\"/&gt;\n &lt;/xsl:for-each&gt;\n &lt;xsl:text&gt;\n &lt;/xsl:text&gt;\n&lt;/xsl:template&gt;\n</code></pre>\n\n<p><strong>Again, Yours</strong></p>\n\n<pre><code>&lt;xsl:template match=\"//Phone\"&gt;\n &lt;xsl:text&gt;\nPh (&lt;/xsl:text&gt;&lt;xsl:value-of select=\"@context\"/&gt; &lt;xsl:text&gt;): &lt;/xsl:text&gt;\n &lt;xsl:value-of select = \".\"/&gt;\n&lt;/xsl:template&gt; \n</code></pre>\n\n<p><strong>Proper</strong></p>\n\n<pre><code>&lt;xsl:template match=\"//Phone\"&gt;\n &lt;xsl:text&gt;Ph (&lt;/xsl:text&gt;\n &lt;xsl:value-of select=\"@context\"/&gt; \n &lt;xsl:text&gt;): &lt;/xsl:text&gt;\n &lt;xsl:value-of select = \".\"/&gt;\n&lt;/xsl:template&gt; \n</code></pre>\n\n<p>there is nothing worse than having to stop and think to see what is nested inside of what. some people have a different style of indenting but what you have posted looks very confusing.</p>\n\n<p>another proper way to write the Phone Template</p>\n\n<pre><code>&lt;xsl:template match=\"//Phone\"&gt;\n &lt;xsl:text&gt;\n Ph (\n &lt;/xsl:text&gt;\n &lt;xsl:value-of select=\"@context\"/&gt; \n &lt;xsl:text&gt;\n ): \n &lt;/xsl:text&gt;\n &lt;xsl:value-of select = \".\"/&gt;\n&lt;/xsl:template&gt; \n</code></pre>\n\n<p>I know this was nitpicky but it helps to keep your code organized in a similar manner to other people that will be reviewing your code, debugging your code, or adding to your code, so that they can understand what is going on quickly.</p>\n\n<p><em>(most of this you probably already know and just had a fun time trying to get your code to paste right into the Code Review Question box)</em></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T02:21:00.790", "Id": "57559", "Score": "0", "body": "Actually, my indenting is that way, because I have constant worries and issues with ensuring that my output in not indented/ line broken in the wrong place.\nEspecially since the output format is a flat file, and so I can not rely on xhtml to only acknowledged <br> and to remove an needed whitespace.\nIt may be my paranoia was for nothing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T05:22:07.570", "Id": "57570", "Score": "0", "body": "@Oxinabox, have you tried it this way? don't use the last example. I could see how that last example would add newlines in your flat file. but the other \"proper\" examples shouldn't do that. because the static text is inside of text tags" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T07:04:59.687", "Id": "57609", "Score": "0", "body": "I don't know this was over 18 months ago" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-16T06:01:48.200", "Id": "35472", "ParentId": "10125", "Score": "3" } } ]
{ "AcceptedAnswerId": "10132", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-18T14:44:17.970", "Id": "10125", "Score": "4", "Tags": [ "xml", "xslt" ], "Title": "Making a flat file" }
10125
<p>This is my first Clojure script (simple word translator based on Wikipedia), and I guess there are things which could be simplified / done more idiomatic way. Specifically, I wonder if <code>get-translations</code> couldn't be done better (it produces map lang code => term form regexp sequence).</p> <pre><code>(ns wiki-translate (:require [clojure.contrib.http.agent :as h]) (:require [clojure.contrib.string :as s]) (:import (java.net URLDecoder URLEncoder)) ) (defn url-decode ([text] (URLDecoder/decode text "UTF-8")) ) (defn url-encode ([text] (URLEncoder/encode text "UTF-8")) ) (defn get-url ([lg term] (str "http://" lg ".wikipedia.org/wiki/" (url-encode term))) ) (defn fetch-url ([url] (h/string (h/http-agent url))) ) (defn get-translations ([cnt] (apply sorted-map (flatten (for [s (re-seq #"interwiki-([^\"]+).*wiki\/([^\"]+)\".*/a&gt;" cnt)] [(s 1) (s 2)])))) ) (defn translate ([term src-lg tgt-lg] ( let [translations (get-translations (fetch-url (get-url src-lg term)))] (if (contains? translations tgt-lg) (s/replace-str "_" " " (url-decode (get translations tgt-lg))) "&lt;NOT FOUND&gt;"))) ) (defn prompt-read ([] (prompt-read "")) ([prompt] (print (format "%s: " prompt)) (flush ) (read-line)) ) (defn prompt-translate ([] (let [src-lg (prompt-read "Source language (en, fr, de ...)") tgt-lg (prompt-read "Target language (en, fr, de ...)") term (prompt-read "Term to translate")] (println (str "\"" term "\" translated from " src-lg " to " tgt-lg " : " (translate term src-lg tgt-lg))))) ) (while true (prompt-translate)) </code></pre>
[]
[ { "body": "<p>Don't use the multiple-arity syntax for <code>defn</code> unless you actually need to:</p>\n\n<pre><code>(defn url-decode\n [text]\n (URLDecoder/decode text \"UTF-8\"))\n</code></pre>\n\n<p>Your code could use some line breaks here and there. This is how clojure is usually indented:</p>\n\n<pre><code>(defn translate\n [term src-lg tgt-lg]\n (let [translations (get-translations (fetch-url (get-url src-lg term)))]\n (if (contains? translations tgt-lg)\n (s/replace-str \"_\" \" \" (url-decode (get translations tgt-lg)))\n \"&lt;NOT FOUND&gt;\")))\n</code></pre>\n\n<p>and:</p>\n\n<pre><code>(defn prompt-translate\n []\n (let [src-lg (prompt-read \"Source language (en, fr, de ...)\")\n tgt-lg (prompt-read \"Target language (en, fr, de ...)\")\n term (prompt-read \"Term to translate\")]\n (println (str \"\\\"\" term \"\\\" translated from \" src-lg \" to \" tgt-lg \" : \" (translate term src-lg tgt-lg)))))\n</code></pre>\n\n<p>Instead picking out the regexp groups by index, you should use destructuring:</p>\n\n<pre><code>(defn get-translations\n [cnt]\n (apply sorted-map\n (flatten\n (for [[_ a b] (re-seq #\"interwiki-([^\\\"]+).*wiki\\/([^\\\"]+)\\\".*/a&gt;\" cnt)]\n [a b]))))\n</code></pre>\n\n<p>... or better yet, I think, would be to do something like this:</p>\n\n<pre><code>(defn get-translations\n [cnt]\n (apply sorted-map\n (mapcat\n rest\n (re-seq #\"interwiki-([^\\\"]+).*wiki\\/([^\\\"]+)\\\".*/a&gt;\" cnt))))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-20T11:03:37.950", "Id": "10179", "ParentId": "10126", "Score": "7" } } ]
{ "AcceptedAnswerId": "10179", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-18T16:07:16.120", "Id": "10126", "Score": "3", "Tags": [ "clojure", "web-scraping", "wikipedia" ], "Title": "Simple word translator taking advantage of Wikipedia" }
10126
<p>After programming a lot in high level languages such as Python and R, I started working with C++ recently. To get my C++ skills up, I of course read a lot of books. In addition, I try and replicate some functionality from high level languages in C++. My first attempt at this (after Hello World :)) was to create a C++ class which could read comma separated files. In essence the class parses the file and reads it into a <code>boost::MultiArray</code>. I would appreciate any feedback on the code. </p> <p>The links to the code and example data are listed below, they link to my bitbucket account.</p> <p>The actual code comprises of a cpp file (<a href="https://bitbucket.org/paulhiemstra/cpp-small-projects/src/8a8cace7a37d/src/csv-test.cpp">csv-reader.cpp</a>):</p> <pre><code>#include &lt;iostream&gt; #include &lt;sstream&gt; #include &lt;fstream&gt; #include &lt;string&gt; #include &lt;vector&gt; #include &lt;boost/algorithm/string.hpp&gt; #include &lt;boost/multi_array.hpp&gt; #include "csv-test.h" #include &lt;cassert&gt; template &lt;class T&gt; class csv_reader { boost::multi_array&lt;T, 2&gt; content2d ; std::vector&lt;std::string&gt; split_line ; std::string line; std::string sep ; int ncol ; int nrow ; public : csv_reader(std::string, std::string) ; // constructor ~csv_reader(); // desctructor void cout_content() ; // print the contents T operator() (unsigned row, unsigned column) ; } ; // Constructor template &lt;class T&gt; csv_reader&lt;T&gt;::csv_reader(std::string path, std::string sep = ",") { // Initializing variables ncol = 0 ; // Initialize the number of colums to 0 nrow = 1 ; // Initialize the number of rows to 1 content2d = boost::multi_array&lt;T, 2&gt; (boost::extents[0][0]) ; std::ifstream data(path.c_str()) ; // read the csv data while(getline(data, line)) { boost::split(split_line, line, boost::is_any_of(sep) ) ; if(ncol == 0) { ncol = split_line.size() ; } else assert(ncol == split_line.size()) ; content2d.resize(boost::extents[nrow][ncol]) ; for(int i = 0; i &lt; split_line.size(); i++) { content2d[nrow - 1][i] = convertToDouble(split_line[i]) ; } nrow++ ; } } // Destructor template &lt;class T&gt; csv_reader&lt;T&gt;::~csv_reader() { } template &lt;class T&gt; void csv_reader&lt;T&gt;::cout_content() { for(int row = 0; row &lt; (nrow - 1); row++) { for(int col = 0; col &lt; ncol ; col++) { std::cout &lt;&lt; content2d[row][col] &lt;&lt; " "; } std::cout &lt;&lt; "\n" ; } } // Allow access to the contents template &lt;class T&gt; T csv_reader&lt;T&gt;::operator() (unsigned row, unsigned column) { if (row &gt;= nrow || column &gt;= ncol) throw BadIndex("boost::MultiArray subscript out of bounds"); return(content2d[row][column]) ; } int main() { // An integer csv reader csv_reader&lt;int&gt; csv_obj_int("test.csv") ; csv_obj_int.cout_content() ; // A double csv reader csv_reader&lt;double&gt; csv_obj_double("test.csv") ; csv_obj_double.cout_content() ; // It also supports direct access to the content using operator() std::cout &lt;&lt; csv_obj_double(1,1) &lt;&lt; "\n" ; std::cout &lt;&lt; csv_obj_double(1,1) * 5 &lt;&lt; "\n" ; // This statement fails with a subscript out of bounds error // std::cout &lt;&lt; csv_obj_double(10,10) * 5 &lt;&lt; "\n" ; // Testing a different seperator csv_reader&lt;double&gt; csv_obj_double_sep2("test_semicol.csv", ";") ; csv_obj_double_sep2.cout_content() ; } </code></pre> <p>and a header file (<a href="https://bitbucket.org/paulhiemstra/cpp-small-projects/src/8a8cace7a37d/src/csv-test.h">csv-test.h</a>):</p> <pre><code> // File: convert.h #include &lt;iostream&gt; #include &lt;sstream&gt; #include &lt;string&gt; #include &lt;stdexcept&gt; class BadConversion : public std::runtime_error { public: BadConversion(std::string const&amp; s) : std::runtime_error(s) { } }; class BadIndex : public std::runtime_error { public: BadIndex(std::string const&amp; s) : std::runtime_error(s) { } }; inline double convertToDouble(std::string const&amp; s) { std::istringstream i(s); double x; if (!(i &gt;&gt; x)) throw BadConversion("convertToDouble(\"" + s + "\")"); return x; } </code></pre> <p>The <code>main()</code> test the class on a number of different csv file examples: <a href="https://bitbucket.org/paulhiemstra/cpp-small-projects/src/8a8cace7a37d/data/test.csv">test.csv</a> and <a href="https://bitbucket.org/paulhiemstra/cpp-small-projects/src/8a8cace7a37d/data/test_semicol.csv">test_semicol.csv</a>.</p>
[]
[ { "body": "<h3>Header Files</h3>\n<p>Should always be protected by include guards.<br />\nOtherwise you are sustainable to infinite recursion and multiple definitions.</p>\n<pre><code>// Header.h\n#ifndef XXX\n#define XXX\n\n/// The header file goes here\n\n#endif\n</code></pre>\n<p>XXX Should be a unique identifier. A lot of build systems will generate a GUID for you. If you are doing your own then make it unique by including the namespace and file name.</p>\n<p>While we are talking about it it is worth putting all your stuff into a namespace to avoid clashes with other people code.</p>\n<h3>Source File</h3>\n<p>There is some stuff here the should be moved to the header file.</p>\n<pre><code>template &lt;class T&gt; class csv_reader {\n</code></pre>\n<p>If you want to re-use this should also be in a header file (note because it is a template you also need to put the definitions of the methods in the header file).</p>\n<p>Looking at the class you seem to be keeping too man member variables:</p>\n<pre><code>template &lt;class T&gt; class csv_reader {\n boost::multi_array&lt;T, 2&gt; content2d ;\n std::vector&lt;std::string&gt; split_line ; \n std::string line;\n std::string sep ;\n int ncol ; \n int nrow ; \npublic :\n csv_reader(std::string, std::string) ; // constructor\n ~csv_reader(); // desctructor\n void cout_content() ; // print the contents\n T operator() (unsigned row, unsigned column) ;\n} ;\n</code></pre>\n<p>The only member variable you need is <code>content2d</code>. The other variables are really function local variables you do not need to store them as part of the class.</p>\n<p>The constructor:</p>\n<pre><code>csv_reader(std::string, std::string) ; // constructor\n</code></pre>\n<p>You are passing the name of a file.<br />\nThis is very limiting. It would be more traditional to pass the file as a stream. Then you can read from a file/string/std::cin etc.</p>\n<p>You are passing things by value. This can introduce unneeded copying of the values so pass by const reference.</p>\n<pre><code>csv_reader(std::istream&amp; str, std::string const&amp; sep) ; // constructor\n</code></pre>\n<p>If you're destructor does not do anything then do not define one.</p>\n<pre><code>// Destructor\ntemplate &lt;class T&gt; csv_reader&lt;T&gt;::~csv_reader() { }\n</code></pre>\n<p>Best to just use the compiler generated version (which does the above).</p>\n<p>Printing the content: You are using the method <code>void cout_content()</code>.</p>\n<p>Explicitly encoding the stream into the name is a bad idea it makes it less flexable. Pass the stream as a parameter you can default the stream to std::cout if you want.</p>\n<pre><code>void printContent(std::ostream&amp; stream = std::cout); // print the contents\n</code></pre>\n<p>I would then also add an output operator <code>operator&lt;&lt;</code> that calls this method.</p>\n<pre><code>template &lt;class T&gt;\nstd::ostream&amp; operator&lt;&lt;(std::ostream&amp; stream, csv_reader&lt;T&gt; const&amp; data)\n{\n data.printContent(stream);\n return stream;\n}\n</code></pre>\n<p>Indexing into data: you use operator() which is fine. But with a tiny amount of work you can use [] see <a href=\"https://stackoverflow.com/a/1971207/14065\">https://stackoverflow.com/a/1971207/14065</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-19T03:09:28.890", "Id": "10141", "ParentId": "10128", "Score": "4" } }, { "body": "<p>First of all, <code>boost::split()</code> is <a href=\"http://www.boost.org/doc/libs/1_49_0/doc/html/boost/algorithm/split_id820181.html\" rel=\"nofollow\">just a <code>strtok()</code></a> so it won't work with REAL csv files. CSV parsing is huge topic and it is better avoid this discussion here.</p>\n\n<p>Second, <code>convertToDouble()</code> is not from C++, seems to be a visitor from C#. Even if I am wrong, it is design problem: template is defined for arbitrary class, but \"silently\" uses <code>double</code> for operation. It is necessary to create proper type casting, or use template specialization.</p>\n\n<p>Strange usage of <code>assert()</code>. It does something in DEBUG builds only, in release build it is empty. If you need debug aids, just put <code>assert()</code> before <code>content2d.resize(boost::extents[nrow][ncol]) ;</code> and add any <code>if</code> that you need to handle the size problem for release builds. Consider throw an exception.</p>\n\n<p>Destructor. You may drop both declaration and implementation of dtor and let the compiler create one for you, but I have a concern. </p>\n\n<p>I do not know, where <code>boost::multi_array</code> allocates its memory, but if it uses stack, you may have troubles with big arrays. Because of this, it may be better to allocate <code>content2d</code> in heap (<code>content2d = new boost::multi_array&lt;T, 2&gt;;</code> and put <code>delete content2d</code> into destructor.</p>\n\n<p>Constructor. It is better to use initializators list, so it may looks like (I agree with Loki about streams):</p>\n\n<pre><code>csv_reader(std::istream&amp; str, std::string const&amp; sep) : content2d( new boost::multi_array&lt;T, 2&gt; (boost::extents[0][0]))\n</code></pre>\n\n<p>I assume <code>boost::multi_array&lt;T, 2&gt;* content2d</code> declaration.</p>\n\n<p>You do not need <code>ncol</code> and <code>nrow</code> variables, besides local variables in ctor: array contains information about its dimensions, and if you add separate variables for that, you just add another point of failure in your code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-19T13:58:01.027", "Id": "10151", "ParentId": "10128", "Score": "5" } }, { "body": "<p>I would use <em>boost::lexical_cast</em> for type conversions. Also I consider that you shouldn't limit class to parse csv values of the single type, so I guess template parameters should specify column types as well, so maybe your multi array should keep something like <em>boost::variant</em></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-15T16:18:47.370", "Id": "54310", "ParentId": "10128", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-18T19:20:03.140", "Id": "10128", "Score": "6", "Tags": [ "c++" ], "Title": "Class to read comma separated data from disk" }
10128
<pre><code>#include &lt;cassert&gt; #include &lt;string&gt; #include &lt;vector&gt; using namespace std; inline size_t min(size_t x, size_t y, size_t z) { if (x &lt; y) return x &lt; z ? x : z; else return y &lt; z ? y : z; } size_t edit_distance(const string&amp; A, const string&amp; B) { size_t NA = A.size(); size_t NB = B.size(); vector&lt;vector&lt;size_t&gt;&gt; M(NA + 1, vector&lt;size_t&gt;(NB + 1)); for (size_t a = 0; a &lt;= NA; ++a) M[a][0] = a; for (size_t b = 0; b &lt;= NB; ++b) M[0][b] = b; for (size_t a = 1; a &lt;= NA; ++a) for (size_t b = 1; b &lt;= NB; ++b) { size_t x = M[a-1][b] + 1; size_t y = M[a][b-1] + 1; size_t z = M[a-1][b-1] + (A[a-1] == B[b-1] ? 0 : 2); M[a][b] = min(x,y,z); } return M[A.size()][B.size()]; } int main() { assert(edit_distance("ISLANDER", "SLANDER") == 1); assert(edit_distance("MART", "KARMA") == 5); assert(edit_distance("KITTEN", "SITTING") == 5); assert(edit_distance("INTENTION", "EXECUTION") == 8); } </code></pre>
[]
[ { "body": "<p>I hope you're enjoying the NLP class. I do. :)</p>\n\n<p><strong>Min</strong></p>\n\n<pre><code>inline size_t min(size_t x, size_t y, size_t z)\n{\n if (x &lt; y)\n return x &lt; z ? x : z;\n else\n return y &lt; z ? y : z;\n}\n</code></pre>\n\n<p>This could be rewritten as:</p>\n\n<pre><code>size_t min(size_t x, size_t y, size_t z)\n{\n return x &lt; y ? min(x,z) : min(y,z);\n}\n</code></pre>\n\n<p>Drop <code>inline</code> since the compiler knows better than you when to inline functions. <code>std::min</code> makes it clearer that you're using the standard library, but since you wrote <code>using namespace std;</code>, I didn't include it. You can further improve it by using a template:</p>\n\n<pre><code>template&lt;class T&gt; T min(T a, T b, T c) {\n return a &lt; b ? std::min(a, c) : std::min(b, c);\n}\n</code></pre>\n\n<p>It now works on all types supporting <code>operator&lt;</code>.</p>\n\n<p><strong>size_t</strong></p>\n\n<p>I think <code>int</code> is more idiomatic than <code>size_t</code> for your M matrix, since you're not storing a size but a distance.</p>\n\n<p><strong>Performance</strong>: You could improve memory usage by storing only two rows of M. But this would prevent your from backtracking to print the alignment, and isn't a huge win anyway (except if you're working on very large strings).</p>\n\n<p><strong>General comments</strong> Your code is really straightforward and well-written. The algorithm is simply translated, and the rest of the function is simply the initialization: there's nothing complicated, and the code is easy to read. Good job!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-18T15:10:01.117", "Id": "17453", "Score": "1", "body": "โ€œisnโ€™t a huge winโ€ โ€“ย actually it is, even on moderately-sized strings (couple thousand characters each, which is just a short text). On still larger data a linear-space implementation becomes crucial. And note that, using Hirshbergโ€™s algorithm, you can even retrieve the alignment in linear space." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-18T21:44:34.597", "Id": "10133", "ParentId": "10130", "Score": "5" } }, { "body": "<ul>\n<li><p>Implementation:</p>\n\n<ul>\n<li><p>Itโ€™s generally discouraged to open namespaces (<code>using namespace โ€ฆ;</code>). Instead, import single symbols (<code>using std::vector;</code>) or qualify symbols explicitly.</p></li>\n<li><p>Three-ways min can be written entirely in terms of <code>std::min</code>:</p>\n\n<pre><code>template &lt;typename T&gt;\nT min(T const&amp; a, T const&amp; b, T const&amp; c) {\n return std::min(std::min(a, b), c);\n}\n</code></pre></li>\n</ul></li>\n<li><p>โ€œBugโ€: the edit distance generally defines the cost for a substitution as 1 (since Levenshtein defined three equivalent edit operations), not 2 which you used in your code;</p></li>\n<li><p>Algorithmic: Your code needs O(<em>n</em> * <em>m</em>) space. Thereโ€™s a not too hard to implement variant which requires just O(min{<em>n</em>, <em>m</em>}) due to the fact that for the computation we only need to save the previous column (or row). In fact, with a bit of trickery you can make do with a <em>single</em> vector and two additional variables to save all the active values.</p></li>\n</ul>\n\n<p>But apart from that itโ€™s a very clean and efficient implementation.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-19T17:09:36.840", "Id": "17511", "Score": "0", "body": "In practice `using namespace std;` is placed in a global header for most C++ projects and code is written to avoid name collisions with the standard library." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-19T17:11:22.890", "Id": "17514", "Score": "0", "body": "The replace cost was intentionally 2, as this is a different metric than Levenstein difference. I have however changed it to parameterize it (insert_cost, delete_cost, replace_cost)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-19T17:52:36.587", "Id": "17518", "Score": "3", "body": "@user1131467 `using namespace std;` in a *header* is unacceptable. Thatโ€™s effectively a bug, since this declaration **cannot be reversed** and this *will* lead to conflict with other libraries over which you have no control, because the effect is nonlocal. This practice precludes every use of 3rd party libraries, and requires very careful coding on your part to boot; I would also discourage avoiding name collisions with the standard library โ€“ย this makes some obvious names unavailable (which leads to obtuse, non-obvious naming) and this is a problem thatโ€™s solved by namespaces." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-20T03:30:24.663", "Id": "17531", "Score": "0", "body": "Ok, so many of the multi-million line C++ codebases have this \"bug\", as does much of the C++ software you use everyday." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-20T03:43:44.210", "Id": "17536", "Score": "3", "body": "@user1131467 The fact that thousands of programmers look at examples of bad legacy code and copy what they see does not magically make it good practice. Konrad makes an excellent point here, but of course you're always free to do with it what you wish." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-20T03:50:10.350", "Id": "17538", "Score": "0", "body": "@DanielStandage: I think the reason it is so popular is not because of dogma, but because most people prefer not to have to write boilerplate code (`using namespace std;` in every file, or `std::` before every standard library symbol) just for some theoretical problem ( name collisions with standard library) that almost never comes up in practice. On the very odd occasion it does there are workarounds (wrapping include in namespace or placing include before global `using namespace std;`, or patching the third-party library, etc)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-20T09:17:21.467", "Id": "17552", "Score": "5", "body": "@user1131467 You are wrong if you think this is not a problem in practice. It can cause very common name clashes, itโ€™s definitely not โ€œthe very odd occasionโ€. And I donโ€™t think itโ€™s used in the headers of many modern C++ projects (but 80% of everything is crap according to Sturgeonโ€™s law). And thereโ€™s a difference between qualifying names and boilerplate code as the latter would be avoidable with a better language design. But qualifying name happens in every well-designed language. Writing a single `using [namespace]` declaration at the beginning of a file cannot be too much to ask for." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-20T12:29:16.010", "Id": "17561", "Score": "0", "body": "@KonradRudolph: Provide an example of a third-party library that has one of these \"very common\" naming conflicts with the standard library." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-20T12:42:20.160", "Id": "17578", "Score": "1", "body": "@user1131467 EASTL. Boost.MPL. Boost.Spirit. Heck, a lot of Boost libraries, which are lauded for their extremely high quality and are probably the most widely used C++ libraries." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-20T13:01:02.897", "Id": "17580", "Score": "0", "body": "@KonradRudolph: Those aren't real conflicts - they are all defined within namespaces - so even if you open all the namespaces - ambiguity is only a problem when you try and use an unqualified name with two definitions visible from the translation unit (eg `ref` could mean `std::ref` or `phoronix::ref`). You just qualify the name with the appropriate namespace to resolve the ambiguity when the compiler complains." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-20T13:08:21.220", "Id": "17581", "Score": "3", "body": "@user1131467 No, it's not only a problem when you do that. It's also a problem when you forget to `using namespace phoronix` and now you're inadvertedly using `std::ref` when you meant `phoronix::ref`, but the compiler doesn't help you in the slightest there. It's also a problem when ADL picks up the wrong things because you never intended for ADL to be doing anything here. Wrapping an `#include` in a namespace is also a bad idea that will probably lead to linker errors down the line." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-20T13:16:36.920", "Id": "17582", "Score": "0", "body": "@user1131467 Scratch that, I was wrong. But in addition to what Martinho said, consider every single C library without prefixes, they all become unusable by this. And you cannot fix this since wrapping the headers in a namespace would modify their symbol names (i.e. that would only work with header-only libraries)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-20T13:22:08.630", "Id": "17583", "Score": "0", "body": "@KonradRudolph: The practice of importing using namespace std in almost every major C++ project means that if a C library cannot handle it, it won't get very far (this is what I was asking for an example of). It just doesn't come up. (Also I think you can use `extern \"c\"` in combination to link across the surrogate namespace.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-25T03:23:18.547", "Id": "58830", "Score": "0", "body": "You chased him off :(" } ], "meta_data": { "CommentCount": "14", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-18T10:01:31.640", "Id": "10984", "ParentId": "10130", "Score": "9" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-18T21:24:49.807", "Id": "10130", "Score": "7", "Tags": [ "c++", "strings", "c++11", "edit-distance" ], "Title": "Edit Distance Between Two Strings" }
10130
<p>Here is my code:</p> <pre><code>hasAttr = new function(tag, attrName) { return (tag.attrName) } </code></pre> <p>Will this code work? I can't test it now because I cannot acces <a href="http://jsfiddle.net/" rel="nofollow">jsfiddle</a> and <a href="http://jsbin.com/" rel="nofollow">jsbin</a> but <a href="http://downforeveryoneorjustme.com/" rel="nofollow">Down For Everyone or Just Me?</a> says something else.</p> <ol> <li><a href="http://www.downforeveryoneorjustme.com/jsfiddle.net" rel="nofollow">jsFiddle Down For Everyone or Just Me</a></li> <li><a href="http://www.downforeveryoneorjustme.com/jsbin.com" rel="nofollow">jsBin Down For Everyone or Just Me</a></li> </ol> <p>Example usage:</p> <p>JavaScript:</p> <pre><code>alert(hasAttr("div", "id")) </code></pre> <p>HTML:</p> <pre><code>&lt;div id="header"&gt;&lt;/div&gt; </code></pre> <p>Expected:</p> <pre><code>(In alert box) true OK </code></pre> <p>Can someone test it for me?</p> <p>If it doesn't work, how should I code it?</p> <p>I want <code>hasAttr</code> to return <code>true</code> or <code>false</code>.</p> <p>I will be open to code optimization, cleaner code etc.</p> <p>Thanks in advance!</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-19T00:10:34.330", "Id": "16147", "Score": "1", "body": "`hasAttr(\"div\", \"id\")` You are sending a string \"div\" and you are treating it like an object in your function. Something is wrong!" } ]
[ { "body": "<p>Testing JavaScript code in jsFiddle to make sure it works is suicide. The difficult part about JavaScript is really cross-browser compatibility, which means you just <strong>can't</strong> just test in one browser to say it works.</p>\n\n<p>That being said, the name <code>hasAttr</code> makes me think that you want to return true/false, which is not what you're doing. You should use DOM's <a href=\"https://developer.mozilla.org/en/DOM/element.hasAttribute\" rel=\"nofollow\"><code>element.hasAttribute()</code></a>, which already implements what you're trying to do. It's DOM 1, so it's safe to use and will work in any browser supporting JavaScript.</p>\n\n<p>By the way, why are you using this funky syntax to create your function? Is there a good reason not to use <code>function hasAttribute() { ... }</code>?</p>\n\n<p>(You should accept seand's answer, though, I didn't know it wasn't supported until IE 8. You should also consider using something like jQuery which will help you avoid mistakes like that.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-18T21:55:11.360", "Id": "16143", "Score": "0", "body": "you beat me by ~20 seconds :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-18T21:59:42.953", "Id": "16144", "Score": "0", "body": "Not really the same answer! I didn't know about IE, and you didn't notice he wants to see \"true\", which means he simply wants hasAttribute. At least I think so." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-18T22:03:17.917", "Id": "16145", "Score": "0", "body": "Ah, good catch, thanks... changed my answer." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-18T21:53:54.600", "Id": "10134", "ParentId": "10131", "Score": "2" } }, { "body": "<p>To check if an HTML element has an attribute, you should use <a href=\"http://www.quirksmode.org/dom/w3c_core.html#t125\" rel=\"nofollow\"><code>hasAttribute</code></a>. If you have to support IE6 and IE7, check its existence using <a href=\"http://www.quirksmode.org/dom/w3c_core.html#t127\" rel=\"nofollow\"><code>[name]</code></a>.</p>\n\n<p>Given that, the implementation of <code>hasAttr</code> would be something like this:</p>\n\n<pre><code>hasAttr = function(tag, attrName) {\n return tag.hasAttribute ? tag.hasAttribute(attrName)\n : tag[attrName] !== undefined;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-19T11:44:26.313", "Id": "16156", "Score": "1", "body": "Can you rewrite using `if` instead of `?`/`:` please?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-19T12:41:11.927", "Id": "16159", "Score": "3", "body": "`return a ? b : c` means `if(a) { return b; } else { return c; }`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T21:34:43.110", "Id": "49551", "Score": "0", "body": "Why the `new` here?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T02:15:03.483", "Id": "49568", "Score": "0", "body": "@BenjaminGruenbaum: Good catch, I don't think it belongs there. It was in the original code but looks like a bug, so I edited it out of my post." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-11T19:58:26.940", "Id": "52108", "Score": "0", "body": "!!tag[attrName] will return false if the attribute exists but is an empty string..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-01-09T18:26:17.023", "Id": "139598", "Score": "0", "body": "@Brett You are correct that this method is blind to the difference between an attribute not existing and an attribute being `''`. But in old IE (versions 5-7 that lack `hasAttribute`), `getAttribute` returns `null` when the attribute is not defined. So doing `function hasAttr(el, attr) { return el.hasAttribute ? el.hasAttribute(attr) : el.getAttribute(attr) !== null; }` should work. Tested using http://netrenderer.com/index.php." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-18T21:54:18.477", "Id": "10135", "ParentId": "10131", "Score": "6" } } ]
{ "AcceptedAnswerId": "10135", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-18T21:27:27.420", "Id": "10131", "Score": "1", "Tags": [ "javascript", "html" ], "Title": "Will this test to check if an element has an attribute work?" }
10131
<p>Here is some code that I put together for an app I am working on that loads 2 XML files and a large CVS file to a dataset at startup. It runs fairly fast, but I would like a second opinion on what I could do to either make it more consise or faster. I'm newer to .NET as well, so if you see anything that isn't very ."net ish" let me know!</p> <pre><code>#Region "Imports" Imports System.IO Imports System.Xml Imports System.Text Imports System.Threading #End Region Class clsLoadTables #Region "Properties and Shared Variables" Private Shared pathTableTwo As String = My.Settings.pathTableTwo Private Shared pathMainTable As String = My.Settings.pathMainTable Private Shared pathBeneLifeExp As String = My.Settings.pathBeneLifeExp Private _ds As New DataSet Public Property ds() As DataSet Get Return _ds End Get Set(ByVal value As DataSet) _ds = value End Set End Property #End Region #Region "Constructors" Sub New() loadBeneLifeExpTable() loadMainRMDTable() loadCSVTableII() End Sub #End Region #Region "ClassMethods" Public Sub loadCSVTableII() Dim dt As DataTable = ds.Tables.Add("TableII") Dim line As String = String.Empty Dim counter As Short = 0 Dim reader As New StreamReader(pathTableTwo) Dim errorString As New StringBuilder Try errorString.Append("The tableII csv file did not load properly") errorString.Append(Environment.NewLine &amp; Environment.NewLine) errorString.Append("Make syre the tabel_II.csv file is in the project folder") Catch ex As Exception Throw End Try Try While Not reader.EndOfStream() line = reader.ReadLine() Dim lineSep As List(Of String) = line.Split(",").ToList If Not counter = 0 Then dt.Rows.Add(lineSep.ToArray) counter += 1 Else For Each value As String In lineSep dt.Columns.Add(value) Next counter += 1 End If End While Dim primarykey(0) As DataColumn primarykey(0) = dt.Columns("Ages") dt.PrimaryKey = primarykey Catch ex As FileNotFoundException MessageBox.Show(errorString.ToString) Throw Catch ex As Exception Throw Finally reader.Close() End Try End Sub Public Sub loadMainRMDTable() Dim tempDs As New DataSet Dim dt As New DataTable Dim settings As New XmlReaderSettings Dim errorString As New StringBuilder Try errorString.Append("The RMD table did not load properly!") errorString.Append(Environment.NewLine &amp; Environment.NewLine) errorString.Append("Make sure that the file 'MainRMDTable.xml' is in the project folder") Catch ex As Exception Throw End Try Try Dim xmlFile As XmlReader xmlFile = XmlReader.Create(pathMainTable, settings) tempDs.ReadXml(xmlFile) dt = tempDs.Tables("Age") dt.TableName = "MainRMDTable" xmlFile.Close() Dim primarykey(0) As DataColumn primarykey(0) = dt.Columns("age") dt.PrimaryKey = primarykey ds.Merge(tempDs) Catch ex As FileNotFoundException Throw Catch ex As Exception MessageBox.Show(errorString.ToString) Throw Finally errorString.Clear() tempDs.Clear() End Try End Sub Public Sub loadBeneLifeExpTable() Dim dt As New DataTable Dim settings As New XmlReaderSettings Dim errorString As New StringBuilder Try errorString.Append("The bene life expectancy table did not load properly ") errorString.Append(Environment.NewLine &amp; Environment.NewLine) errorString.Append("Make sure that the file 'beneLifeExpectancyTable.xml' is in the project folder") Catch ex As Exception Throw End Try Try Dim xmlFile As XmlReader xmlFile = XmlReader.Create(pathBeneLifeExp, settings) ds.ReadXml(xmlFile) dt = ds.Tables("Age") dt.TableName = "BeneLifeExpectancyTable" xmlFile.Close() Dim primarykey(0) As DataColumn primarykey(0) = dt.Columns("BeneLifeExpectancyTable") dt.PrimaryKey = primarykey Catch ex As Exception MessageBox.Show(errorString.ToString) MessageBox.Show(ex.Message &amp; ex.StackTrace()) Throw Finally errorString.Clear() End Try End Sub #End Region End Class </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-21T19:16:39.177", "Id": "16275", "Score": "1", "body": "I'm not a vb.net expert but do you need to do a line.ToList() on the string when you are doing a ToArray() later on. Seems like possible duplication to me?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-22T00:23:07.787", "Id": "16287", "Score": "0", "body": "Dreza, yeah you are right. The reason I did it this way is that I am trying to not use any of the vb array methods if I can get away with it. I want to get in the habit of using the modern .Net components. But in this case you are correct, I should just declare lineSep as an array becuase that is what line.split will return. Also, since you can't add a generic list directly to a datatable I could eliminate the dt.row.Add(lineSep.ToArray) statement as well. Good catch." } ]
[ { "body": "<p>Move code that displays Message Boxes up the call hierarchy.\nMake better use of exceptions.\nUse String Builders only when you append a lot, not just a couple of lines, try using String.Format.\nFollow official VB.NET naming conventions \"Begin each separate word in a name with a capital letter\".</p>\n\n<p>Make one generic method instead of loadMainRMDTable and loadBeneLifeExpTable by passing file path, table name and column name(s) as parameters.</p>\n\n<p>Some code to illustrate:</p>\n\n<pre><code>Sub New()\n Try\n LoadBeneLifeExpTable()\n LoadMainRMDTable()\n LoadCSVTableII()\n Catch ex As Exception\n MessageBox.Show(ex.ToString())\n End Try\nEnd Sub\n\n\nPublic Sub LoadBeneLifeExpTable()\n Dim dt As New DataTable\n Dim settings As New XmlReaderSettings\n\n Try\n Dim xmlFile As XmlReader\n xmlFile = XmlReader.Create(pathBeneLifeExp, settings)\n\n ds.ReadXml(xmlFile)\n dt = ds.Tables(\"Age\")\n dt.TableName = \"BeneLifeExpectancyTable\"\n\n xmlFile.Close()\n\n Dim primarykey(0) As DataColumn\n primarykey(0) = dt.Columns(\"BeneLifeExpectancyTable\")\n dt.PrimaryKey = primarykey\n\n Catch ex As Exception\n //' Using String.Format would be even better\n Throw New Exception(\"The bene life expectancy table did not load properly \" + _\n Environment.NewLine + Environment.NewLine + _\n \"Make sure that the file '\" + \"' is in the project folder\",\n ex)\n End Try\nEnd Sub\n</code></pre>\n\n<p>PS: try not to use VB(.NET) - there are better languages; get ReSharper (it will give you some hints on how to make code better).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-22T00:18:48.963", "Id": "16286", "Score": "0", "body": "Thanks for the analysis. When I use just the 'throw' statement in my methods it is because the class that is calling the methods is already using a try statement. I thought that I had to do it this way to retain the ex.stacktrace all the way up the code. I've been looking around for some good vb.net documentation about nested exceptions but cannot find any. Do you know of any good links? BTW - I am using VB.Net because I have to for a few projects at work. I fully intend on getting up to speed with C# once I can write basic apps in vbnet." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-22T09:49:42.220", "Id": "16302", "Score": "0", "body": "\"Nested exceptions\" is probably not a widely recognized term and there is not much to it. You are correct that \"Throw\" allows you to preserve the stack trace as opposed to \"Throw ex\". However you can also set ex.InnerException property as I did via constructor to specify the underlying exception that caused current exception. This way you can build a \"hierarchy\" of exceptions - e.g. from more concrete to more generic. When using ex.ToString() it will produce a string containing messages and stack traces of current exception along with all its inner exceptions. It's OOP - not a language feature" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-21T10:15:52.953", "Id": "10209", "ParentId": "10137", "Score": "2" } } ]
{ "AcceptedAnswerId": "10209", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-18T23:17:08.343", "Id": "10137", "Score": "2", "Tags": [ ".net", "xml", "csv", "vb.net" ], "Title": "Loading XML and csv files to datatables at startup" }
10137
<p>The game of life is often implemented by representing the board as a 2D boolean array. This doesn't scale very well to larger boards -- it starts to consume lots of memory, and without some separate mechanism to keep track of a list of live cells, you have to visit each board cell on each iteration. This implementation just keeps a list of live cells to represent the board state; the board "size" is limited only by the maximum of an integer.</p> <pre><code>import Data.List as L import Data.Map as M type Coo = (Int,Int) type Board = Map Coo Int moveBoard::Coo-&gt;Board-&gt;Board moveBoard (dx,dy) = M.mapKeysMonotonic (\(x,y)-&gt;(x + dx, y + dy)) countNeighbors::Board-&gt;Board countNeighbors b = unionsWith (+) [ moved (-1, -1), moved (0, -1), moved (1, -1), moved (-1, 0), moved (1, 0), moved (-1, 1), moved (0, 1), moved (1, 1) ] where moved (dx, dy) = moveBoard (dx, dy) b lifeIteration::Board-&gt;Board lifeIteration b = M.union birth survive where neighbors = countNeighbors b birth = M.map (const 1) (M.filter (==3) neighbors) survive = M.intersection b (M.filter (==2) neighbors) glider = M.fromList $ L.map (\(x,y)-&gt;((x,y),1::Int)) ([(1,1),(1,2),(1,3),(2,3),(3,2)]::[(Int,Int)]) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T18:10:20.540", "Id": "50326", "Score": "0", "body": "If you want to compute long and large sequences of Life, you might be interested in [hashlife](https://en.wikipedia.org/wiki/Hashlife)." } ]
[ { "body": "<p><strong>Edit</strong>: This answer was given when the reviewed code looked quite differently.</p>\n\n<p>Any specific questions? Here's what stands out for me:</p>\n\n<ol>\n<li><p>Why do <code>toList</code> in <code>emptyNeighbors</code>, then go back to <code>Set</code> again? You could simply use <code>Data.Set.map</code> there.</p></li>\n<li><p><code>countNeighbor</code> is very inefficient: the <code>filter</code> operation always iterates over all life cells, and you are calling it three times per existing cell! That's unneeded, as you only ever care about a handful of neighbourhood cells.</p></li>\n</ol>\n\n<p>My idea to fix issue 2 would be to build a <code>Map</code> of the neighbour count of every cell. If you represent the board as a <code>Map</code> with only <code>1</code> cells in it, that can be done pretty efficiently using <code>mapKeysMonotonic</code> and <code>unionsWith</code>:</p>\n\n<pre><code>type Coo = (Int, Int)\ntype Board = Map Coo Int\n\nmoveBoard :: Coo -&gt; Board -&gt; Board\nmoveBoard (dx,dy) = M.mapKeysMonotonic (\\(x, y) -&gt; (x+dx, y+dy))\n\ncountNeighbours :: Board -&gt; Board\ncountNeighbours b =\n unionsWith (+) [ moved (-1) (-1), moved 0 (-1), moved 1 (-1)\n , moved (-1) 0 , moved 1 0\n , moved (-1) 1 , moved 0 1 , moved 1 1 ]\n where moved dx dy = moveBoard (dx,dy) b\n</code></pre>\n\n<p>Note that usage of <code>mapKeysMonotonic</code> is only safe because the order of coordinates doesn't change when we add a constant. Effectively, this means that the library can simply replace the concrete coordinates without any internal resorting.</p>\n\n<p>The iteration is then a simple matter of using <code>filter</code>, <code>map</code> and <code>intersection</code> over the result:</p>\n\n<pre><code>lifeIteration :: Board -&gt; Board\nlifeIteration b = M.union birth survive\n where neighbours = countNeighbours b\n birth = M.map (const 1) (M.filter (==3) neighbours)\n survive = M.intersection b (M.filter (==2) neighbours)\n</code></pre>\n\n<p>Changing your formulation slightly by having a life cell with 3 neighbours \"rebirth\" instead of survive, as that's a bit simpler to write.</p>\n\n<p>Also note that this is a bit \"clever\" by taking advantage of the fact that <code>intersection</code> always returns the value of the <em>first</em> <code>Map</code>, therefore I don't need to do another <code>M.map (const 1)</code> step in there.</p>\n\n<p>I hope this is helpful to you.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-19T13:44:01.613", "Id": "10150", "ParentId": "10139", "Score": "3" } } ]
{ "AcceptedAnswerId": "10150", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-19T01:26:43.753", "Id": "10139", "Score": "3", "Tags": [ "haskell", "game-of-life" ], "Title": "The game of life with a truly infinite board" }
10139
<pre><code>public interface ICacheable&lt;TK,TV&gt; { TV Get(TK key); void Add(TK key, TV val); } public abstract class BaseCache&lt;TK, TV&gt; { protected static Dictionary&lt;Guid, Dictionary&lt;TK, TV&gt;&gt; data = new Dictionary&lt;Guid, Dictionary&lt;TK, TV&gt;&gt;(); private Guid StorageNameSpage; protected BaseCache(Guid storageNameSpage) { StorageNameSpage = storageNameSpage; } protected BaseCache() { StorageNameSpage = Guid.NewGuid(); } public TV Get(TK key) { return data[StorageNameSpage][key]; } public void Add(TK key, TV val) { data.Add(....); } } </code></pre> <p>2 different ways to implement it:</p> <p>"mulityTon" or what ever you want to call it.</p> <pre><code>public class KeyValCacheStorage&lt;TK, TV&gt; : BaseCache&lt;TK, TV&gt;, ICacheable&lt;TK, TV&gt; { } </code></pre> <p>SingleTome</p> <pre><code>public class KeyValCacheStorageSingleTon&lt;TK, TV&gt; : BaseCache&lt;TK, TV&gt;, ICacheable&lt;TK, TV&gt; { private static Guid storageNameSpage = Guid.NewGuid(); public KeyValCacheStorageSingleTon():base(storageNameSpage) { } } </code></pre> <p>usage:</p> <pre><code>KeyValCacheStorageSingleTon&lt;string, string&gt; storageSingleTon1 = new KeyValCacheStorageSingleTon&lt;string, string&gt;(); storageSingleTon1.Add("storageSingleTon1", "KeyValCacheStorageSingleTon"); storageSingleTon1.Add("bla", "yada"); KeyValCacheStorageSingleTon&lt;string, string&gt; storageSingleTon2 = new KeyValCacheStorageSingleTon&lt;string, string&gt;(); storageSingleTon2.Add("storageSingleTon2", "KeyValCacheStorageSingleTon2"); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-19T15:30:02.470", "Id": "16164", "Score": "1", "body": "How is this better than having a private static dictionary elsewhere? The dictionary gives you a lot of functionality, such as it can tell you whether a key exists, it can participate in a LINQ query, etc. etc. I would rather write an algorithm against an IDictionary than ICacheable interface." } ]
[ { "body": "<p>One comment on the code: you will find your constructors easier to maintain if you use constructor chaining</p>\n\n<p>protected BaseCache() : this(Guid.NewGuid() ) \n{\n} </p>\n\n<p>Now my possibly ignorant comments on other things. </p>\n\n<ul>\n<li>The usage is almost identical to <code>Dictionary&lt;K,V&gt;</code> why would I not just use a static instance of a dictionary?</li>\n<li>Are you sure that a single multidimensional dictionary actually preforms better than different instances of a regular dictionary? Have you done profiling on this? It seems to me unlikely (I use that in a snark-free sense, it seems unlikely but I don't know)</li>\n<li>There's like a 192732981923 different cache implementations already out there. Why not use one of those?</li>\n<li>When is this cache cleared? I don't see any options about that. That is the more interesting part of any caching API.</li>\n<li>The interface is similar to <code>IDictionary&lt;K,V&gt;</code> but not quite the same. This might subtly break expectations. I don't think you'd loose anything in just implementing that interface.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-19T14:05:04.683", "Id": "16161", "Score": "0", "body": "Thanks, \n1. Because you have a singleTon mechanism \"for free\" 2. no, but from what I read its the same. 3. yea I know, each of everyone who wrote them has the right to start a new one, like myself. 4. yes, I added that. 5. more complex. thank you" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-19T14:48:12.727", "Id": "16163", "Score": "0", "body": "@sexyMF Yes you can of course implement your own, I was more wondering what requirement drove you to that and if there's another way to address it. I don't know what you mean by getting a static mechanism for free. The only difference seems to be that you don't have to write the word 'static'?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-19T13:37:24.313", "Id": "10149", "ParentId": "10146", "Score": "3" } }, { "body": "<p>So I've made a few modifications; here are the explanations:</p>\n\n<ul>\n<li>Used interfaces a bit more liberally (<code>IDictionary</code>)</li>\n<li>Made <code>BaseClass</code> implement <code>ICacheable</code> so the subclasses don't explicitly have to</li>\n<li>Made fields <code>readonly</code> as appropriate to declare intent</li>\n<li>Made field <code>data</code> <code>private</code> and exposed as <code>protected</code> by way of a property</li>\n<li>Chained the <code>BaseCache</code> constructors</li>\n<li>Created the storage dictionary in the constructor (could do this in <code>Add</code> if you were looking for lazy creation)</li>\n<li><code>sealed</code> subclasses (if they're intended to be non-inheritable, of course)</li>\n</ul>\n\n<p>The code:</p>\n\n<pre><code>public interface ICacheable&lt;TK, TV&gt;\n{\n TV Get(TK key);\n\n void Add(TK key, TV val);\n}\n\npublic abstract class BaseCache&lt;TK, TV&gt; : ICacheable&lt;TK, TV&gt;\n{\n private static readonly IDictionary&lt;Guid, IDictionary&lt;TK, TV&gt;&gt; data = new Dictionary&lt;Guid, IDictionary&lt;TK, TV&gt;&gt;();\n\n private readonly Guid storageNameSpace;\n\n protected BaseCache(Guid storageNameSpace)\n {\n this.storageNameSpace = storageNameSpace;\n data[this.storageNameSpace] = new Dictionary&lt;TK, TV&gt;();\n }\n\n protected BaseCache() : this (Guid.NewGuid())\n {\n }\n\n protected static IDictionary&lt;Guid, IDictionary&lt;TK, TV&gt;&gt; Data\n {\n get\n {\n return data;\n }\n }\n\n public TV Get(TK key)\n {\n return data[this.storageNameSpace][key];\n }\n\n public void Add(TK key, TV val)\n {\n data[this.storageNameSpace].Add(key, val);\n }\n}\n\npublic sealed class KeyValCacheStorage&lt;TK, TV&gt; : BaseCache&lt;TK, TV&gt;\n{\n}\n\npublic sealed class KeyValCacheStorageSingleton&lt;TK, TV&gt; : BaseCache&lt;TK, TV&gt;\n{\n private static readonly Guid storageNameSpace = Guid.NewGuid();\n\n public KeyValCacheStorageSingleton() : base(storageNameSpace)\n {\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-19T16:11:01.563", "Id": "10153", "ParentId": "10146", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-19T11:29:42.850", "Id": "10146", "Score": "3", "Tags": [ "c#", "cache" ], "Title": "C# small caching API" }
10146
<p>I use ruby 1.8.7. I have method wich select records and fill hash. In my opinion the code is not dry. Could somebody help me to refactor it and make it shorter and more elegant?</p> <pre><code>def fill_attributes() if (!$array[:status_id]) $array[:status_id] = @customer.status_id @status_name=Status.find($array[:status_id]).name rescue nil $array[:status]=@status_name if @status_name end if (!$array[:color_id]) $array[:color_id] = @customer.color_id @color_name=Color.find($array[:color_id]).name rescue nil $array[:color]=@color_name if @color_name end ..... end </code></pre> <p>My version is:</p> <pre><code> map={'model1' =&gt; Model1, 'model2' =&gt; Model2,'model3' =&gt;Model3} map.keys.each do |model| key="#{model}_id".to_sym value="#{model}.#{model}_id" if (!$array[key]) $array[key] = #instance_variable_set("@#{value}",eval(value, binding) ) name=map[model].find($array[key]).name rescue nil $array[key]=name if name end end </code></pre> <p>But there's a problem, to use <code>instance_variable_set</code> I have to create a class? What is the best way to refactor it?</p>
[]
[ { "body": "<p>I think you can optimize it like :</p>\n\n<pre><code>def fill_attributes()\n if (!$array[:status_id])\n $array[:status_id] = @customer.status_id\n $array[:status]= get_attribute_name('status',$array[:status_id] )\n end\n\n if (!$array[:color_id])\n $array[:color_id] = @customer.color_id\n $array[:color]= get_attribute_name('color',$array[:color_id] )\n end\n\nend \n\nPrivate\n\ndef get_attribute_name(relator, relator_id)\n relator = relator.classify.constantize.find(relator_id)\n !relator.nil? ? relator.name : nil\nend\n</code></pre>\n\n<p>Hope this will help you .</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-19T10:13:57.470", "Id": "16158", "Score": "0", "body": "Hi, but it does not reduced the code :) almost the same" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-19T21:32:39.957", "Id": "16174", "Score": "3", "body": "Refactoring isn't always about making your code shorter. Your aim is always to make the code easier to understand, or to introduce more flexibility so that you can add a new feature. A refactor often has the effect on increasing your code length (especially if you extract lots of methods). This is not a bad thing if your code becomes easier to read." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-19T06:17:32.710", "Id": "10148", "ParentId": "10147", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-18T20:31:32.673", "Id": "10147", "Score": "2", "Tags": [ "ruby", "ruby-on-rails" ], "Title": "Select records and fill hash" }
10147
<p>I've defined a Client class to connect to an external API. The Client class will return XML responses for various resources. Here's what it looks like now:</p> <pre><code>require 'nokogiri' class Client include Exceptions CONFIG = YAML.load_file(File.join(Rails.root, 'config', 'mark.yml')) def self.get_leagues_xml(league, start_date, end_date) raise ArgumentError, "No args can be nil." if league.nil? || start_date.nil? || end_date.nil? start_date = format_date(start_date) end_date = format_date(end_date) @url = build_url_for(:leagues) @url_params = {'League' =&gt; league, 'StartDate' =&gt; start_date, 'EndDate' =&gt; end_date} call_http_service end def self.get_seasons_xml(season) raise ArgumentError, "No args can be nil." if season.nil? @url = build_url_for(:seasons) @url_params = {'Season' =&gt; season} call_http_service end protected def self.call_http_service begin conn = create_connection resp = get_response(conn) resp_xml = Nokogiri::XML(resp.body) rescue Faraday::Error::ClientError =&gt; ce raise MarkClientError.new("Client error occurred trying to access Mark feed at #{@url}: #{ce.message}.") rescue =&gt; e raise e end end def self.get_response(connection) connection.get do |req| req.params['Username'] = CONFIG['api']['username'] req.params['Password'] = CONFIG['api']['password'] @url_params.each_pair { |key, val| req.params[key] = val} req.options = {:timeout =&gt; 30} # open/read timeout in secs end end def self.create_connection Faraday.new(:url =&gt; @url) do |builder| builder.request :url_encoded builder.response :logger builder.adapter :net_http end end def self.build_url_for(resource) CONFIG['api']['url'] + CONFIG['resource']["#{resource.to_s}"]['url'] end def self.format_date(date) date = Chronic.parse(date) if date.is_a?(String) date.strftime('%m/%d/%Y') end end </code></pre> <p>My primary question is whether or not my use of the class instance variables (@url and @url_params) is an anti-Rubyism and will get me into trouble when multiple concurrent class method calls are being made? I've considered making Client a module or a superclass and then having separate classes for each type of API call that needs to made, for ex, LeaguesClient and SeasonsClient. That way I could make those instantiated classes and initialize with url and url_params. I'm starting to experiment with the distinct nuances of Ruby but want to check with you guys as to how you would approach. Any thoughts you have would be welcome. Thanks!</p>
[]
[ { "body": "<p>Using the <code>@url</code> and <code>@url_params</code> variables this way is not idiomatic Ruby. There are similar uses of instance fields in Ruby on Rails, but this is for passing state out of Controllers and into Views. It is not standard object-oriented practice, but in Rails it is done to remove boiler-plate code. Elsewhere this style is not the norm.</p>\n\n<p>You should also be consistent within the class in how you pass state between methods. <code>get_response</code> expects a <code>connection</code> to be passed to it, but pulls another \"parameter\" <code>@url_params</code> out of the class-level fields. It should get all input from one location to make it easier to follow the code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-19T21:29:33.453", "Id": "10162", "ParentId": "10152", "Score": "1" } }, { "body": "<pre><code>CONFIG = YAML.load_file(File.join(Rails.root, 'config', 'mark.yml'))\n</code></pre>\n\n<p>This does not belong inside the class, it makes it impossible for others to change the configuration depending on environment (dev, test, prod). You can either pass in a map of options to the constructor or say in Rails use an initializer class to read in the appropriate configuration and apply it.</p>\n\n<pre><code>raise ArgumentError, \"No args can be nil.\" if league.nil? || start_date.nil? || end_date.nil?\n</code></pre>\n\n<p>It's good to validate your arguments, however this message doesn't help the developer/user of the class because it doesn't indicate which argument was nil. As tedious as it is I would validate each arg separately and indicate which argument was nil in the message.</p>\n\n<p>Regarding the use of <code>@url</code> and <code>@url_params</code> sgmorrison is correct and you should not be using class instance variables especially in a static class. If their values were immutable then fine but that is not the case. A simple change would be to pass both url and urlparams as options/args to call_http_service and so forth.</p>\n\n<p>Another option would be to separate the two concerns of this class into individual classes. One that is a service class and one that is a connection class. Then you can encapsulate all connection logic into one (likely none static) class, and the user can interface with the service class. Should you choose this method you could then use a factory and/or mock out the connection to make unit testing easier.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-21T01:15:21.583", "Id": "17622", "Score": "0", "body": "marc, great input...thanks for taking the time...i'll definitely implement your suggestions" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-19T12:11:35.697", "Id": "11008", "ParentId": "10152", "Score": "2" } } ]
{ "AcceptedAnswerId": "11008", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-19T15:36:40.650", "Id": "10152", "Score": "2", "Tags": [ "ruby", "classes", "api" ], "Title": "Ruby - class definition for connecting to external API" }
10152
<p>I'm pretty new to OCaml, so any feedback is appreciated. The goal is to implement a trie that efficiently stores and sorts strings.</p> <pre><code>module CharMap = Map.Make(Char) (* count of members of the set that end at this node * mapping from next char =&gt; children *) type trie = Node of int * trie CharMap.t let empty = Node (0, CharMap.empty) (* Add a string to the trie *) let rec add (Node (count, children) : trie) = function | "" -&gt; Node (count + 1, children) | str -&gt; let firstChar = String.get str 0 in let lastChars = String.sub str 1 ((String.length str) - 1) in let newTrie = if CharMap.mem firstChar children then add (CharMap.find firstChar children) lastChars else add empty lastChars in let newChildren = CharMap.add firstChar newTrie children in Node (count, newChildren) let addAll (trie : trie) (strs : string list) : trie = List.fold_left (fun trieAcc str -&gt; add trieAcc str) empty strs (* Get all the strings of a trie *) let traverse (trie : trie) : string list = let rec helper (Node (count, children) : trie) (prevChar : char option) : string list = let string_of_char chr = match chr with | None -&gt; "" | Some ch -&gt; String.make 1 ch in let perChild = List.map (fun (chr, child) -&gt; (helper child (Some chr))) (CharMap.bindings children) in let fromChildren = List.flatten perChild in let withPrev = List.map (fun str -&gt; (string_of_char prevChar) ^ str) fromChildren in let rec clone str count = if count = 0 then [] else str::(clone str (count - 1)) in (clone (string_of_char prevChar) count) @ withPrev in helper trie None let sort (strs: string list): string list = traverse (addAll empty strs) </code></pre> <p>What do you think?</p>
[]
[ { "body": "<p>You're pretty new to OCaml? You're using OCaml 3.12 features and probably did a lot of functional programming before. Let's see if I can show what idioms I've seen before. I'm not an OCaml expert though, far from it.</p>\n\n<p><strong>Empty trie</strong> Consider using something like <code>Empty</code> to denote the empty trie. <code>type trie = Empty | Node of int * trie CharMap.t</code> This is better than your <code>empty</code> hack, and will allow you to take advantage of OCaml's pattern matching.</p>\n\n<p><strong>string_of_char</strong> is a nice OCaml name, but this is not <em>really</em> <code>string_of_char</code>, but <code>string_of_char_option</code>. Since it's not important, I'd tend to make it look smaller in the code.</p>\n\n<pre><code>let string_of_char_option = function None -&gt; \"\" | Some ch -&gt; String.make 1 ch\n</code></pre>\n\n<p><strong>Auxiliary function name</strong> You don't need to use the name <code>helper</code>: <code>traverse</code> is fine. It's not ambiguous since traverse is not recursive. This applies to all functions with auxiliary functions.</p>\n\n<p><strong>Indentation</strong> I'm not sure I understand how you choose to put your <code>in</code>s. Also, <code>fromChildren</code> has a wrong indentation.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-19T23:04:51.913", "Id": "16176", "Score": "0", "body": "Thanks for the feedback!\n\nGood catch on `string_of_char`. I feel like `string_of_char_opt` is a good compromise. I know it's not ambiguous, but shadowing variables from enclosing scopes (like having `traverse` within `traverse`) feels too \"clever\". Indentation is weird, I know. I'm trying to keep it as readable as possible with 80 chars/line." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-19T23:06:02.537", "Id": "16177", "Score": "1", "body": "I'm not sure about `Empty`. Adding `Empty` to type `trie` means that there are now more ways to encode emptiness, increasing complexity. Also, there's never a time that I check if some `trie = empty`, so it's not clear when I'd take advantage of the pattern matching." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-19T20:48:20.623", "Id": "10160", "ParentId": "10154", "Score": "3" } }, { "body": "<p>This is how I would write the traverse function:</p>\n\n<pre><code>(* Get all the strings of a trie *)\nlet traverse (trie : trie) : string list =\n let string_of_char chr = String.make 1 chr in\n let rec traverse (Node (count, children) : trie) (prevString : string) : string list =\n let fromChildren = List.flatten (List.map (fun (chr, child) -&gt; \n (traverse child (prevString^(string_of_char chr)))) (CharMap.bindings children))\n in\n let rec clone count =\n if count = 0 then fromChildren\n else prevString::(clone (count - 1))\n in\n clone count\n in\n traverse trie \"\"\n</code></pre>\n\n<p>I think you use too much auxiliary variables, there is no need for them here.</p>\n\n<p>The next step when you have a fonction like this is to use minimum space on the stack, for that you must remove the <code>List.flatten</code> function:</p>\n\n<pre><code>let traverse_tr trie =\n let string_of_char chr = String.make 1 chr in\n let rec traverse (Node(count, children)) prevString acc =\n let rec clone count acc =\n if count = 0 then acc\n else (clone (count-1) (prevString :: acc))\n in\n CharMap.fold (fun chr t -&gt; traverse t (prevString^(string_of_char chr)) )\n children (clone count acc)\n in\n traverse trie \"\" []\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-04T20:06:40.373", "Id": "12278", "ParentId": "10154", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-19T17:46:58.623", "Id": "10154", "Score": "5", "Tags": [ "ocaml" ], "Title": "String Trie in OCaml" }
10154
<p>I would like some eyes on this:</p> <pre><code>/* Little XHR * by: rlemon http://github.com/rlemon/ * see README for useage. * */ var xhr = { xmlhttp: (function() { var xmlhttp; try { xmlhttp = new XMLHttpRequest(); } catch (e) { try { xmlhttp = new ActiveXObject('Msxml2.XMLHTTP'); } catch (er) { try { xmlhttp = new ActiveXObject('Microsoft.XMLHTTP'); } catch (err) { xmlhttp = false; } } } return xmlhttp; }()), /* https://github.com/Titani/SO-ChatBot/blob/ccf6cfe827aee2af7b2832e48720a8e24a8feeed/source/bot.js#L110 */ urlstringify: (function() { var simplies = { 'number': true, 'string': true, 'boolean': true }; var singularStringify = function(thing) { if (typeof thing in simplies) { return encodeURIComponent(thing.toString()); } return ''; }; var arrayStringify = function(array, keyName) { keyName = singularStringify(keyName); return array.map(function(thing) { return keyName + '=' + singularStringify(thing); }); }; return function(obj) { return Object.keys(obj).map(function(key) { var val = obj[key]; if (Array.isArray(val)) { return arrayStringify(val, key); } else { return singularStringify(key) + '=' + singularStringify(val); } }).join('&amp;'); }; }()), post: function(options) { this.request.apply(this, ['POST', options]); }, get: function(options) { this.request.apply(this, ['GET', options]); }, request: function(type, options) { if (this.xmlhttp &amp;&amp; options &amp;&amp; 'url' in options) { var xhr = this.xmlhttp, enctype = ('enctype' in options) ? options.enctype : 'application/x-www-form-urlencoded'; xhr.open(type, options.url, true); xhr.setRequestHeader('Content-Type', enctype); xhr.onreadystatechange = function() { if (xhr.readyState == 4) { if (xhr.status == 200) { if ('success' in options &amp;&amp; options.success.apply) { options.success.apply(this, [xhr]); } } else if (xhr.status &amp;&amp; xhr.status != 200) { if ('failure' in options &amp;&amp; options.failure.apply) { options.failure.apply(this, [xhr]); } } } }; var data = null; if ('data' in options) { data = this.urlstringify.apply(this, [options.data]); } xhr.send(data); } } }; </code></pre> <p>For a barebones object; have I missed anything important? Should I change how any of this is organized or layed out? I have also tested in a limited number of browsers and so far so good! However I am unsure about older browsers and compatibility.</p> <p>Any input would be great! thanks!</p>
[]
[ { "body": "<p>Its interface might not be obvious enough for junior programmers in a hurry. I suppose there's some assistance in your README. Anyway the code is quite clear given a little experience or effort. It doesn't use exactly the subset of JavaScript that Douglas Crockford recommended in <em>JavaScript: The Good Parts</em>, but that doesn't always matter.</p>\n\n<p>I like this code. It has enough complexity for the real world without taking on responsibilities extraneous to wrapping XmlHttpRequest (or its equivalents). Nice use of closures. I really like that you incorporated a hyperlink to a line of github code that you found helpful.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-22T04:02:23.780", "Id": "10237", "ParentId": "10156", "Score": "1" } } ]
{ "AcceptedAnswerId": "10237", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-19T19:53:19.623", "Id": "10156", "Score": "3", "Tags": [ "javascript", "ajax" ], "Title": "Simple XmlHttpRequest object" }
10156
<p>Is this the easiest way to delete everything between and including the two first quotes (if present) in an <code>std::wstring</code>?</p> <pre><code>unsigned int firstQuotePos = logFileName.find_first_of(L"\""); unsigned int secondQuotePos = logFileName.find_first_of(L"\"", firstQuotePos + 1); if (firstQuotePos != std::wstring::npos &amp;&amp; secondQuotePos != std::wstring::npos) { logFileName = std::wstring(logFileName.begin(), logFileName.begin() + firstQuotePos) + std::wstring(logFileName.begin() + secondQuotePos + 1, logFileName.end()); } </code></pre>
[]
[ { "body": "<p>C++ is very picky about types.<br>\nYou should always try and use the correct ones:</p>\n\n<pre><code>unsigned int firstQuotePos = logFileName.find_first_of(L\"\\\"\");\nunsigned int secondQuotePos = logFileName.find_first_of(L\"\\\"\", firstQuotePos + 1);\n</code></pre>\n\n<p>should be:</p>\n\n<pre><code>std::string::size_type firstQuotePos = logFileName.find_first_of(L\"\\\"\");\nstd::string::size_type secondQuotePos = logFileName.find_first_of(L\"\\\"\", firstQuotePos + 1);\n</code></pre>\n\n<p>Next there is already an erase that does this:</p>\n\n<pre><code>if (firstQuotePos != std::string::npos)\n{\n logFileName.erase(firstQuotePos, (secondQuotePos - firstQuotePos));\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-19T21:49:32.277", "Id": "10164", "ParentId": "10157", "Score": "4" } } ]
{ "AcceptedAnswerId": "10164", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-19T20:10:28.053", "Id": "10157", "Score": "2", "Tags": [ "c++", "strings" ], "Title": "Deleting everything between two quotes in a string" }
10157
<p>I successfully created an expression evaluator in C#, and I would like to know if it works well, and what I can do to improve it.</p> <pre><code> class ExpressionEvaluator2 { public enum Token { None, Literal, Variable, Operator, Function, FunctionArgumentSeparator, LeftParanthesis, RightParanthesis }; private List&lt;KeyValuePair&lt;Token, string&gt;&gt; tokens = new List&lt;KeyValuePair&lt;Token, string&gt;&gt; (); private List&lt;KeyValuePair&lt;Token, string&gt;&gt; output = new List&lt;KeyValuePair&lt;Token, string&gt;&gt; (); private Dictionary&lt;string, double&gt; variables = new Dictionary&lt;string, double&gt;(); public List&lt;KeyValuePair&lt;Token, string&gt;&gt; Tokens { get { return tokens; } } public List&lt;KeyValuePair&lt;Token, string&gt;&gt; Output { get { return output; } } public Dictionary&lt;string, double&gt; Variables { get { return variables; } } public ExpressionEvaluator2() { Variables.Add("pi", Math.PI); Variables.Add("e", Math.E); } public string Expression { get; set; } public void Tokenize() { tokens.Clear(); for (int i = 0; i &lt; Expression.Length; i++) { if (char.IsWhiteSpace(Expression[i])) continue; if (IsOperator(Expression[i])) { // Unary minus if (Expression[i] == '-' &amp;&amp; (tokens.Count == 0 || tokens.Last().Key == Token.LeftParanthesis || tokens.Last().Key == Token.Operator)) tokens.Add(new KeyValuePair&lt;Token, string&gt;(Token.Operator, "!-")); // Any other operator else tokens.Add(new KeyValuePair&lt;Token, string&gt;(Token.Operator, Expression[i].ToString())); } else if (Expression[i] == '(') tokens.Add(new KeyValuePair&lt;Token, string&gt;(Token.LeftParanthesis, Expression[i].ToString())); else if (Expression[i] == ')') tokens.Add(new KeyValuePair&lt;Token, string&gt;(Token.RightParanthesis, Expression[i].ToString())); else if (Expression[i] == ',') tokens.Add(new KeyValuePair&lt;Token, string&gt;(Token.FunctionArgumentSeparator, Expression[i].ToString())); else if (Char.IsDigit(Expression[i])) tokens.Add(new KeyValuePair&lt;Token, string&gt;(Token.Literal, GetLiteral(Expression, ref i))); else if (Char.IsLetter(Expression[i])) { if (IsFunction(Expression, i)) tokens.Add(new KeyValuePair&lt;Token, string&gt;(Token.Function, GetVariable(Expression, ref i))); else tokens.Add(new KeyValuePair&lt;Token, string&gt;(Token.Variable, GetVariable(Expression, ref i))); } else throw new Exception("Unrecognized character found!"); } } public void ShuntingYard() { Stack&lt;KeyValuePair&lt;Token, string&gt;&gt; stack = new Stack&lt;KeyValuePair&lt;Token, string&gt;&gt;(); foreach (var i in Tokens) switch (i.Key) { case Token.Variable: case Token.Literal: output.Add(i); break; case Token.Function: stack.Push(i); break; case Token.FunctionArgumentSeparator: while (stack.Peek().Key != Token.LeftParanthesis) { output.Add(stack.Pop()); if (stack.Count == 0) throw new Exception("Syntax error!"); } break; case Token.Operator: if (IsLeftAssociative(i.Value)) { while (stack.Count != 0 &amp;&amp; Precedence(i.Value) &lt;= Precedence(stack.Peek().Value)) output.Add(stack.Pop()); } else { while (stack.Count != 0 &amp;&amp; Precedence(i.Value) &lt; Precedence(stack.Peek().Value)) output.Add(stack.Pop()); } stack.Push(i); break; case Token.LeftParanthesis: stack.Push(i); break; case Token.RightParanthesis: while (stack.Peek().Key != Token.LeftParanthesis) { output.Add(stack.Pop()); if (stack.Count == 0) throw new Exception("Mismatched parantheses!"); } stack.Pop(); // Pop paranthesis if (stack.Peek().Key == Token.Function) output.Add(stack.Pop()); // Pop function break; } while (stack.Count &gt; 0) { if (stack.Peek().Key == Token.LeftParanthesis) throw new Exception("Mismatched parantheses!"); output.Add(stack.Pop()); } } public double Evaluate() { Stack&lt;double&gt; stack = new Stack&lt;double&gt;(); foreach (var i in Output) switch (i.Key) { case Token.Variable: if (!Variables.ContainsKey(i.Value)) throw new Exception("Variable missing: " + i.Value); stack.Push(Variables[i.Value]); break; case Token.Literal: stack.Push(double.Parse(i.Value)); break; case Token.Operator: switch (i.Value) { case "!-": stack.Push(stack.Pop() * -1); break; case "+": stack.Push(stack.Pop() + stack.Pop()); break; case "-": { double b = stack.Pop(); double a = stack.Pop(); stack.Push(a - b); } break; case "*": stack.Push(stack.Pop() * stack.Pop()); break; case "/": { double b = stack.Pop(); double a = stack.Pop(); stack.Push(a / b); } break; case "%": { double b = stack.Pop(); double a = stack.Pop(); stack.Push(a % b); } break; case "^": { double b = stack.Pop(); double a = stack.Pop(); stack.Push(Math.Pow(a,b)); } break; } break; case Token.Function: EvaluateFunction(i.Value, ref stack); break; } return stack.Pop(); } void EvaluateFunction(string func, ref Stack&lt;double&gt; stack) { switch (func) { case "sin": stack.Push(Math.Sin(stack.Pop())); break; case "cos": stack.Push(Math.Cos(stack.Pop())); break; case "tan": stack.Push(Math.Tan(stack.Pop())); break; case "ctan": stack.Push(1 / Math.Tan(stack.Pop())); break; case "arcsin": stack.Push(Math.Asin(stack.Pop())); break; case "asin": stack.Push(Math.Asin(stack.Pop())); break; case "arccos": stack.Push(Math.Acos(stack.Pop())); break; case "acos": stack.Push(Math.Acos(stack.Pop())); break; case "arctan": stack.Push(Math.Atan(stack.Pop())); break; case "atan": stack.Push(Math.Atan(stack.Pop())); break; case "int": stack.Push(Math.Truncate(stack.Pop())); break; case "abs": stack.Push(Math.Abs(stack.Pop())); break; case "max": stack.Push(Math.Max(stack.Pop(), stack.Pop())); break; case "min": stack.Push(Math.Min(stack.Pop(), stack.Pop())); break; case "sqrt": stack.Push(Math.Sqrt(stack.Pop())); break; case "cbrt": stack.Push(Math.Pow(stack.Pop(), 1.0 / 3.0)); break; case "lg": stack.Push(Math.Log10(stack.Pop())); break; case "log": stack.Push(Math.Log(stack.Pop(), stack.Pop())); break; case "ln": stack.Push(Math.Log(stack.Pop(), Math.E)); break; default: throw new Exception("Unknown function " + func); } } #region Helper routines private static bool IsLeftAssociative (string op) { return (op != "^"); } private static int Precedence(string op) { switch (op) { case "+": case "-": return 1; case "*": case "/": case "%": return 2; case "^": return 3; case "!-": return 10; default: return 0; } } private static bool IsOperator(char c) { const string operators = "+-*/%^"; return operators.Contains(c); } private static bool IsFunction(string s, int index) { // Skip function/variable name while (index &lt; s.Length &amp;&amp; char.IsLetterOrDigit(s[index])) index++; while (index &lt; s.Length &amp;&amp; char.IsWhiteSpace(s[index])) index++; // End of string? Than it's a variable if (index &gt;= s.Length) return false; // If an operator, function separator, or ), variable if (s[index] == '(') return true; return false; } private static string GetVariable(string s, ref int index) { StringBuilder str = new StringBuilder(); while (index &lt; s.Length &amp;&amp; (char.IsLetterOrDigit(s[index]))) str.Append(s[index++]); index -= 1; return str.ToString(); } private static string GetLiteral(string s, ref int index) { StringBuilder str = new StringBuilder(); while (index &lt; s.Length &amp;&amp; (char.IsDigit(s[index]) || s[index] == '.')) str.Append (s[index++]); index -= 1; return str.ToString(); } #endregion } </code></pre> <p>To evaluate an expression, first the expression needs to be tokenized using the Tokenize method. After that, apply the ShuntingYard algorithm to prepare the expression. In the end, it can evaluate the expression (assuming you give values to all the input variables).</p> <p>I didn't manage to test it very thoroughly, and I don't even know how to test for large expressions that I can't calculate in my head.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-19T21:17:02.010", "Id": "16172", "Score": "0", "body": "A very quick minor thing is I would put braces around your else if statements in the Tokenize method." } ]
[ { "body": "<p>It is very inconvenient to force the client to call your methods in a very specific order. I would have a top level API that is easy to use. Have the API take care of all the grunt work for you. In the following example, take notice that I am using <code>decimal</code> instead of <code>double</code>. This will avoid precision errors that floating point numbers are prone to. </p>\n\n<pre><code>interface IEvaluator\n{\n void AddValue(string key, decimal value);\n void RemoveValue(string key);\n decimal Evaluate(string input);\n}\n</code></pre>\n\n<p>Just remember that you should hide things that are irrelevant to client code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-20T14:13:07.527", "Id": "16190", "Score": "0", "body": "Thanks, I will do it differently instead. Evaluate() also does the work of the other two functions that need to be called, but only if the expression code was change. Otherwise, just perform the evaluation. This is because I intend to use this class to evaluate an expression many times, with the variable changed." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-19T21:21:11.390", "Id": "10161", "ParentId": "10158", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-19T20:10:37.943", "Id": "10158", "Score": "3", "Tags": [ "c#", ".net", "parsing" ], "Title": "C# expression evaluator review request" }
10158
<pre><code>string Format(string format_string, T1 p1, T2 p2, ..., TN pn) </code></pre> <p>The <code>Format()</code> function takes a copy of <code>format_string</code> and replace occurrences of <code>"___"</code> with the remaining parameters to the function (<code>p1</code>, <code>p2</code>,...). The first occurrence of <code>"___"</code> will be replaced by <code>p1</code>, the next by <code>p2</code>, and so on. If there are no occurrences of <code>"___"</code> the remaining parameters will be appended to the string delimited by spaces. If the parameters are not strings they will be converted to strings with <code>operator&lt;&lt;(ostream,x)</code>. Format will return the modified string.</p> <p>For example:</p> <pre><code>Format("The ___ is ___ years", "fox", 8, "old") </code></pre> <p>evaluates to:</p> <blockquote> <p>"The fox is 8 years old"</p> </blockquote> <p>The implementation follows:</p> <pre><code>struct FormatEmptyStruct {}; const string FormatPlaceholder("___"); template&lt;class T&gt; inline FormatEmptyStruct OStreamWriteT(ostringstream&amp; os, const std::string&amp; sFormat, string::size_type&amp; iCurrentPos, const T&amp; t) { auto iNextPos = sFormat.find(FormatPlaceholder, iCurrentPos); if (iNextPos == std::string::npos) { os.write(sFormat.data() + iCurrentPos, sFormat.size() - iCurrentPos); iCurrentPos = sFormat.size(); os &lt;&lt; " "; os &lt;&lt; t; } else { os.write(sFormat.data() + iCurrentPos, iNextPos - iCurrentPos); os &lt;&lt; t; iCurrentPos = iNextPos + FormatPlaceholder.size(); } return {}; } struct EmptyStruct {}; inline string Format() { return ""; } template &lt;class... Args&gt; inline string Format(const string&amp; sFormat, const Args&amp;... args) { ostringstream os; string::size_type iCurrentPos = 0; initializer_list&lt;FormatEmptyStruct&gt;{ OStreamWriteT(os, sFormat, iCurrentPos, args)... }; if (!sFormat.empty()) os.write(&amp;sFormat.front() + iCurrentPos, sFormat.size() - iCurrentPos); return os.str(); } </code></pre>
[]
[ { "body": "<p>I can't fault the code (assuming it works). Looks good.</p>\n\n<p>But what I would point is that to improve flexibility you should probably use numbered replacement sites.</p>\n\n<p>The problem with format strings is that for I18N and L10N the format strings will be pulled out of the source code and placed in a separate resource file for translation. Unfortunately not all languages use the same noun verb ordering so for I18N to work efficiently you need a flexible placement strategy (so that you only need to change the string resource not the code).</p>\n\n<p>English:</p>\n\n<pre><code>// \"The disk named MyDisk contains 300 files.\"\n\"The disk named %1 contains %2 files\" % DiskName % FileCount;\n</code></pre>\n\n<p>Basque:</p>\n\n<pre><code>// \"300 fitxategi ditu, izendatutako MyDisk diskoa.\"\n\"%2 fitxategi ditu, izendatutako %1 diskoa.\" % DiskName % FileCount;\n</code></pre>\n\n<p>Or in your code:</p>\n\n<pre><code>std::cout &lt;&lt; Format(stringresource.get(\"DiskString\"), DiskName, FileCount) &lt;&lt; std::endl;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-20T04:08:13.460", "Id": "10168", "ParentId": "10163", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-19T21:37:56.377", "Id": "10163", "Score": "1", "Tags": [ "c++", "strings", "c++11", "formatting" ], "Title": "String format function" }
10163
<p>I am stuck with some old API that involves COM and ODBC, and I cannot switch to cool things like MEF or entity framework. So, I am working on some wrappers that will help me write less code and also bring some of the type safety back (as you know, COM and SQL do not have type safety, at least not in the same way as C# does).</p> <p>The goal is that I want to be able to write things like</p> <pre><code>int? orderId = sqlHelper.GetOrderId(...some arguments that will help the where clause...) </code></pre> <p>and</p> <pre><code>List&lt;int&gt; goodOrderIds = sqlHelper.GetGoodOrderIds(...) </code></pre> <p>and</p> <pre><code>List&lt;int?&gt; orderId = activeReport.GetGoodSelectedOrderIds() </code></pre> <p>where <code>activeReport</code> is a home-brewed GUI grid, which may or may not have a column named <code>order_id</code>, and if it does, then some rows of the GUI report may still have null values. </p> <p>Here is an extension class for the GUI report. I have two TODO comments that I would like you to address:</p> <pre><code>public static class ReportExtensions { public static IList&lt;object&gt; GetSelectedFieldValues(this Report activeReport, string fieldName) { // Implementation hidden. May return at least some null values. return result; } public static IList&lt;T&gt; GetSelectedFieldValues&lt;T&gt;(this Report activeReport, string fieldName) where T : struct, IConvertible { // This smells like a maybe monad; I wish I got Haskell. // TODO: See if this can be simplified. return activeReport.GetSelectedFieldValues(fieldName) .Select(value =&gt; GenericConverter.To&lt;T&gt;(value)) .Where(nullable =&gt; nullable.HasValue) .Select(nullable =&gt; nullable.Value) .ToList(); } public static IList&lt;string&gt; GetSelectedStringFields(this Report activeReport, string fieldName) { // TODO: Is this LINQ query in its simplest form? return activeReport.GetSelectedFieldValues(fieldName) .Select(value =&gt; GenericConverter.ToString(value)) .Where(str =&gt; str != null) .ToList(); } } </code></pre> <p>And here is my <code>GenericConverter</code> class, which allows converting an object to a given simple type, if it can. I introduced the <code>private static IConvertible ConvertTo&lt;T&gt;(object value)</code> method in order to appease the compiler. As I understand, generic types can be restricted to some interface or a subclass in a hierarchy, but I do not think I can say something like</p> <blockquote> <p>where <code>T</code> in (<code>int</code>, <code>short</code>, ... <code>double</code>, <code>DateTime</code>, <code>string</code>), which is what I would ultimately like to do, if I could. One alternative would be to create my own <code>NullableConvert</code> class and implement methods such as <code>decimal?</code>ToDecimal(object value)`</p> </blockquote> <p>but I do not like having to type all that stuff in. For instance, having to return null on cast failure would require a <code>try</code>/<code>catch</code> or other code inside the body of every method.</p> <pre><code>/// &lt;summary&gt; /// This class helps to convert from any object to an IConvertible if possible. /// This is convinient to use with the SqlHelper, ReportHelper class. /// This class does not convert everything imaginable, but it does support the "standard" IConvertible. /// &lt;/summary&gt; public static class GenericConverter { public static bool IsNullValue(object value) { return (value == null || value == DBNull.Value); } public static string ToString(object value) { if (IsNullValue(value)) { return null; } return Convert.ToString(value); } public static T? To&lt;T&gt;(object value) where T : struct, IConvertible { var result = ConvertTo&lt;T&gt;(value); if (result == null) { return null; } return (T)result; } // http://msdn.microsoft.com/en-us/library/system.iconvertible.aspx // Boolean, SByte, Byte, Int16, UInt16, Int32, UInt32, Int64, UInt64, Single, Double, Decimal, DateTime, Char private static IConvertible ConvertTo&lt;T&gt;(object value, bool nullOnCastException = false) where T : struct, IConvertible { if (IsNullValue(value)) { return null; } try { if (typeof(T) == typeof(bool)) { return Convert.ToBoolean(value); } if (typeof(T) == typeof(sbyte)) { return Convert.ToSByte(value); } if (typeof(T) == typeof(byte)) { return Convert.ToByte(value); } if (typeof(T) == typeof(char)) { return Convert.ToChar(value); } if (typeof(T) == typeof(short)) { return Convert.ToInt16(value); } if (typeof(T) == typeof(ushort)) { return Convert.ToUInt16(value); } if (typeof(T) == typeof(int)) { return Convert.ToInt32(value); } if (typeof(T) == typeof(uint)) { return Convert.ToUInt32(value); } if (typeof(T) == typeof(long)) { return Convert.ToInt64(value); } if (typeof(T) == typeof(ulong)) { return Convert.ToUInt64(value); } if (typeof(T) == typeof(float)) { return Convert.ToSingle(value); } if (typeof(T) == typeof(double)) { return Convert.ToDouble(value); } if (typeof(T) == typeof(decimal)) { return Convert.ToDecimal(value); } if (typeof(T) == typeof(DateTime)) { return Convert.ToDateTime(value); } // I never trully intended to work with everything that implements IConvertible. // I just wanted string fromTypeName = value.GetType().FullName; string toTypeName = typeof(T).FullName; string exceptionMessage = String.Format( "Unable to convert a value '{0}' of type '{1}' to type '{2}'.", value, fromTypeName, toTypeName); throw new InvalidCastException(message: exceptionMessage); } catch // Perhaps restrict these only to the exception types that pertain to casting only. How do I find the exhaustive list though? C# does not have "checked exceptions" like Java does. { if (nullOnCastException) { return null; } throw; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-20T04:44:01.340", "Id": "16180", "Score": "0", "body": "For sql at least look at MicroORMs like Dapper and Massive. I have used Dapper on a multi-month project and was very happy. Not the end-all be-all but really very nice for most of the time." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-20T18:22:35.377", "Id": "16200", "Score": "0", "body": "@George Mauer, do you know one that works specifically with an ODBC source?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-20T18:37:30.823", "Id": "16204", "Score": "0", "body": "Here's the entire source code of dapper: https://github.com/SamSaffron/dapper-dot-net/blob/master/Dapper/SqlMapper.cs it is about 2200 well documented lines and on a scan I don't see anything that ties it to a particular data source. Even if it does, it's small enough that you should be able to just grab it and make a few modifications to get it working. At the very least you can steal some of their ideas." } ]
[ { "body": "<p>I believe you can shorten this by using <a href=\"http://msdn.microsoft.com/en-us/library/dtb69x08.aspx\" rel=\"nofollow\">Convert.ChangeType</a>. Also I altered your catch to handle only <code>InvalidCastException</code> since the name of your <code>bool</code> argument is quite specific. You may want to consider how you'll handle <code>FormatException</code> and <code>OverflowException</code>.</p>\n\n<pre><code>private static IConvertible ConvertTo&lt;T&gt;(object value, bool nullOnCastException = false)\n where T : struct, IConvertible\n{\n if (IsNullValue(value))\n {\n return null;\n }\n\n try\n {\n return (T)Convert.ChangeType(value, typeof(T));\n }\n catch (InvalidCastException)\n {\n if (nullOnCastException)\n {\n return null;\n }\n\n throw;\n }\n}\n</code></pre>\n\n<p>}</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-20T00:43:37.753", "Id": "10166", "ParentId": "10165", "Score": "2" } } ]
{ "AcceptedAnswerId": "10166", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-20T00:16:41.120", "Id": "10165", "Score": "1", "Tags": [ "c#", "linq", "converting" ], "Title": "Using strong types on top of COM and ODBC" }
10165
<p>Just wondering if there was someone out there that could offer help in optimizing my script which "derpifies" images.</p> <pre><code>&lt;?php /** * If you don't understand what this does * you have no hope as a programmer. * */ function usage ( ) { // Ahhh the marvels of echo, such a wonderful tool // yet so advanced that a beginner will tremble at the // word. Woe's me is spoken to the RAM with such care. echo "\n"; echo "----------------------------\n"; echo "&gt; Derp.PHP is a CLI based \n"; echo "&gt; image derpification tool. \n"; echo "&gt; Use only with: \n"; echo "&gt; jpeg, gif, or png files \n"; echo "&gt; \n"; echo "&gt; Usage: \n"; echo "&gt; derp.php path/to/file \n"; echo "----------------------------\n"; echo "\n"; } /** * In this function we make sure the end user isn't * a total moran by checking weather we have access * to certain hacker libraries. * **/ function make_checks ( ) { # A beautiful built_in function that is necessary to # this programs inherited existence, such a lovely sight. if ( !function_exists('imagecopy') ) { // Here we throw an error if we encounter a stupid user. // &gt;2012 // &gt;Not having GD installed. // // ISHYGDDT. echo "\n"; echo "&gt;&gt;&gt; ERROR &lt;&lt;&lt;\n"; echo "&gt;&gt;&gt; INSTALL THE GD LIBRARY\n"; echo "\n"; /* This is a boolean return. False essentially means 0; TMYK. */ return false; } else return true; # Note the lack of curly brackets around this # line of code. Amazing technology these days. } /** * Stand back kiddies, this is how a real * programmer does things. * **/ function main ( $argv ) { // Enterprise usage of the count() function // is demonstrated here, take note of the // combined &lt; and = symbol here, only a master // programmer could have achieved such an // operater without R(ing)TFM. if ( count($argv) &lt;= 1 ) { // An excellent call to an undoubtedly elegant // and not to mention genius display function. usage(); exit; # Notice the multiple comment types in this file. # The mark of a true programming genius. } // Simple and elegant usage of the master make_checks() // library checking function, what would be referred to // by a Java programmer as a Factory(lmfao Java). if ( !make_checks() ) exit; # Sweet succulent success. NOT(lmfao!1)! // The file to be derpafied. $file = $argv[1]; # Only the technologically independent and savvy programmer # will be able to truly understand the genius of the below # statement; one that even William Shakespear could not have # written better. $type = ( substr($file, -4, 1) !== '.' ) // Can you see? ? substr($file, -4) // Can you see my genius. : substr($file, -3) // It's shining... ; // oh so bright. What a marvelous function, I // couldn't have done it better myself. Oh, wait. echo $type, "\n"; } main( $argv ); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-20T07:28:13.740", "Id": "16183", "Score": "38", "body": "You're not funny. :) Oh, and `echo pathinfo($file)['extension']; // PHP 5.4`" } ]
[ { "body": "<pre><code>sed 's/\\(\\/\\/\\|#\\).*$//g' YOUR_FILENAME | sed '/^$/N;/^\\s*$/D'\n</code></pre>\n\n<p>To clarify, that strips comments and multiple blank lines. Generally comments are a good idea. I would not remove them or create shorter names for functions and variables for performance. Any benefit there is minuscule beyond belief. Your comments trolled me into giving that answer, seriously though: <strong>remove your comments</strong>.</p>\n\n<h2>Ignoring the Comments - some real recommendations</h2>\n\n<p>Consistency makes things easier to read.</p>\n\n<ol>\n<li>Work out your maximum line length and use it (especially for the comments).</li>\n<li>Stop trolling me with mixed brace styles in <code>if</code>/<code>else</code> statements.</li>\n</ol>\n\n<p><code>make_checks</code> is not a very descriptive name for a function. It would be better as <code>check_libraries</code>.</p>\n\n<p>Now, the bit of your code that actually does something:</p>\n\n<pre><code>$type = ( substr($file, -4, 1) !== '.' ) // Can you see?\n ? substr($file, -4) // Can you see my genius.\n : substr($file, -3) // It's shining...\n ; // oh so bright. What a marvelous function, I\n // couldn't have done it better myself. Oh, wait.\n</code></pre>\n\n<p>Should be rewritten:</p>\n\n<pre><code>$type = pathinfo($file, PATHINFO_EXTENSION);\n</code></pre>\n\n<p>In fact, the variables <code>$file</code> and <code>$type</code> are only used once (and hence shouldn't even be variables).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-14T01:10:22.310", "Id": "71527", "Score": "13", "body": "Hmm, it looks like you are a PHP guru. We could use one of your kind in our [chat room](http://chat.stackexchange.com/rooms/8595/the-2nd-monitor). ;)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-20T04:30:58.393", "Id": "10169", "ParentId": "10167", "Score": "50" } }, { "body": "<p>This script is a total of 99 lines. Of that, 49 lines are insulting, annoying, and ironic self-congratulating comments. </p>\n\n<p>In general, comments are good. They help any future maintainer (including yourself when it's been 6 months since the last time you looked at the script) to understand what the code does because programmer time is extraordinarily valuable. Programmer time should be spent fixing the code--not trying to understand it, and helpful comments go a long way toward cutting down on the \"trying to understand it\" part of the program.</p>\n\n<p>These comments are not funny, at least not in a \"laughing with you\" sort of way. And they are not constructive. And perhaps worst of all, they're not even consistent.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>/**\n * In this function we make sure the end user isn't\n * a total moran by checking weather we have access\n * to certain hacker libraries.\n *\n **/\n</code></pre>\n</blockquote>\n\n<p>Here, we accuse the user of being a \"moran\" by checking the \"weather\" or something (though the function doesn't at all appear to be accessing any sort of weather web service). This comment might be better written as:</p>\n\n<pre><code>// Determine whether necessary libraries exist\n</code></pre>\n\n<p>This removes the misspellings and still accurately describes in plain-English what the goal of the function is.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>// Here we throw an error if we encounter a stupid user.\n// &gt;2012\n// &gt;Not having GD installed.\n//\n// ISHYGDDT.\n</code></pre>\n</blockquote>\n\n<p>As a note from someone who has plenty of experience dealing with users, your best bet is to program for the lowest common denominator. A \"stupid\" user is still a user, and if you're not capable of writing programs that \"stupid\" users can use, then perhaps it is you who has no hope as a programmer.</p>\n\n<p>This comment might be better written as:</p>\n\n<pre><code>// Alert the user that a necessary library is missing\n</code></pre>\n\n<p>I'd also argue that including some instructions on how to install the missing library would probably be helpful in your <code>echo</code> statements.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>/**\n * Stand back kiddies, this is how a real\n * programmer does things.\n *\n **/\n</code></pre>\n</blockquote>\n\n<p>This comment is completely unhelpful and can be completely removed.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> // Enterprise usage of the count() function\n // is demonstrated here, take note of the\n // combined &lt; and = symbol here, only a master\n // programmer could have achieved such an\n // operater without R(ing)TFM.\n</code></pre>\n</blockquote>\n\n<p>As a programmer, you have 3 options.</p>\n\n<p>The first option is to develop your own programming language and write the manual for it, and then you don't have to read the manual. This is PHP; you didn't create it, so you're going to fall into one of the other two categories.</p>\n\n<p>The second option is to read the manual. This is what the master programmers do. Manuals are boring and hard to read, but if you want to make the most out of a given programming language, you have to be familiar with the documentation for that language or... fall into the third category...</p>\n\n<p>The third option is learning from other programmers who already read the manual, and while you could still be a \"master\" programmer and be in this category, you're no more \"master\" than those from whom you learn.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> # Only the technologically independent and savvy programmer\n # will be able to truly understand the genius of the below\n # statement; one that even William Shakespear could not have\n # written better.\n</code></pre>\n</blockquote>\n\n<p>Once again, another misspelling in the midst of self-congratulating the genius of a programmer who can't even spell-check.</p>\n\n<p>The irony of this comment is astounding.</p>\n\n<p>Let's first of all ignore the fact that you misspelled Shakespeare and ignore the fact that he was a playwright, not a programmer, so if you can't write code better than him, again, you're probably the one who has no hope at a programmer.</p>\n\n<p>Instead, let's look at the comment which introduces a somewhat confusing ternary statement. The whole point of comments, again, is to make code more readable. Although, a true master programmer writes the executable code in a highly readable way as a starting point, and only needs comments to explain the bits of code that can't easily be written in a highly readable manner.</p>\n\n<p>There's nothing that impressive about the ternary statement--it's certainly not worthy of self-congratulation. However, it'd be my guess that there's a better way of doing this in PHP (though I'm no PHP master, so maybe not). But if we feel the ternary statement is not so obvious to the average reader of our source code that a comment is necessary, then the appropriate sort of comment would be to clarify what the code is actually doing. Something more along the lines of this:</p>\n\n<pre><code>// Grabs the file extension\n</code></pre>\n\n<p>Also, by the way...</p>\n\n<blockquote>\n<pre><code>// oh so bright. What a marvelous function\n</code></pre>\n</blockquote>\n\n<p>It's not a function. It's an operator. It's called the ternary operator. The fact that it's called a ternary operator is something you could learn by reading the documentation.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-19T00:13:48.727", "Id": "60435", "ParentId": "10167", "Score": "91" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-20T03:24:47.490", "Id": "10167", "Score": "-50", "Tags": [ "php", "performance" ], "Title": "Derpifying Images" }
10167
<p>For more information, see <a href="http://cakephp.org" rel="nofollow">http://cakephp.org</a>.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-20T07:58:23.423", "Id": "10171", "Score": "0", "Tags": null, "Title": null }
10171
CakePHP is a rapid development framework for PHP that provides an extensible architecture for developing, maintaining, and deploying applications. It uses commonly known design patterns like MVC and ORM within the convention over configuration paradigm.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-20T07:58:23.423", "Id": "10172", "Score": "0", "Tags": null, "Title": null }
10172
<p>This is a very simple nested property extractor. I wonder if it can be optimised further?</p> <pre><code>/** * Extract nested property from object. If nested property cannot be reached, return value of rescue * @param obj Object * @param path Can be dot-separated string or array * @param rescue (optional) default value. Defaults to null */ function extract(obj, path, rescue){ if (typeof obj === "object" &amp;&amp; path){ var elements = typeof path === "string" ? path.split(".") : path; if (typeof elements.shift === "function"){ var head = elements.shift(); if (obj.hasOwnProperty(head)){ return (elements.length === 0) ? obj[head] : extract(obj[head], elements, rescue); } // if } // if } // if return rescue || null; } // extract var noob = {k1 : {k11 : {k111 : "v1"}}, k2 : { k21 : "v2"}}; console.log(extract(noob, 'k1.k11')); // {k111 : "v1"} console.log(extract(noob, 'k1.k11.k111')); // v1 console.log(extract(noob, ['k1', 'k11', 'k111'])); // v1 console.log(extract(noob, 'k1.k11.kx')); // null console.log(extract(noob, 'k2')); // k2 : { k21 : "v2"} console.log(extract(noob, 'k2.k21.k22')); // null console.log(extract(noob, 'k1.k11.k22', "ZUT")); // ZUT console.log(extract(noob, '', "ZUT")); // ZUT console.log(extract(false, '', "ZUT")); // ZUT </code></pre> <p>โ€‹</p>
[]
[ { "body": "<p>Here are some of my thoughts:</p>\n\n<ul>\n<li>I don't see the point in providing the path as a dot separated string, but it may be useful in your application. </li>\n<li>If you keep the dot separated string, then you should consider extracting the recursive function into a separate internal function, so that you don't have to repeat the check of the path argument in each iteration. </li>\n<li>Why do you check for the <code>shift</code> method? If it doesn't exist, then your function will fail silently. The regular \"method does not exist\" exception would be much more useful. Instead implement the method on the <code>Array.prototype</code> yourself separately if it doesn't exist. </li>\n<li>Finally I would move the <code>path.length == 0</code> to the start of the function. That is where the break condition of recursive functions are usually expected. </li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-20T21:27:45.353", "Id": "16217", "Score": "0", "body": "I check for shift method to avoid TypeError and return rescue value in case if path is meaningless. And path as a string is merely syntactic sugar." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-21T08:23:14.110", "Id": "16229", "Score": "0", "body": "@ts01 But it's not really useful to get the rescue value, if `shift` doesn't exist (or is the wrong type). It would be much better to A) clearly document that it's required and B) throw an exception. Alternatively you should either implement it yourself, if it's so important, or avoid using it all." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-21T08:28:50.063", "Id": "16230", "Score": "0", "body": "@seand Thanks for the edit. I wrote that on my phone which doesn't allow me to enter the backtick." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-20T16:32:18.930", "Id": "10187", "ParentId": "10176", "Score": "4" } }, { "body": "<p>RoToRa is absolutely correct. A few other considerations:</p>\n\n<ul>\n<li><p>A dot is a valid property name part. Whatcha gonna do when:</p>\n\n<p>var x = {};\nx[\"blah.blam\"] = \"bloo\";</p></li>\n<li><p>Why are you checking hasOwnProperty? This would exclude any usage of prototype inheritance.</p></li>\n</ul>\n\n<p>For the above reasons I would recommend against using this as a general utility function. However, if this is going to be a specific utility (for example you're trying to create a simple data-binding framework where you know you won't have to worry about the above) this might be the rare legitimate use of the controversial <a href=\"https://developer.mozilla.org/en/JavaScript/Reference/Statements/with\" rel=\"nofollow\">with statement</a>.</p>\n\n<pre><code>var x = {\n blah: {\n blam: \"bloo\"\n }\n}\nwith(x) {\n console.log(blah)\n}\nwith(x){\n console.log(blah.blam)\n}\n</code></pre>\n\n<p>To take you the rest of the way you use the even more maligned <code>eval</code>:</p>\n\n<pre><code>var extract = function(obj, path, rescue){\n with(obj) {\n return eval(path) || rescue;\n }\n}\n</code></pre>\n\n<p>Yes this doesn't do all the type checks that you do above but why do you need them? </p>\n\n<p>Now let me be clear</p>\n\n<h2>It is possible to expose an XSS vulnerability for your users here</h2>\n\n<p>Specifically if you allow users to enter values which are posted back, persisted on the server, downloaded by other users, and then used with this function on their computers.</p>\n\n<p>Suppose you are doing binding to objects which users can customize. These can be arbitrarily nested so you use this pattern. You also have summary screens in which users can view other users' customizations.</p>\n\n<p>All an attacker has to do is create a property named <code>some javascript code that steals browser information</code> and it will be eval'ed and run on the machines of other users of the system.</p>\n\n<p>That's the danger. If you're aware of it and make sure that condition never happens, feel free to use the with-eval.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-20T17:31:10.190", "Id": "10190", "ParentId": "10176", "Score": "3" } }, { "body": "<p>As suggested by others, the string approach with dot-separated properties can be ambigious. I present an alternative using lambda functions. It chains property extraction from inner objects, until a property can no longer be retrieved, in which case the default value is returned. It also performs an early exit earlier than the initial code.</p>\n\n<pre><code>function extract (source, selectors, defaultValue) {\n if (source == undefined || selectors == undefined) {\n return defaultValue;\n }\n if (!Array.isArray(selectors)) {\n selectors = [ selectors ];\n }\n let value = source;\n for (const i in selectors) {\n try {\n value = selectors[i](value);\n } catch {\n value = defaultValue;\n break;\n }\n }\n return value;\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>const data = {\n inner: {\n message: 'Hello world',\n }\n}\n\n// 'Hello world'\nvar prop1 = extract(data, [\n obj =&gt; obj.inner\n , obj =&gt; obj.message\n ], 'not found');\n\n// 'not found'\nvar prop2 = extract(data, [\n obj =&gt; obj.unknownpropname\n , obj =&gt; obj.message\n ], 'not found');\n</code></pre>\n\n<p>Your example reworked:</p>\n\n<pre><code>var noob = {k1 : {k11 : {k111 : \"v1\"}}, k2 : { k21 : \"v2\"}};\n\n// 'v1'\nvar prop = extract(noob, [obj =&gt; obj.k1, obj =&gt; obj.k11, obj =&gt; obj.k111 ], 'not found');\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T08:32:17.427", "Id": "226370", "ParentId": "10176", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2012-03-20T09:14:05.807", "Id": "10176", "Score": "5", "Tags": [ "javascript", "recursion", "properties" ], "Title": "javascript property extractor optimisation" }
10176
<p>This is intended to be part of a generalised solution to the problem of converting any (with some minor restrictions) CSV content into XML. The restrictions on the CSV, and the purpose of the schema should be apparent from the annotations.</p> <p>The main review criteria I request are:</p> <ol> <li>Is it suitable for non-destructive round-trip transformations from .csv to .xml and back again to .csv?</li> <li>Is the schema clear and readable enough?</li> <li>Is there a simpler way to do the same thing?</li> <li>Are there any obvious errors?</li> </ol> <p>This schema, as well as associated XSLT style-sheets, when polished, will be put to good use in the public domain with a creative commons license.</p> <p>Here is the schema to be reviewed: </p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xcsv="http://seanbdurkin.id.au/xslt/xcsv.xsd" elementFormDefault="qualified" targetNamespace="http://seanbdurkin.id.au/xslt/xcsv.xsd" version="1.0"&gt; &lt;xs:import namespace="http://www.w3.org/XML/1998/namespace" schemaLocation="xml.xsd"/&gt; &lt;xs:element name="comma-separated-single-line-values"&gt; &lt;xs:annotation&gt;&lt;xs:documentation xml:lang="en"&gt; This schema describes an XML representation of a subset of csv content. The format described by this schema, here-after referred to as "xcsv" is part of a generalised solution to the problem of converting general csv files into suitable XML, and the reverse transform. The restrictions on the csv content are: * The csv file is encoded either in UTF-8 or UTF16. If UTF-16, a BOM is required. * The cell values of the csv may not contain the CR or LF characters. Essentially, we are restricted to single-line values. The xcsv format was developed by Sean B. Durkin&amp;#x85; www.seanbdurkin.id.au &lt;/xs:documentation&gt;&lt;/xs:annotation&gt; &lt;xs:complexType&gt; &lt;xs:sequence&gt; &lt;xs:element ref="xcsv:notice" minOccurs="0" maxOccurs="1"/&gt; &lt;xs:element name="row" minOccurs="0" maxOccurs="unbounded"&gt; &lt;xs:annotation&gt;&lt;xs:documentation xml:lang="en"&gt; A row element represents a "row" or "line" in the csv file. Rows contain values. &lt;/xs:documentation&gt; &lt;xs:appinfo&gt; &lt;example&gt; &lt;csv-line&gt;apple,"banana","red, white and blue","quote this("")"&lt;/csv-line&gt; &lt;row&gt; &lt;value&gt;apple&lt;/value&gt; &lt;value&gt;banana&lt;/value&gt; &lt;value&gt;red, white and blue&lt;/value&gt; &lt;value&gt;quote this(")&lt;/value&gt; &lt;/row&gt; &lt;/example&gt; &lt;/xs:appinfo&gt; &lt;/xs:annotation&gt; &lt;xs:choice minOccurs="1" maxOccurs="unbounded"&gt; &lt;xs:annotation&gt;&lt;xs:documentation xml:lang="en"&gt; Empty rows are not possible in csv. We must have at least one value or one error. &lt;/xs:documentation&gt;&lt;/xs:annotation&gt; &lt;xs:element name="value"&gt; &lt;xs:annotation&gt;&lt;xs:documentation xml:lang="en"&gt; A value element represents a decoded (model) csv "value" or "cell". If the encoded value in the lexical csv was of a quoted form, then the element content here is the decoded or model form. In other words, the delimiting double-quote marks are striped out and the internal escaped double-quotes are de-escaped. &lt;/xs:documentation&gt;&lt;/xs:annotation&gt; &lt;xs:simpleType&gt; &lt;xs:restriction base="xs:string"&gt; &lt;xs:pattern value="[^\n]*"/&gt; &lt;xs:whiteSpace value="preserve"/&gt; &lt;xs:annotation&gt;&lt;xs:documentation xml:lang="en"&gt; Cell values must fit this pattern because of the single-line restriction that we placed on the csv values. &lt;/xs:documentation&gt;&lt;/xs:annotation&gt; &lt;/xs:restriction&gt; &lt;/xs:simpleType&gt; &lt;/xs:element&gt; &lt;xs:group ref="xcsv:errorGroup"&gt; &lt;xs:annotation&gt;&lt;xs:documentation xml:lang="en"&gt; An error can be recorded here as a child of row, if there was an encoding error in the csv for that row. &lt;/xs:documentation&gt;&lt;/xs:annotation&gt; &lt;/xs:group&gt; &lt;/xs:choice&gt; &lt;/xs:element&gt; &lt;xs:group ref="xcsv:errorGroup"&gt; &lt;xs:annotation&gt;&lt;xs:documentation xml:lang="en"&gt; An error can be recorded here as a child of the comma-separated-values element, if there was an i/o error in the transformational process. For example: CSV file not found. &lt;/xs:documentation&gt;&lt;/xs:annotation&gt; &lt;/xs:group&gt; &lt;/xs:sequence&gt; &lt;xs:attribute name="xcsv-version" type="xs:decimal" fixed="1.0" use="required"/&gt; &lt;/xs:complexType&gt; &lt;/xs:element&gt; &lt;xs:element name="comma-separated-multiline-values"&gt; &lt;xs:annotation&gt;&lt;xs:documentation xml:lang="en"&gt; Similar to xcsv:comma-separated-multi-line-values but allows multi-line values. &lt;/xs:documentation&gt;&lt;/xs:annotation&gt; &lt;xs:complexType&gt; &lt;xs:sequence&gt; &lt;xs:element ref="xcsv:notice" minOccurs="0" maxOccurs="1"/&gt; &lt;xs:element name="row" minOccurs="0" maxOccurs="unbounded"&gt; &lt;xs:choice minOccurs="1" maxOccurs="unbounded"&gt; &lt;xs:element name="value"&gt; &lt;xs:simpleType&gt; &lt;xs:restriction base="xs:string"&gt; &lt;xs:whiteSpace value="preserve"/&gt; &lt;/xs:restriction&gt; &lt;/xs:simpleType&gt; &lt;/xs:element&gt; &lt;xs:group ref="xcsv:errorGroup"&gt; &lt;/xs:group&gt; &lt;/xs:choice&gt; &lt;/xs:element&gt; &lt;xs:group ref="xcsv:errorGroup"&gt; &lt;/xs:group&gt; &lt;/xs:sequence&gt; &lt;xs:attribute name="xcsv-version" type="xs:decimal" fixed="1.0" use="required"/&gt; &lt;/xs:complexType&gt; &lt;/xs:element&gt; &lt;xs:element name="notice" type="xcsv:notice-en" /&gt; &lt;xs:annotation&gt;&lt;xs:documentation xml:lang="en"&gt; This is an optional element below comma-separated-single-line-values or comma-separated-multiline-values that looks like the example. &lt;/xs:documentation&gt; &lt;xs:appinfo&gt; &lt;example&gt; &lt;notice xml:lang="en"&gt;The xcsv format was developed by Sean B. Durkin&amp;#x85;www.seanbdurkin.id.au&lt;/notice&gt; &lt;/example&gt; &lt;/xs:appinfo&gt;&lt;/xs:annotation&gt; &lt;xs:complexType name="notice-en"&gt; &lt;xs:simpleContent&gt; &lt;xs:extension base="xcsv:notice-content-en"&gt; &lt;xs:attribute ref="xml:lang" use="required" fixed="en" /&gt; &lt;/xs:extension&gt; &lt;/xs:simpleContent&gt; &lt;/xs:complexType&gt; &lt;xs:simpleType name="notice-content-en"&gt; &lt;xs:restriction base="xs:string"&gt; &lt;xs:enumeration value="The xcsv format was developed by Sean B. Durkin&amp;#x85;www.seanbdurkin.id.au"/&gt; &lt;/xs:restriction&gt; &lt;/xs:simpleType&gt; &lt;xs:element /&gt; &lt;xs:group name="errorGroup"&gt; &lt;xs:annotation&gt;&lt;xs:documentation xml:lang="en"&gt; This is an error node/message in one or more languages. &lt;/xs:documentation&gt; &lt;xs:appinfo&gt; &lt;example&gt; &lt;error error-code="2"&gt; &lt;message xml:lang="en"&gt;Quoted value not terminated.&lt;/message&gt; &lt;message xml:lang="ru"&gt;ะฆะธั‚ะธั€ัƒะตั‚ัั ะทะฝะฐั‡ะตะฝะธะต ะฝะต ะฟั€ะตะบั€ะฐั‰ะฐะตั‚ัั.&lt;/message&gt; &lt;error-data&gt;"&lt;/error-data&gt; &lt;/error&gt; &lt;/example&gt; &lt;example&gt; &lt;error error-code="3"&gt; &lt;message xml:lang="en"&gt;Quoted value incorrectly terminated.&lt;/message&gt; &lt;message xml:lang="ru"&gt;ะฆะธั‚ะธั€ัƒะตั‚ัั ะทะฝะฐั‡ะตะฝะธะต ะฝะตะฟั€ะฐะฒะธะปัŒะฝะพ ะฟั€ะตะบั€ะฐั‰ะตะฝะพ.&lt;/message&gt; &lt;/error&gt; &lt;/example&gt; &lt;/xs:appinfo&gt; &lt;/xs:annotation&gt; &lt;xs:element name="error"&gt; &lt;xs:element name="message" minOccurs="1" maxOccurs="unbounded" type="xcsv:string-with-lang" /&gt; &lt;xs:annotation&gt;&lt;xs:documentation xml:lang="en"&gt; Although there can be multiple messages, there should only be at most one per language. &lt;/xs:documentation&gt;&lt;/xs:annotation&gt; &lt;xs:element name="error-data" minOccurs="0" maxOccurs="1" &gt; &lt;xs:simpleContent&gt; &lt;xs:restriction base="xs:string"&gt; &lt;xs:whiteSpace value="preserve"/&gt; &lt;/xs:restriction&gt; &lt;/xs:simpleContent&gt; &lt;/xs:element&gt; &lt;xs:attribute name="error-code" type="xs:positiveInteger" default="1" /&gt; &lt;xs:annotation&gt;&lt;xs:documentation xml:lang="en"&gt; Each different kind of error should be associated with a unique error code. A map for the error codes is outside the scope of this schema, except to say the following: * one (1) means a general or uncategorised error. (Try to avoid this!) &lt;/xs:documentation&gt;&lt;/xs:annotation&gt; &lt;/xs:element&gt; &lt;/xs:group&gt; &lt;xs:complexType name="string-with-lang"&gt; &lt;xs:annotation&gt;&lt;xs:documentation xml:lang="en"&gt; This is an element with text content in some language as indicated by the xml:lang attribute. &lt;/xs:documentation&gt;&lt;/xs:annotation&gt; &lt;xs:simpleContent&gt; &lt;xs:extension base="xs:string"&gt; &lt;xs:attribute ref="xml:lang" use="required" default="en" /&gt; &lt;/xs:extension&gt; &lt;/xs:simpleContent&gt; &lt;/xs:complexType&gt; &lt;/xs:schema&gt; </code></pre> <p><strong>Use cases</strong></p> <p><strong>Case 1</strong></p> <p>Lines ending in CR LF, including the last line.</p> <p>The CSV:</p> <pre><code>1st name,2nd name Sean,Brendan,"Durkin" """,""" &lt;This is a place-marker for an empty row&gt; "", </code></pre> <p>The XML equivalent (schema valid):</p> <pre><code>&lt;xcsv:comma-separated-values xmlns:xcsv="http://seanbdurkin.id.au/xslt/xcsv.xsd" xmlns:xml="http://www.w3.org/XML/1998/namespace" xcsv-version="1.0"&gt; &lt;xcsv:notice xml:lang="en"&gt;The xcsv format was developed by Sean B. Durkin&amp;#x85;www.seanbdurkin.id.au&lt;/xcsv:notice&gt; &lt;xcsv:row&gt; &lt;xcsv:value&gt;1st name&lt;/xcsv:value&gt; &lt;xcsv:value&gt;2nd name&lt;/xcsv:value&gt; &lt;/xcsv:row&gt; &lt;xcsv:row&gt; &lt;xcsv:value&gt;Sean&lt;/xcsv:value&gt; &lt;xcsv:value&gt;Brendan&lt;/xcsv:value&gt; &lt;xcsv:value&gt;Durkin&lt;/xcsv:value&gt; &lt;/xcsv:row&gt; &lt;xcsv:row&gt; &lt;xcsv:value&gt;","&lt;/xcsv:value&gt; &lt;/xcsv:row&gt; &lt;xcsv:row&gt; &lt;xcsv:value /&gt; &lt;/xcsv:row&gt; &lt;xcsv:row&gt; &lt;xcsv:value /&gt; &lt;xcsv:value /&gt; &lt;/xcsv:row&gt; &lt;/xcsv:comma-separated-values&gt; </code></pre> <p><strong>Case 2</strong></p> <p>As case 1, but with line endings as just LF.</p> <p>XML as case 1.</p> <p><strong>Case 3</strong></p> <p>Lines ending in CR LF, including the last line.</p> <p>The CSV:</p> <pre><code>Fruit,Colour Banana,Yellow </code></pre> <p>The XML equivalent (schema valid):</p> <pre><code>&lt;xcsv:comma-separated-values xmlns:xcsv="http://seanbdurkin.id.au/xslt/xcsv.xsd" xmlns:xml="http://www.w3.org/XML/1998/namespace" xcsv-version="1.0"&gt; &lt;xcsv:row&gt; &lt;xcsv:value&gt;Fruit&lt;/xcsv:value&gt; &lt;xcsv:value&gt;Colour&lt;/xcsv:value&gt; &lt;/xcsv:row&gt; &lt;xcsv:row&gt; &lt;xcsv:value&gt;Banana&lt;/xcsv:value&gt; &lt;xcsv:value&gt;Yellow&lt;/xcsv:value&gt; &lt;/xcsv:row&gt; &lt;/xcsv:comma-separated-values&gt; </code></pre> <p><strong>Case 4</strong></p> <p>Same as case 3, but last line ends in eof. In other words, the last byte of the file is the UTF-8 code for 'w'.</p> <p>Same XML!</p> <p><strong>Case 5</strong></p> <p>Empty file. The size of the file is zero.</p> <p>Valid XML instance:</p> <pre><code>&lt;xcsv:comma-separated-values xmlns:xcsv="http://seanbdurkin.id.au/xslt/xcsv.xsd" xcsv-version="1.0" /&gt; </code></pre> <p><strong>Case 6.</strong></p> <p>The file has one byte: the UTF-8 code for LF.</p> <p>CSV:</p> <pre><code>LF </code></pre> <p>Valid XML instance:</p> <p>Same XML as case 5!</p> <p><strong>Case 7</strong></p> <p>CVS encoding errors</p> <p>The CSV (not valid):</p> <pre><code>Fruit,"Colour Banana,"Yell"ow </code></pre> <p>The valid XML instance:</p> <pre><code>&lt;xcsv:comma-separated-values xmlns:xcsv="http://seanbdurkin.id.au/xslt/xcsv.xsd" xmlns:xml="http://www.w3.org/XML/1998/namespace" xcsv-version="1.0"&gt; &lt;xcsv:row&gt; &lt;xcsv:value&gt;Fruit&lt;/xcsv:value&gt; &lt;xcsv:error error-code="2"&gt; &lt;xcsv:message xml:lang="en"&gt;Quoted value not terminated.&lt;/xcsv:message&gt; &lt;xcsv:error-data&gt;"&lt;/xcsv:error-data&gt; &lt;/xcsv:error&gt; &lt;xcsv:value&gt;Colour&lt;/xcsv:value&gt; &lt;/xcsv:row&gt; &lt;xcsv:row&gt; &lt;xcsv:value&gt;Banana&lt;/xcsv:value&gt; &lt;xcsv:error error-code="3"&gt; &lt;xcsv:message xml:lang="en"&gt;Quoted value incorrectly terminated.&lt;/xcsv:message&gt; &lt;xcsv:error-data&gt;"&lt;/xcsv:error-data&gt; &lt;/xcsv:error&gt; &lt;xcsv:value&gt;Yell"ow&lt;/xcsv:value&gt; &lt;/xcsv:row&gt; &lt;/xcsv:comma-separated-values&gt; </code></pre> <p><strong>Case 8</strong></p> <p>Specific application where CSV looks like:</p> <pre><code>1st name,2nd name Sean,Durkin "Peter","Pan" </code></pre> <p>In this specific application, the header is always there, with columns in the specified order:</p> <pre><code>&lt;people&gt; &lt;person first-name="Sean" first-name="Durkin" /&gt; &lt;person first-name="Peter" first-name="Pan" /&gt; &lt;/people&gt; </code></pre> <ol> <li>Step 1. Transform .cvs into .xcvs, using a generic library XSLT style-sheet.</li> <li>Step 2. Transform .xcsv into the application-specific structure as above, using a trivial XSLT style-sheet.</li> </ol> <p><strong>Case 9</strong></p> <p>This use case demonstrates the necessary XML encoding on a lexical level for &amp; and &lt; and raw data. No special encoding is required at the XML parser API level.</p> <p>The CSV:</p> <pre><code> Character,Name &amp;,Ampersand &lt;,Less than </code></pre> <p>The equivalent schema-valid XML instance:</p> <pre><code>&lt;xcsv:comma-separated-values xmlns:xcsv="http://seanbdurkin.id.au/xslt/xcsv.xsd" xmlns:xml="http://www.w3.org/XML/1998/namespace" xcsv-version="1.0"&gt; &lt;xcsv:row&gt; &lt;xcsv:value&gt;Character&lt;/xcsv:value&gt; &lt;xcsv:value&gt;Name&lt;/xcsv:value&gt; &lt;/xcsv:row&gt; &lt;xcsv:row&gt; &lt;xcsv:value&gt;&amp;amp;&lt;/xcsv:value&gt; &lt;xcsv:value&gt;Ampersand&lt;/xcsv:value&gt; &lt;/xcsv:row&gt; &lt;xcsv:row&gt; &lt;xcsv:value&gt;&amp;lt;&lt;/xcsv:value&gt; &lt;xcsv:value&gt;Less than&lt;/xcsv:value&gt; &lt;/xcsv:row&gt; &lt;/xcsv:comma-separated-values&gt; </code></pre>
[]
[ { "body": "<p>(This is more of a comment, than an answer, but there are several longer points I'd like to address which is easier in an answer).</p>\n\n<p>Could you show some use cases for this? Considering that both CSV and XML are both formats for general data storage, I don't see point in converting as CSV file into a \"non-specifc\" XML format instead directly into the \"specific\" XML format of the application in use.</p>\n\n<p>Also, the problem with CSV is that it's not really standardized. Despite the name they don't need to use commas as value separators. Semicolons or tabs are common variants. Also some variants require quoting all values, or allow single quotes, or use backslashes to escape quotes in values, or allow line breaks in values (which is the one variant you curiously disallow). If you really need \"non-destructive round-trip transformations\" you should consider all these variants and store the \"features\" of the CSV implementation in your XML.</p>\n\n<p>On the other hand, you store the information if a value is quoted or not, but this isn't really part of the \"relevant information\". Take a, for example, similar \"conversation\": XML -> DOM -> XML. Here it is also not stored if or how a value is quoted. An XML document such as</p>\n\n<pre><code>&lt;example&gt;&lt;![CDATA[ &lt;&amp;&gt; ]]&gt;&lt;/example&gt;\n</code></pre>\n\n<p>after reading it into a DOM structure and then re-serializing it, it could (and often would) come out as:</p>\n\n<pre><code>&lt;example&gt; &amp;lt;&amp;amp;&amp;gt; &lt;/example&gt;\n</code></pre>\n\n<p>because both encodings are equivalent.</p>\n\n<p>Similarly in your case, it shouldn't matter if a value was originally quoted or not. So if a row such as</p>\n\n<pre><code>\"apple\",\"banana\",\"red, white and blue\",\"quote this(\"\")\"\n</code></pre>\n\n<p>come out as</p>\n\n<pre><code>apple,banana,\"red, white and blue\",\"quote this(\"\")\"\n</code></pre>\n\n<p>should be irrelevant - unless the specific CSV application requires quoting. So it's more important to store <em>that</em> information in the XML, than whether or a single value was quoted or not.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-21T23:35:52.353", "Id": "16284", "Score": "0", "body": "Thanks for that RoToRa. You put some really good points and questions. I will respond fully over the weekend. I will include use cases and rationales." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-26T07:14:32.907", "Id": "16468", "Score": "0", "body": "It was a good point that I should specify Use Cases. Please find a collection of Use Cases following." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-26T07:15:51.110", "Id": "16469", "Score": "0", "body": "To explain the value of a generic XML format, consider the situation where one is required to convert an specific csv format into a specific XML format using XSLT 2+ . Without a generic format, you can do it. It is not a big problem, but there is a certain non-zero cost to develop the\n XSLT. ...." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-26T07:20:12.587", "Id": "16470", "Score": "0", "body": "With a generic format, one could handle the transformation in two phases. The first phase\nfrom generic csv to generic xml using a stock standard library XSLT script. Since this is a pre-made\nlibrary routine, the cost of this phase is zero. The second phase would be to convert the generic\nXML to the application-specific XML. Again, there is some non-zero cost involved. So both paths\nhave a cost. The relevant question is which is the lower cost. ....." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-26T07:20:37.830", "Id": "16471", "Score": "0", "body": "The theory that I propose, and the\nneed-driver for this schema, is the idea that cost of developing a transform from generic XML\nto a specific XML, in XSLT, is a lot cheaper and simpler than developing a direct single-pass transform\nfrom a specific csv to a specific XML. Well is it really true? I guess if you are not convinced\nthe real test would be giving an example use case of a csv to xml problem, and showing two solutions:\nOne direct single-pass, and the other two-pass using a generic xml format (xcsv) in the middle. ...." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-26T07:21:01.057", "Id": "16472", "Score": "0", "body": "... I will make this demonstration/proof/disproof and attach it or reference it to the schema when I\nfinish polishing the schema and publish it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-26T07:21:26.470", "Id": "16473", "Score": "0", "body": "I think you are right about round-trip. Only the real pay-load data of the csv or xml files\nmatters and not its lexical representation. Looking back, I can't see much value in trying to\npreserve bit-for-bit identicality in a round-trip transformation. Its like the difference between\nsingle quotes and double quotes in an XML attribute delimiter - It shouldn't matter....." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-26T07:21:56.733", "Id": "16474", "Score": "0", "body": "... Therefore I \nwill drop the \"xcsv:quoted\" attribute from the \"xcsv:value\" element, as it now appears to be an\nunnecessary complexity...." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-26T07:23:16.327", "Id": "16475", "Score": "0", "body": "Upon reflection, I think I should also remove the name-space qualification from the domestic attributes, to bring the schema more in line with common practice." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-26T07:23:53.830", "Id": "16476", "Score": "0", "body": "Why did I exclude Line-breaking csv from the scope? CSV is an extremily broad format with no commonly\nrecognised standard. The schema was designed with an XSLT 2 & 3 transformation solution in mind.\nIt is just too hard a problem to generically solve the conversion problem with multi-line in XSLT\nwith any kind of reasonable efficiency for large files. ...." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-26T07:24:17.480", "Id": "16477", "Score": "0", "body": "... The problem would have been even more difficult\nif I expanded to scope to include any kind of character encoding or any kind of value separator\n(such as dots, pipes, space, tabs etc). I made the compromise of limiting the scope of the problem\ndefinition for the practical purposes of being able to offer an attactive generic practical efficient XSLT 2/3\nsolution which meets the schema. ..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-26T07:24:46.327", "Id": "16478", "Score": "0", "body": "... Having said that, I am not at all confident that I made the right\ncompromise here. It would be possible to remove the no-line-breaks restriction from the value cell\nof the schema, and then the schema would be just as usefull for two different csv-to-xml transformations:\none fast one with scope limited to single line values, and another broader one that can include\nmulti-line values. After all, a Schema is not necessarily tied to any particular transform...." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-26T07:24:52.877", "Id": "16479", "Score": "0", "body": "... So I leave\nthis question (\"was limiting the scope to single-line values a good idea\") unresolved, except to say\nthat I want to collect more opinions on the matter." } ], "meta_data": { "CommentCount": "13", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-21T10:08:28.363", "Id": "10208", "ParentId": "10180", "Score": "4" } } ]
{ "AcceptedAnswerId": "10208", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-20T11:21:54.047", "Id": "10180", "Score": "6", "Tags": [ "xml", "xsd", "xslt" ], "Title": "XML Schema for an XML representation of CSV" }
10180
<p>I have an application which is used for displaying and modifying huge volumes of point cloud data from lidar files (up to few gigabytes each, sometimes loaded in simultaneously). In the app the user is able to view a 2D image of loaded points (from the top) and select a profile to view in another window (from the side). Again this involves millions of points and they are displayed using OpenGL.</p> <p>To handle the data there is also a quadtree library, which works, but is extremely slow. It has been used for some time, but recently the lidar point format changed and the <code>LidarPoint</code> object needed a number of attributes (class members) added, which cause it to grow in size in turn affecting the performance to almost unusable level (think 5 minutes to load a single 2GB file).</p> <p>The quadtree currently consist of pointers to <code>PointBucket</code> objects which are simply arrays of <code>LidarPoint</code> objects with specified capacity and defined boundaries (for spatial queries). If the bucket capacity is exceeded it splits into four buckets. There is also kind of a caching system in place which causes point buckets to get dumped to disk when the point data is taking too much memory. These are then loaded back into memory if needed. Finally every <code>PointBucket</code> contains subbuckets/resolution levels which hold every n-th point of the original data and are used when displaying the data depending on the zoom level. That is because displaying few million points at once, while that level of detail is not necessary, is just extremely slow.</p> <p>Here is the current (and slow) <code>insert()</code> method:</p> <pre><code>// Insert in QuadTree bool QuadtreeNode::insert(LidarPoint newPoint) { // if the point dosen't belong in this subset of the tree return false if (newPoint.getX() &lt; minX_ || newPoint.getX() &gt; maxX_ || newPoint.getY() &lt; minY_ || newPoint.getY() &gt; maxY_) { return false; } else { // if the node has overflowed and is a leaf if ((numberOfPoints_ + 1) &gt; capacity_ &amp;&amp; leaf_ == true) { splitNode(); // insert the new point that caused the overflow if (a_-&gt;insert(newPoint)) { return true; } if (b_-&gt;insert(newPoint)) { return true; } if (c_-&gt;insert(newPoint)) { return true; } if (d_-&gt;insert(newPoint)) { return true; } throw OutOfBoundsException("failed to insert new point into any \ of the four child nodes, big problem"); } // if the node falls within the boundary but this node not a leaf if (leaf_ == false) { return false; } // if the node falls within the boundary and will not cause an overflow else { // insert new point if (bucket_ == NULL) { bucket_ = new PointBucket(capacity_, minX_, minY_, maxX_, maxY_, MCP_, instanceDirectory_, resolutionBase_, numberOfResolutionLevels_); } bucket_-&gt;setPoint(newPoint); numberOfPoints_++; return true; } } } // Insert in PointBucket (quadtree holds pointers to PointBuckets which hold the points) void PointBucket::setPoint(LidarPoint&amp; newPoint) { //for each sub bucket for (int k = 0; k &lt; numberOfResolutionLevels_; ++k) { // check if the point falls into this subbucket (always falls into the big one) if (((numberOfPoints_[0] + 1) % int(pow(resolutionBase_, k)) == 0)) { if (!incache_[k]) cache(true, k); // Update max/min intensity/Z values for the bucket. if (newPoint.getIntensity() &gt; maxIntensity_) maxIntensity_ = newPoint.getIntensity(); else if (newPoint.getIntensity() &lt; minIntensity_) minIntensity_ = newPoint.getIntensity(); if (newPoint.getZ() &gt; maxZ_) maxZ_ = newPoint.getZ(); else if (newPoint.getZ() &lt; minZ_) minZ_ = newPoint.getZ(); points_[k][numberOfPoints_[k]] = newPoint; numberOfPoints_[k]++; } } } </code></pre> <ol> <li>Can you think of a way to improve this design?</li> <li>What are some general strategies when dealing with huge amounts of data that doesn't fit into memory?</li> <li>How can I make the quadtree more efficient? Is there a way to speed up rendering of points?</li> </ol>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-22T12:35:01.163", "Id": "16306", "Score": "0", "body": "Are you using a library for your Lidar data? What does LidarPoint look like under the hood?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-22T19:20:37.813", "Id": "16325", "Score": "0", "body": "I am using laslib for reading the points from LAS files. LidarPoint just holds the attributes of lidar points (time, intensity, classification...) and inherits from Point which only has x, y, z. I could paste the whole thing if that would help." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-17T04:58:47.687", "Id": "37014", "Score": "0", "body": "Have you considered using http://pointclouds.org/ ?" } ]
[ { "body": "<p>Profiling is always good to locate bottlenecks.</p>\n\n<p>If quadtree construction is a bottleneck, it might help to use multiple passes. A first pass might only store the x/y values which are all that is needed to determine the structure of the quadtree. For a second pass, the buckets can be pre-allocated to the correct size (most less than <code>capacity_</code>) and each point goes directly to the right bucket.</p>\n\n<p>For the resulting quadtree, do you really need to store the point values (multiple times, at that)? Maybe just the summary info is enough (min/max z, min/max intensity). Or if you need the points only rarely, store an index to each point and do a more expensive look-up to find the point specifics when needed.</p>\n\n<p>Lastly, if your coordinates are used at display resolution, you can store them with floats instead of doubles.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-03T21:08:29.110", "Id": "12251", "ParentId": "10181", "Score": "2" } }, { "body": "<p>You may find this article gives you some ideas...</p>\n\n<p><a href=\"http://queue.acm.org/detail.cfm?id=1814327\" rel=\"nofollow\">http://queue.acm.org/detail.cfm?id=1814327</a></p>\n\n<p>You mention a caching scheme. What this argues is that rather than having a caching scheme, you let virtual memory do the work for you on that, and manage things so that data fits into memory pages in a way which matches how the data tends to be used.</p>\n\n<p>The article doesn't talk about quadtrees - rather it's talking about b-heaps, and the usage is quite different - they are looking at locating single data-points as fast as possible on a heavily used server, whereas it seems you're looking at pulling in large amounts on data on a single workstation. So it's something to be inspired by, more than something which solves your problem directly, but it may give you thoughts about how you can structure your data to make best use of disk accesses. The resulting data structure might end up being much more complex, but I would be surprised if the issue was CPU rather than disk so the tradeoff should work in your favour.</p>\n\n<p>Hope it gives you some ideas!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-24T11:43:16.767", "Id": "13003", "ParentId": "10181", "Score": "2" } }, { "body": "<p>As you have not provided any profiling data I can only speculate in what I see in the code you have provided.</p>\n<h1>Guesstimating expected performance</h1>\n<p>First of lets consider some numbers, you say millions of points so I'm going to assume 10 million points.</p>\n<p>You say 2GB file then for 10 million points, that's around 200 bytes per point sounds reasonable.</p>\n<p>Lets assume a typical HDD with read speed somewhere around 80MB/s, then reading 2GB of data should take 2000/80 = 25 seconds or so.</p>\n<p>Lets assume a modern 3GHz CPU with average instructions per cycle (IPC) of 5 (which is a bit pessimistic). That means that you can do around 3000*5/10 = 1500 instructions per point, per second per core. I would reasonably expect to be able to build the tree (ignoring the delay to read from disk) in a few, maybe tens of seconds.</p>\n<p>All in all to read the entire thing into memory and build a quadtree, <strong>I would expect around a minute</strong>. You say 5 minutes which is a bit slower than what should be possible.</p>\n<h1>Looking at the code</h1>\n<p>I see no major blunders that would be an obvious culprit but I do see a LOT of branching on data.</p>\n<p>One reason CPUs can have such high IPC is that they do something called &quot;Speculative Execution&quot;. When the CPU encounters a branch (if-else) it will take an educated guess using sophisticated algorithms to try to predict which branch will be taken and start executing that branch before it has actually computed the branching condition. Pretty neat stuff. As long as this branch prediction goes well (and it does so quite frequently) you gain a lot of performance, but if the CPU on the other hand miss-predicted the branch, it has to back out of the work it already did and then go back and execute the correct branch.</p>\n<p>This is called, &quot;branch prediction failure&quot; and is very well illustrated in <a href=\"https://stackoverflow.com/questions/11227809/why-is-it-faster-to-process-a-sorted-array-than-an-unsorted-array\">this SO question</a>.</p>\n<p>In that question the OP has an array of random characters and sums all values larger than 128 (i.e. 50% of the values). Then the op does additional work and sorts the array first, and then runs the exactly same code. Intuitively you would expect it to be slower because you have done an additional sort before hand. But this is not the case, doing the extra work of the sorting actually makes the entire code 5x faster. This 5x speedup is entirely due to avoiding branch miss-predictions as the data is now sorted and the branch predictor in the CPU can correctly predict almost all branches while the random array is impossible to predict.</p>\n<p>The 5x speedup factor uncannily matches my guesstimate above (1min vs 5min) and your code appears to be branching on random data (as the points are not sorted geometrically, whatever that means).</p>\n<p>I believe that you can gain some significant performance by rethinking how you branch in your insert method.</p>\n<p>For example here:</p>\n<pre><code>// if the point dosen't belong in this subset of the tree return false\nif (newPoint.getX() &lt; minX_ || newPoint.getX() &gt; maxX_ || \n newPoint.getY() &lt; minY_ || newPoint.getY() &gt; maxY_)\n{ \n return false;\n}\nelse\n{\n // if the node has overflowed and is a leaf\n if ((numberOfPoints_ + 1) &gt; capacity_ &amp;&amp; leaf_ == true)\n {\n splitNode();\n\n // insert the new point that caused the overflow\n if (a_-&gt;insert(newPoint))\n {\n return true;\n }\n if (b_-&gt;insert(newPoint))\n {\n return true;\n }\n if (c_-&gt;insert(newPoint))\n {\n return true;\n }\n if (d_-&gt;insert(newPoint))\n {\n return true;\n }\n throw OutOfBoundsException(&quot;failed to insert new point into any \\\n of the four child nodes, big problem&quot;);\n }\n</code></pre>\n<p>First you check if you're inside the node, then you repeat the same check for each of the children, this is a lot of branching. Unnecessary branching.</p>\n<p>Assume for a second that the root contains the point (check this only once for each point) then one of the children <strong>must</strong> contain the point. The distinction is instead of asking:</p>\n<blockquote>\n<p>&quot;Does any one of my children contain the point&quot;</p>\n</blockquote>\n<p>you are asking</p>\n<blockquote>\n<p>&quot;Which one of my children contains the point, I know it's one of you&quot;.</p>\n</blockquote>\n<p>Which is a big difference, let me show you with some pseudo code:</p>\n<pre><code>bool QuadTree::insert(Point p){\n if(p &lt; min || p &gt; max){\n return false; // Point outside tree\n } \n return root-&gt;insert();\n} \n\nbool QuadTreeNode::insert(Point p){\n if( leaf ){\n return addPointAndPossiblySplitThisNode(p);\n }\n \n if (p.x &lt; midpoint.x){\n if(p.y &lt; midpoint.y){\n return lowerLeftChild-&gt;insert();\n }\n return upperLeftChild-&gt;insert();\n }\n if(p.y &lt; midpoint.y){\n return lowerRightChild-&gt;insert();\n }\n return upperRightChild-&gt;insert();\n}\n</code></pre>\n<p>See how many fewer branches this code has? Note that this code breaks boundary hits towards the right and the top.</p>\n<p>This code does at most 3 branches per node, and the branching conditions are trivial which makes a miss-predicted branch cost less (as the delay until you compute the branching condition is shorter).</p>\n<p>On just the code I quoted, you do at most 6 branches. I realise I did not implement the node splitting part and allocation of the buckets but I did also not take that into account when I counted branches on your code.</p>\n<p>At any rate, this is just qualified speculation on my part. I recommend you try the above and see if it makes any difference. Remember, the only way to know if it made a difference is to measure before and after!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-04-05T10:12:17.737", "Id": "302934", "Score": "0", "body": "Aaand I just relalized this question is from 2012 lol" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-04-05T12:40:19.640", "Id": "302955", "Score": "0", "body": "Old question, but a good and educational answer, so completely worthwhile!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-04-04T20:56:42.403", "Id": "159843", "ParentId": "10181", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-20T12:51:08.067", "Id": "10181", "Score": "15", "Tags": [ "c++", "performance", "tree", "opengl" ], "Title": "Quadtree design" }
10181
<p>Ok I have a method:</p> <pre><code>//_seen is defined as a HashSet earlier public boolean isTerminal(Node node) { if (_seen.contains(node.getState())) { return true; } else { _seen.add(node.getState()); return false; } } </code></pre> <p>What is the nicest way of doing this? It could use a variable to hold <code>_seen.contains</code>, and return just that, and maybe always add. Or, perhaps I could do:</p> <pre><code>public boolean isTerminal(Node node) { return !_seen.add(node.getState()); } </code></pre> <p>but is that clear?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-20T13:35:39.780", "Id": "16189", "Score": "1", "body": "What does this function actually do? The name `isTerminal` seems heavily misleading." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-20T14:36:08.613", "Id": "16191", "Score": "0", "body": "Perhaps i should replace isTerminal(Node node) with Foo(Node node) for clarity.\nbut FYI:\nIt checks if there are no nodes worth exploring below this one.\nIf we have already seen a node who's state is the same as the state of this one, then we have already seen the nodes that would decend from it, so this is a Terminal Node - it has no worthwild decendants.\nThe reason it remembers that nodes it has been asked about is because this function is basically the only certain interaction that exists between the (server) class and the client class that uses it. (and I can't change this)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T18:20:12.137", "Id": "33007", "Score": "0", "body": "Pass in the NodeState instead of the Node. You don't actually use the node in the function." } ]
[ { "body": "<p>Both forms will produce the same result. Choosing between them is a stylistic/aesthetic question.</p>\n\n<p>Many people will claim that the more compact form is easier to read, despite the fact that someone new to Java might not be aware of the fact that the add method of HashMap returns true if the map did not already contain the value.</p>\n\n<p>Some will prefer the more explicit form. Even if they understand how add works, they might argue that relying on a quirk of its implementation to write more compact code as inherently less readable.</p>\n\n<p>I think it's a sort of chocolate/vanilla (or purple/green for B5 fans) question. Think about who is likely to be looking at the code in the future and select the form most appropriate for that audience.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-20T14:24:08.190", "Id": "10183", "ParentId": "10182", "Score": "4" } }, { "body": "<p>You could also use a variable to make the compact version more readable:</p>\n\n<pre><code>public boolean isTerminal(Node node)\n{\n boolean stateWasAdded = _seen.add(node.getState());\n return !stateWasAdded;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-20T14:45:15.507", "Id": "10184", "ParentId": "10182", "Score": "8" } }, { "body": "<p>First of all I don't think its a good idea to have a function that does all that tasks Check, Sets and Add.\nThe code should look like this:</p>\n\n<pre><code>public boolean isTerminal(Node node)\n{\n return _seen.contains(node.getState());\n}\n</code></pre>\n\n<p>and if you want to add the state/node, you should have a separate method</p>\n\n<pre><code>public void addNode(Node node)\n{\n if (!isTerminal(node))\n {\n _seen.add(node.getState());\n }\n}\n</code></pre>\n\n<p>Hope I understood well what you need.</p>\n\n<p>Cheers!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-24T02:42:18.763", "Id": "16399", "Score": "0", "body": "As stated in comments on the Question post. I appreciate this point, but it is outside of my control. The function is as it stands." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-25T18:59:40.510", "Id": "16443", "Score": "0", "body": "@Oxinabox, WHY is that outside of your control? I do not like the signature of the method." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-01T02:54:18.480", "Id": "16762", "Score": "0", "body": "because for a Uni lab, I must meet the eixsting badly defined interfaces. ( don't know wjhy they are so bad, but they do some other things that make me thing the interfaces weren't actually designed A) well (I can go on with why) B) for the current set of lab tasks.\nI think I could prob strecth things and avoid it.\nMarking this as excepted. - your answer is correct." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-22T19:34:16.490", "Id": "10261", "ParentId": "10182", "Score": "2" } }, { "body": "<p>The verbose form lends itself to future refactoring. It's easier to follow just by skimming the code, rather than needing to stop (even for a second) to figure out what the compact form is <em>really</em> doing. I think this is especially true given that method names that begin with <code>is</code> generally perform a read-only operation. Given that, I think the side effect that could potentially be performed by <code>isTerminal</code> should remain independent of the non-side-effecting operation. This will make it clear that there are two things happening, and make it easier to decouple them in the future.</p>\n\n<p>Also, as a minor concern, someone not intimately familiar with Java Collections might not remember what the <code>add</code> method returns. Does it return true if and only if the item was added? Does it return true or false if the item was already there? I understand that this simple to look up, but if you're looking for clarity and readability, this may be a factor.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-25T18:17:05.733", "Id": "10323", "ParentId": "10182", "Score": "1" } } ]
{ "AcceptedAnswerId": "10261", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-20T12:55:24.447", "Id": "10182", "Score": "6", "Tags": [ "java" ], "Title": "Sets, Check and add" }
10182
<p>This is for a college assignment, it has been submitted but I'd like some general feedback on how to improve it or whether I should be using more functions or less functions.</p> <p>Also, is my commenting too extreme?</p> <pre><code>/** * This program takes two binary integers and performs one of three operations * on them. * * It will either multiple, divide or get the modulo of the two * numbers. * * It ignores whitespace and accepts input in the following format * &lt;number&gt;&lt;operation&gt;&lt;number&gt; = &lt;enter&gt; * * The program will then convert the binary integer to decimal, perform it's * operation, convert the output back to binary and print the result. * * An error will occur the incoming input is in the wrong format or if the * binary intergers are not unsigned (positive). * * @author Sam Dunne &lt;sam.dunne@ucdconnect.ie&gt; 10308947 */ /** * Include standard libraries */ #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &lt;math.h&gt; #include &lt;limits.h&gt; /** * This function checks the string to ensure it's valid * * @param char input The string input to be checked * * @var int i * @var char operation The operation to be performed * * @return char operation */ static char check_string(char *input) { char operation; unsigned int i = 0; /** * Check to see which operation is contained within the string. * Assign the correct operation to the 'operation' variable. */ operation = strchr(input, '*') ? '*' : ( strchr(input, '/') ? '/' : ( strchr(input, '%') ? '%' : '0')); /** * Ensure a valid operator was found */ if(operation == '0') { printf("\n\nNo operator found. Closing\n\n"); exit(1); } /** * Ensure there are no illegal characters in the string */ for(i = 0; i &lt; strlen(input); ++i) { if(input[i] != '0' &amp;&amp; input[i] != '1' &amp;&amp; input[i] != '*' &amp;&amp; input[i] != '/' &amp;&amp; input[i] != '%' &amp;&amp; input[i] != ' ') { printf("\n\nInvalid Input. Closing\n\n"); exit(1); } } return operation; } /** * This function parses the input into two numbers and an operation and * performs the operation * * @param char input The string input to be parsed * @param char operation The operation being performed * @param int dec_output The pointer that will 'return' the decimal value * @param int bin_output The pointer that will 'return' the binary value * * @var int dec[] The decimal representations of the binary strings * @var int dec_result The decimal result of the operation * @var int mask This is the mask for the decimal to binary conversaion * @var char bin[] The binary strings * @var char rest The rest of the string after it has been tokenised * @var char junk Junk left over from strtol() * * @return int 0 */ static void parse(char *input, char operation, unsigned int *dec_output, char *bin_output){ unsigned int dec[2], dec_result = 0, mask = 0; char *bin[2], *rest, *junk; /** * Tokenise the string and assign the two tokens to variables */ bin[0] = strtok_r(input, &amp;operation, &amp;rest); bin[1] = rest; /** * Convert binary number to decimal */ dec[0] = strtol(bin[0], &amp;junk, 2); dec[1] = strtol(bin[1], &amp;junk, 2); if(dec[1] == 0){ printf("\n\nDividing by zero and modulus with zero is impossible. Destroy the Universe elsewhere. Good day.\n\n"); exit(1); } /** * Perform correct operation */ dec_result = (operation == '*') ? (dec[0]*dec[1]) : ( (operation == '/') ? (dec[0]/dec[1]) : (dec[0]%dec[1]) ); /** * Convert result back to binary */ *(bin_output+16) = '\0'; mask = 0x10 &lt;&lt; 1; while(mask &gt;&gt;= 1) *bin_output++ = !!(mask &amp; dec_result) + '0'; *dec_output = dec_result; } /** * This is the main function that calls all other functions * * @var char line[] The array for storing the incoming string * @var int i * @var int dec_output The decimal result to be printed * @var int bin_output The binary result to be printed * * @return int 0 */ int main(void) { char operation, line[256], bin_output[256]; unsigned int i = 0, dec_output = 0; /** * Read in the input to 'char line[]' */ printf("Enter two binary integers seperated by one of [ * / %% ] and press enter\nCALC: "); fgets(line, sizeof(line), stdin); /** * Remove newline from string if present */ i = strlen(line) - 1; line[i] = '\0'; /** * Check validity of the input */ operation = check_string(line); /** * Call the parser for results */ parse(line, operation, &amp;dec_output, bin_output); /** * Print the final answer */ printf("\n\n|*---|Result = {DECIMAL:%d || BINARY:%s}|---*|\n\n", dec_output, bin_output); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-21T12:31:57.067", "Id": "16238", "Score": "1", "body": "Typos in file comment:\n - \"multiple\" should be \"multiply\"\n - \"modulo of\" should be \"result of applying modulo to\"\n - \"it's\" (the contraction for \"it is\") should be \"its\" (the possessive form of \"it\")\n - \"interger\" should be \"integer\"\n - \"occur\" should be \"occur if\"\n - \"positive\" should be \"positive or zero\"" } ]
[ { "body": "<p>Good work delineating the functions. You have met several relevant guidelines for each one of your functions. It is reasonably short. It performs one clearly defined operation. It uses a limited amount of conditional logic. Each of its conditional statements has a purpose that is clearly related to the rest. Any conditional statement whose purpose is loosely related to the rest is factored out as a separate function.</p>\n\n<p>I would generally suggest to eliminate the use of the ternary operator (<code>? :</code>) despite that it is much more compact than <code>if</code> ... <code>else</code>. The ternary operator was a good hint to earlier compilers, but now people need more help than the compiler does. When branching on several values of the same data element you can generally arrange your code to use <code>switch</code> effectively.</p>\n\n<p>I agree that you have incorporated more comments than are really useful. A good example of a comment that is better to remove is \"Check validity of the input\". The code uses the function name \"check_string\" that already expresses that purpose clearly. You can also assume that anyone reading your code knows the programming language (or is willing to learn it). Comments equivalent to identifiers or programming language constructs are good placeholders for your own use while the code is incomplete. When the code is complete and it expresses just what those comments say, then the comments are only clutter and are better removed.</p>\n\n<p>On the other hand, your comments introducing each function are good. They are useful definitions of the contract (the API) that each function is intended to fulfill.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-21T14:47:45.327", "Id": "16246", "Score": "0", "body": "I agree with everything said. An additional remark about the ?: operator - it is not only superfluous, it is dangerous too. If you for example have code like this: `memcpy(dest, src, sizeof(type==INT ? my_int : my_double));`. Lets say this code is supposed to copy generic data based on some enum \"type\" which keeps track of the data type. The code will not work, it will always copy 8 bytes no matter what type is set to. The culprit is the illogical behavior of the ?: operator, which always performs balancing between its 2nd and 3rd operand, silently converting the int to a double in this case." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-21T14:50:11.097", "Id": "16247", "Score": "0", "body": "Try to compile & run this snippet for example: `int my_int; double my_double; enum {INT, DOUBLE} type = INT; printf(\"%d\", sizeof(type==INT ? my_int : my_double));`. Always prints 8, assuming double has size 8 bytes." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-21T14:55:58.060", "Id": "16248", "Score": "0", "body": "The hint about `?:` is completely false, sorry. Its use is entirely appropriate here. An `if` would only make the code longer and more convoluted, not clearer. And the conditional operator was *not* a โ€œhint at earlier compilersโ€, thatโ€™s nonsense. Itโ€™s a normal operation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-21T15:21:41.877", "Id": "16250", "Score": "0", "body": "@KonradRudolph Even still, the ?: is unpredictable and unsafe, as I demonstrated. if-else is perfectly safe. Why use a language feature that is both superfluous and unsafe?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-21T15:28:01.187", "Id": "16251", "Score": "0", "body": "@Lundin Wrong. The conditional operator is predictable and safe. Your code just fails to take into account fundamental rules of expression type and conversion. Thatโ€™s not partial to `?:`, the same happens for other operators (`my_int + my_double` โ€ฆ) and should be obvious. Failure to understand the language doesnโ€™t obviate the usefulness of this operator." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-21T15:33:39.037", "Id": "16252", "Score": "0", "body": "@KonradRudolph No it doesn't. The C standard clearly states that the 1st operand (the condition) of ?: is evaluated first, and then the 2nd **or** the 3rd operand is evaluated. However, the C standard also states that, even though the 2nd or the 3rd operand isn't used, it should partake and affect invisible type promotions. You can't compare it to `my_int + my_double`, because there you expect that both operands of the binary operation are evaluated. In case of ?: you never expect that all 3 operands are evaluated." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-21T15:39:03.217", "Id": "16254", "Score": "0", "body": "@Lundin โ€œit doesnโ€™tโ€ โ€“ What doesnโ€™t? The effect of `?:` is entirely predictable and logical from a fundamental understanding of C. Types of expressions in C are static, they cannot be influenced by the *value* of one of its operands. And this isnโ€™t a particularity of C either โ€“ย itโ€™s true for *any* statically typed language. In fact, itโ€™s its defining property." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-21T15:47:16.633", "Id": "16258", "Score": "0", "body": "Another example: `char ch; const char a = 'A'; memcpy(&ch, &a, sizeof (true ? ch : 0));`. Nobody but a true language nerd will realize that this code copies 4 bytes into a 1 byte-large variable and crashes the program. I would not expect the average C programmer to understand this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-21T15:51:23.567", "Id": "16259", "Score": "0", "body": "@Lundin Konrad is right, for the case of C. However in C++ there are ways to abuse the conditional operator, where you'd need a PhD in standardese to grok the formal rules (the only case in C is like `a? b : c = d`). On the third hand, this is so also for most any language feature: there are ways to (ab)use each feature so that it's ungood code. In the case above, however, the code is straightforward. Then it's just a matter of personal taste -- or coding standard -- which construct to use." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-21T15:58:02.330", "Id": "16261", "Score": "0", "body": "So everyone thinks the latest snippet I posted is trivial and obvious? It is obvious to you that the code always crashes the program?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-21T16:41:58.967", "Id": "16265", "Score": "0", "body": "@Lundin: yes (to the obviousness of the code being wrong, not that it necessarily crashes, which it won't necessarily do). but it may be peculiar to C++ programmers, i.e. it may be different for people used to coding in C. good C++ programmers usually stay away from `memcpy` entirely, and look on any usage as very suspicious, worthy of more close inspection & thinking." } ], "meta_data": { "CommentCount": "11", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-21T12:45:34.570", "Id": "10217", "ParentId": "10186", "Score": "1" } }, { "body": "<p>In general the code is very clear.</p>\n\n<p>That said, you use <em>way</em> too many comments. Do not paraphrase the code in comments, and instead use them to say things you cannot express in code: โ€œcode tells you how, comments tell you why.โ€</p>\n\n<p>Comments such as โ€œThis is the main function that calls all other functionsโ€ or โ€œ This function checks the string to ensure it's validโ€ are useless. They are only useful if the reader doesnโ€™t understand C, and this isnโ€™t the point of comments.</p>\n\n<p>In particular, the <code>main</code> function needs no comment. Its use is clear to everybody. The <code>check_string</code> function, on the other hand, needs an improved comment: use it to explain <em>what</em> constitutes a valid string (instead of just saying that it checks validity).</p>\n\n<p>Whatโ€™s more, a multi-line comment in C starts by <code>/*</code>, not by <code>/**</code>. Use the latter only for documentation comments. By convention, they are then used by documentation systems to parse the code and generate documentation. For all other comments (in functions etc.) use normal single-line comments or multi-line comments that start with a single star (<code>/*</code>).</p>\n\n<p>A word on the conditional operator: I believe the other commenters are wrong in their assessment of this operator. Itโ€™s safe, readable and should absolutely be used when necessary. However, a slightly different formatting can make chained conditions much more readable:</p>\n\n<pre><code>operation = strchr(input, '*') ? '*' :\n strchr(input, '/') ? '/' :\n strchr(input, '%') ? '%' : '0';\n</code></pre>\n\n<p>Note that thanks to the precedence rules of the conditional operator, the original parentheses arenโ€™t necessary. Chaining conditionals in this way is a pretty well established idiom and certainly improves readability over using <code>if</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-21T17:33:13.917", "Id": "16266", "Score": "0", "body": "+1 for comments about the ternary operator, although I prefer to put the very last operand (the _else_) on its own line so the entire thing reads like a series of questions with answers." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-21T15:02:01.627", "Id": "10219", "ParentId": "10186", "Score": "6" } }, { "body": "<p>In addition to minopret's comments:</p>\n\n<p><strong>Functionality</strong></p>\n\n<ul>\n<li><p>Avoid using exit(), it is frowned upon in most implementations. For example, see <a href=\"http://www.flounder.com/badprogram.htm#ExitProcess\" rel=\"nofollow\">this explanation</a> of why it is bad in Windows. Instead, use <code>return EXIT_FAILURE;</code> (found in stdlib.h). And if you try to convert your program to use <code>return</code> instead, you will find out that you need to (and should) leave all error handling to the caller. Return an error code or similar.</p></li>\n<li><p><code>!!(mask &amp; dec_result)</code> is this a typo? Why would you want to call the boolean NOT operator twice in a row?</p></li>\n<li><p>Ensure that all user input strings are null terminated <em>before</em> passing them to string handling functions like strlen, or the program might go haywire. I suspect that this the row <code>i = strlen(line) - 1;</code> is a severe bug, but you get away with it because the debug executable build in your compiler happens to set <code>line</code> to all zeroes, which the standard does not guarantee. </p></li>\n</ul>\n\n<p><strong>Style</strong></p>\n\n<ul>\n<li><p>A function that does not modify the contents of a parameter passed by reference (pointer), should declare that pointer as <code>const</code>. For example <code>static char check_string(const char *input);</code>. This is referred to as \"const correctness\" among C and C++ programmers and is considered good practice.</p></li>\n<li><p>Avoid declaring several variables on the same line, it leads to bugs and confusion. For example <code>char* ptr1, ptr2;</code>, ptr1 is a pointer, ptr2 is a char, which was perhaps not the intention. Instead, declare every variable on a line of its own:</p></li>\n</ul>\n\n<p>-</p>\n\n<pre><code> char operation;\n char line[256];\n char bin_output[256];\n</code></pre>\n\n<p><strong>Performance</strong></p>\n\n<ul>\n<li><code>for(i = 0; i &lt; strlen(input); ++i)</code>. Avoid calling functions from a loop condition. Code like this is not always optimized, so you end up calling strlen() over and over, even though it performs the very same calculation each time. A better way is this:</li>\n</ul>\n\n<p>-</p>\n\n<pre><code> int length = strlen(input);\n for(i = 0; i &lt; length; ++i)\n</code></pre>\n\n<p>(or to be pedantic: <code>size_t length = strlen(input);</code>)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-21T17:34:34.900", "Id": "16267", "Score": "0", "body": "\"`!!(mask & dec_result)` is this a typo?\" I don't think it's a typo. `!!` is a common idiom for converting any non-zero value into `1`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-21T17:57:35.017", "Id": "16271", "Score": "1", "body": "@JoeyAdams It won't convert anything to 1, it will convert it to non-zero. Though of course in practice, it will most likely be 1. A better way would be to write `(mask & dec_result) > 0` which will evaluate directly to boolean." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-21T18:57:57.917", "Id": "16273", "Score": "0", "body": "The expression `!a` yields 0 if `a` is non-zero, and 1 if `a` is zero. Thus, `!!a` yields 0 if `a` is 0, and 1 if `a` is non-zero. Link me to the standard if it says otherwise." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-23T09:00:08.960", "Id": "16341", "Score": "0", "body": "from documentation of `fgets`: If any characters are read and there is no error, a \\0 character is appended to end the string. So there is no mistake in `strlen` but one in `fgets` it should be `fgets(line, sizeof(line)-1, stdin);`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-20T11:07:21.027", "Id": "17557", "Score": "0", "body": "Clearly `!!(mask & dec_result)` is not that common because Lundin didn't know what it was for and neither did I, I think `(mask & dec_result) ? '1' : '0'` would have been a better version of that whole expression." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-21T15:19:17.533", "Id": "10220", "ParentId": "10186", "Score": "3" } }, { "body": "<p>Appearance is very nice, good attention to readability. Good consistency.</p>\n\n<ul>\n<li><p>Too many comments for my liking. Comments that are obvious from the context are just noise. For example a call to a function called 'parse' is not made any clearer by telling the reading that you are \"Calling the parser for the results\" - the reader can see that. However, my guess is that you have been instructed to insert such comments and would lose marks if you omitted them, so maybe you should ignore me.</p></li>\n<li><p>Opening braces in functions are normally at column 0.</p></li>\n<li><p>Variables are better declared on their own line (ie. one per line) - with a short comment on their purpose if necessary.</p></li>\n<li><p>Use an int for the operation type; using char saves nothing and may even cost extra cycles.... I see later that you have char for a purpose - misused.</p></li>\n<li><p>Arguably, it is better to return (eg) 0 on failure from your functions, letting the caller handle it, rather than to exit. If you exit, use EXIT_FAILURE, not 1.</p></li>\n<li><p>Excess comments in function headers. Repeating the types in the header is unwise; as programs are maintained, people forget to update headers when they change the code and so the types will become mismatched.</p></li>\n<li><p>Including local variables in headers seems excessive (see above too).</p></li>\n<li><p>Drop the text \"This function \" from headers - it can be assumed that you are describing the function.</p></li>\n</ul>\n\n<p>Comments on functions:</p>\n\n<p>check_string:</p>\n\n<ul>\n<li><p>Doesn't check for multiple operators or for the number of operands;</p></li>\n<li><p>for-loop could be replaced by strspn(input, \"01*/% \") != strlen(input)</p></li>\n<li><p>Input can be const</p></li>\n</ul>\n\n<p>parse:</p>\n\n<ul>\n<li><p>You assume bin_output size to be 17 bytes - you might at least state this in the header. Better to add a size parameter.</p></li>\n<li><p>Input can be const</p></li>\n<li><p>Call to strtok_r pretends that 'operation' is a nul-terminated string when it is really just a char. This is not reliable. Perhaps use strtol/strspn/strtol to separate parameters and operator?</p></li>\n<li><p>check_string() and parse() might be combined, as check_string does very little checking</p></li>\n<li><p>Overusing the ?: operator. A switch is more readable.</p></li>\n<li><p>Conversion to binary better extracted into a separate function. Then do it correctly - your conversion is junk (sorry, but it is true). </p></li>\n<li><p>Why not return dec_output rather than have an output parameter?</p></li>\n</ul>\n\n<p>main:</p>\n\n<ul>\n<li><p>Missing check for success of call to fgets</p></li>\n<li><p>Newline is removed without checking that it is there (if user ended input with ctrl-d, it will not be) and if line length is zero, you will zero line[-1]</p></li>\n<li><p>Return EXIT_SUCCESS rather than 0</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-21T15:52:58.733", "Id": "16260", "Score": "0", "body": "`\"Use an int for the operation type; using char saves nothing and may even cost extra cycles.... I see later that you have char for a purpose - misused.\"`. You are making assumptions about his hardware. On a 8-bit CPU char will be far more efficient than int." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-21T16:07:05.773", "Id": "16262", "Score": "0", "body": "@Lundin SCD used char so that he could misuse it later in the call to strtok_r in parse(). However, you are of course correct - but it is a realistic assumption :-)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-21T15:25:00.317", "Id": "10221", "ParentId": "10186", "Score": "0" } } ]
{ "AcceptedAnswerId": "10219", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-20T15:48:17.043", "Id": "10186", "Score": "4", "Tags": [ "c", "calculator" ], "Title": "Calculator supporting multiplication, division, or modulo of two numbers" }
10186
<p>This script fetches a list of "end-positions" from a MySQL database. The positions are array positions that are the same in both MySQL and R.</p> <p>Next, the script takes the previous 34 elements for each metric and calculates their correlation with a query series.</p> <p>The top X highest correlated (in total for each metric) and bottom X lowest correlated rows are saved.</p> <p>Finally the initial MySQL list is trimmed to contain only those highly correlated points.</p> <p>I am very new to R, and I am pretty sure that I did a very inefficient job of implementing this. I am looking for response times under 1 second in length.</p> <pre><code>#Executed during initialization: library(RODBC) library(stats) channel&lt;- odbcConnect("data") c&lt;-mat.or.vec(3000,5) #will hold correlations n1&lt;-seq(-33,0) z &lt;- sqlQuery(channel,"SELECT RPos,M1,M2,M3,M4 FROM `data`.`z` ") #Get whole series al_string &lt;- "select RPos,OpenTime FROM z JOIN actionlist on(OpenTime = pTime)" trim_string&lt;- "DELETE FROM ActionList WHERE OpenTime NOT IN (SELECT OpenTime FROM ReducedList)" #This segment is called repeatedly. Each time actionlist contains different positions. actionlist&lt;- sqlQuery(channel,al_string) #SIMULATION: (x will be filled by something else in reality) x &lt;- sqlQuery(channel,"SELECT z.pTime AS pTime,M1,M2,M3,M4 FROM z JOIN (SELECT pTime FROM z ORDER BY rand() limit 1) AS X ON (z.pTime&lt;=X.pTime AND z.pTime&gt; x.pTime-(300*34))") i&lt;-1 </code></pre> <p><strong>This is the part I am most interested in speeding up</strong>: </p> <pre><code>GetTopN&lt;-function(n) { for(i in 1:nrow(actionlist)) { c[i,1]&lt;-actionlist$OpenTime[i]; for(j in 2:ncol(z)) c[i,j]&lt;-cor(z[actionlist$RPos[i]+n1,j],x[,j]); } avc &lt;- (cbind(c[,1],rowSums(c[,2:5]))); topx &lt;- c[order(avc[,2], decreasing=T),1][1:n]; bottomx &lt;- c[order(avc[,2], decreasing=F),1][1:n]; DF&lt;-as.data.frame(c(topx,bottomx),row.names=NULL); colnames(DF)[1]&lt;-"OpenTime"; sqlSave(channel,dat=DF,tablename="ReducedList",append=FALSE,rownames=FALSE,safer=FALSE); sqlQuery(channel,trim_string); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-07T04:02:19.500", "Id": "16201", "Score": "5", "body": "Just off the top of my head: 1) Don't name things `c`. It's a very important base R function. 2) Now that you've renamed it, don't sort it twice. Sort it once, and then use `head` and `tail`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-07T11:33:48.913", "Id": "16202", "Score": "3", "body": "Also, change `c[i,1]<-actionlist$OpenTime[i]` to `c[,1]<-actionlist$OpenTime` and move it out of the loop." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-07T15:31:28.480", "Id": "16203", "Score": "1", "body": "Also, look at `?Rprof` to know how you can check which part of your function is slowing everything down." } ]
[ { "body": "<p>The comments are good; I copy them here so this question has a \"proper\" answer, and add some my own:</p>\n\n<blockquote>\n <p>Just off the top of my head: 1) Don't name things <code>c</code>. It's a very important base R function. 2) Now that you've renamed it, don't sort it twice. Sort it once, and then use <code>head</code> and <code>tail</code>. โ€“ joran</p>\n</blockquote>\n\n<p>and </p>\n\n<blockquote>\n <p>Also, change <code>c[i,1]&lt;-actionlist$OpenTime[i]</code> to <code>c[,1]&lt;-actionlist$OpenTime</code> and move it out of the loop. โ€“ Richie Cotton</p>\n</blockquote>\n\n<p>and</p>\n\n<blockquote>\n <p>Also, look at <code>?Rprof</code> to know how you can check which part of your function is slowing everything down. โ€“ Joris Meys</p>\n</blockquote>\n\n<p>This last is important; if you don't know where the code is slow, you don't know where to apply effort to speed it up.</p>\n\n<p>My comments are that, if you have a function that is doing some work, all the information that it needs should generally be passed in as arguments. It took me a bit to figure out what <code>c</code> and <code>z</code> (after I overcame the cognitive dissonance of thinking <code>c[i,1]</code> was itself an error).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T17:10:39.913", "Id": "36976", "ParentId": "10191", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-07T03:43:53.527", "Id": "10191", "Score": "2", "Tags": [ "optimization", "beginner", "mysql", "r" ], "Title": "Script for fetching a list of \"end-positions\" from a MySQL database" }
10191
<p>I have black and white <code>SDL_Surface</code> and I'm trying to change colors, such as from black to white and from white to red. I did it, but it is taking too long to work.</p> <pre><code>SDL_Surface* tempSurface = SDL_DisplayFormat(textSurface); for(int i=0;i&lt;256;i++){ SDL_SetColorKey(textSurface,SDL_SRCCOLORKEY,SDL_MapRGB(textSurface-&gt;format,i,i,i)); SDL_FillRect(tempSurface, 0, SDL_MapRGB(tempSurface-&gt;format, 255, i, i)); SDL_BlitSurface(textSurface,0,tempSurface,0); SDL_FreeSurface(textSurface); textSurface=tempSurface; tempSurface = SDL_DisplayFormat(textSurface); } SDL_FreeSurface(tempSurface); </code></pre> <p>It works for a few seconds, but it needs to run very fast. It is C code, but it is not important. SDL is compatible with both languages.</p> <p>How can I optimize this algorithm? Or can you suggest another way?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-20T19:03:18.203", "Id": "16205", "Score": "1", "body": "`C`? `C++`? So this is working but not fast enough?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-20T19:43:01.237", "Id": "16206", "Score": "0", "body": "Yes, it works for a few seconds, but it needs to run very fast.\nIt is C code, but it is not important. SDL is compatible with both languages." } ]
[ { "body": "<p>It would be helpful to know how textSurface is created. There may be a performance win to be had by using, say, a hardware surface instead of a software surface.</p>\n\n<p>If you are using a surface that supports double buffering I would reccomend using SDL_FLip rather than flipping the buffers yourself using 2 surfaces.</p>\n\n<p>E.g:</p>\n\n<pre><code>SDL_Surface* textSurface;\nif(!(textSurface = SDL_SetVideoMode(600, 400, 32, SDL_HWSURFACE)))\n SDL_Quit();\n\nSDL_SetColorKey(textSurface, SDL_SRCCOLORKEY, SDL_MapRGB(textSurface-&gt;format, 255, 0, 255)); //typically we use magenta\nfor(auto i=0; i&lt;256; i++){\n auto col = SDL_MapRGB(textSurface-&gt;format, i, i, i);\n std::cout &lt;&lt; col &lt;&lt; \",\" &lt;&lt; SDL_FillRect(textSurface, 0, col) &lt;&lt; std::endl;\n SDL_Flip(textSurface);\n}\n</code></pre>\n\n<p>Note that for your current goal, there is no need to reset the ColorKey each time around the loop.</p>\n\n<p>If you want to run faster than \"a few seconds\" you certainly won't need to display all 256 intermediate colours to achieve the desired effect. </p>\n\n<pre><code>SDL_Surface* textSurface;\nif(!(textSurface = SDL_SetVideoMode(600, 400, 32, SDL_HWSURFACE)))\n SDL_Quit();\n\nSDL_SetColorKey(textSurface, SDL_SRCCOLORKEY, SDL_MapRGB(textSurface-&gt;format, 255, 0, 255)); //typically we use magenta\nauto frame_increment = 4;\nfor(auto i=0; i&lt;256; i += frame_increment){\n auto col = SDL_MapRGB(textSurface-&gt;format, i, i, i);\n std::cout &lt;&lt; col &lt;&lt; \",\" &lt;&lt; SDL_FillRect(textSurface, 0, col) &lt;&lt; std::endl;\n SDL_Flip(textSurface);\n}\n</code></pre>\n\n<p>You should determine <code>frame_increment</code> based on your desired time and hardware capabilities.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-16T08:36:11.157", "Id": "17377", "Score": "0", "body": "This routine fills screen with white color only. It draws 256 filled rectangles on surface. I can't receive the result using this code. Or, may be, I not understand something in this algorithm?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-13T18:13:56.777", "Id": "10869", "ParentId": "10193", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-20T18:52:59.543", "Id": "10193", "Score": "3", "Tags": [ "c++", "optimization", "c", "sdl" ], "Title": "Colors changing in SDL program" }
10193
<p>I have about 5 of these but I can't figure out how to consolidate them.</p> <pre><code>$('#togglemass').toggle(function () { $("#plusmass").attr("src", "minus.png"); }, function () { $(".plusmass").attr("src", "plus.png"); }); $('#togglestar').toggle(function () { $(".plusstar").attr("src", "minus.png"); }, function () { $(".plusstar").attr("src", "plus.png"); }); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-21T09:03:14.777", "Id": "16232", "Score": "1", "body": "You should explain your use case and show the HTML to this, because I think the optimization could start on the HTML level. For example, I think you should't need to hard code the selector to the \"plus\" image in the JavaScript, but refer to it via the HTML structure." } ]
[ { "body": "<pre><code>$(function() {\n\n var togglePlusMin = function(clicker, img) {\n $(clicker).toggle(function() {\n $(img).attr(\"src\", \"minus.png\");\n }, function() {\n $(img).attr(\"src\", \"plus.png\");\n });\n };\n\n // can be used by\n togglePlusMin('#togglemass', '#plusmass'); \n\n // BONUS: this will also work:\n var star = $('#togglestar'),\n starIcon = $('img.plusstar');\n\n togglePlusMin(star, starIcon);\n})\n</code></pre>\n\n<p>As a comment, its generally a bad idea to use ids without <a href=\"http://api.jquery.com/jQuery/\" rel=\"nofollow\">a second context parameter</a> </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-21T02:43:02.353", "Id": "16224", "Score": "0", "body": "I have the worst luck, this is the 2nd time in a week someone beat me to an answer by a few seconds." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-21T02:36:47.253", "Id": "10202", "ParentId": "10196", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-20T20:34:27.760", "Id": "10196", "Score": "2", "Tags": [ "javascript", "jquery" ], "Title": "Toggling icon images using jQuery" }
10196
<p>I have three tables</p> <pre><code>class User &lt; AR::Base has_many :lexemes, :dependent =&gt; :destroy end class Lexeme &lt; AR::Base belongs_to :user belongs_to :word end class Word &lt; AR::Base has_many :lexemes end </code></pre> <p>This code is storing the word to Words table and assign it to the user.</p> <pre><code>word = Word.where(:word=&gt;token).first_or_create lexeme = @user.lexemes.where(:word_id=&gt;word.id).first_or_create </code></pre> <p>I don't like my code, so is it possible to improve it? Thanks </p>
[]
[ { "body": "<pre><code>class User &lt; AR::Base\n has_many :lexemes, :dependent =&gt; :destroy\n has_many :words, :through =&gt; :lexemes\nend\n\nclass Lexeme &lt; AR::Base\n belongs_to :user\n belongs_to :word\nend\n\nclass Word &lt; AR::Base\n has_many :lexemes\n has_many :users, :through =&gt; :lexemes\nend\n</code></pre>\n\n<p>You should normally be able to create word by following code but it seems there is <a href=\"https://github.com/rails/rails/issues/5325\" rel=\"nofollow\">a bug in Rails</a>.</p>\n\n<pre><code>word = @user.words.find_or_create_by_word(token)\n</code></pre>\n\n<p>Therefore I have changed the model to following. You may remove it when the bug is fixed.</p>\n\n<pre><code>class User &lt; ActiveRecord::Base\n has_many :lexemes\n has_many :words, :through =&gt; :lexemes do\n def find_or_create_by_word(token)\n find_by_word(token) || create(:word =&gt; token)\n end\n end\nend\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-24T19:54:49.657", "Id": "17768", "Score": "1", "body": "`first_or_create` considered to be a clearer alternative for `find_or_create_by_xxx`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-29T11:31:54.197", "Id": "18148", "Score": "0", "body": "@Alexey it had the same bug, overriding find_or_create_by_xxx was a better option. Thanks for the tip." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-01T12:17:32.060", "Id": "10543", "ParentId": "10197", "Score": "2" } } ]
{ "AcceptedAnswerId": "10543", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-20T20:39:03.990", "Id": "10197", "Score": "1", "Tags": [ "ruby", "ruby-on-rails" ], "Title": "activerecord, refactoring the source code" }
10197
<p>This class is used to draw an old school flame on a canvas element. I'm wondering if there is any way to speed up the <code>fire</code> method. The class is based on old C code.</p> <pre><code>LayerFire = { init : function(options, elem) { this.options = $.extend({ width : '320', height : '240' }, this.options, options); this.elem = elem; this.$elem = $(elem); // Create our buffer this.bufferp = []; this.buffer = []; var i = this.options.width * this.options.height * 4; while (i--) { this.bufferp[i] = 0; this.buffer[i] = 0; } // Create the palette this.palette = []; this.makePalette(); // Initilize our main loop var t = this; this.updater = setInterval(function() {t.fire.apply(t);}, 125); }, makePalette : function () { // make a nice looking color palette for a flame for (i = 0; i &lt; 256; i++) { this.palette[i] = Object.create(VideoColor); } for (i = 0; i &lt; 32; i++) { /* black to blue, 32 values*/ this.palette[i].b = i &lt;&lt; 1; this.palette[i].a = 255; /* blue to red, 32 values*/ this.palette[i + 32].r = i &lt;&lt; 3; this.palette[i + 32].b = 64 - (i &lt;&lt; 1); this.palette[i + 32].a = 255; /*red to yellow, 32 values*/ this.palette[i + 64].r = 255; this.palette[i + 64].g = i &lt;&lt; 3; this.palette[i + 64].a = 255; /* yellow to white, 162 */ this.palette[i + 96].r = 255; this.palette[i + 96].g = 255; this.palette[i + 96].b = i &lt;&lt; 2; this.palette[i + 96].a = 255; this.palette[i + 128].r = 255; this.palette[i + 128].g = 255; this.palette[i + 128].b = 64 + (i &lt;&lt; 2); this.palette[i + 128].a = 255; this.palette[i + 160].r = 255; this.palette[i + 160].g = 255; this.palette[i + 160].b = 128 + (i &lt;&lt; 2); this.palette[i + 160].a = 255; this.palette[i + 192].r = 255; this.palette[i + 192].g = 255; this.palette[i + 192].b = 192 + i; this.palette[i + 192].a = 255; this.palette[i + 224].r = 255; this.palette[i + 224].g = 255; this.palette[i + 224].b = 224 + i; this.palette[i + 224].a = 255; } }, fire : function() { // create a ransom flame at the bottom of the screen y = this.options.width * (this.options.height- 1); for (x = 0; x &lt; this.options.width; x+=3) { var random = 1 + (16 * ((Math.random() * 32767) / 32767) + 1.0); if (random &gt; 11) { /*hot*/ this.bufferp[y + x] = 200; this.bufferp[y + x + 1] = 255; this.bufferp[y + x + 2] = 200; } else { this.bufferp[y + x] = 50; this.bufferp[y + x + 1] = 20; this.bufferp[y + x + 2] = 50; } } // move the flame up var top = this.options.height; if (top &gt; 110) top = 110; for (index = 0; index &lt; top ; ++index) { for (x = 0; x &lt; this.options.width; x++) { if (x == 0) /* at the left border*/ { temp = this.bufferp[y]; temp += this.bufferp[y + 1]; temp += this.bufferp[y - this.options.width]; temp /= 3; } else if (x == this.options.width - 1) /* at the right border*/ { temp = this.bufferp[y + x]; temp += this.bufferp[y - this.options.width + x]; temp += this.bufferp[y + x - 1]; temp /= 3; } else { temp = this.bufferp[y + x]; temp += this.bufferp[y + x + 1]; temp += this.bufferp[y + x - 1]; temp += this.bufferp[y - this.options.width + x]; temp /= 4; } if (temp &gt; 1) temp -= 1; /* decay */ this.bufferp[y - this.options.width + x] = Math.round(temp); } y -= this.options.width; } // copy the palette buffer to display buffer for (x = 0; x &lt; this.options.width; x++) { for (y = 0; y &lt; this.options.height; y++) { var index = (y * this.options.width + x) * 4; var c = this.bufferp[(y * this.options.width) + x]; //console.log(c); this.buffer[index+0] = this.palette[c].r; this.buffer[index+1] = this.palette[c].g; this.buffer[index+2] = this.palette[c].b; this.buffer[index+3] = this.palette[c].a; } } } }; </code></pre> <p>Working demo <a href="http://jsfiddle.net/jzaun/qscru/" rel="nofollow">here</a>.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-21T03:29:57.707", "Id": "16225", "Score": "2", "body": "Do you have a runnable example (perhaps in a jsFiddle)? It's hard to run performance tests on a piece of code that you can't run because you're missing pieces that are need to make it run or don't know what sequence to call it to make it run." } ]
[ { "body": "<p>I'm not really an expert on speed optimization, but here are some thoughts:</p>\n\n<ul>\n<li>You should keep references/copies to often used objects/values instead of accessing them repeatedly through properties, e.g:</li>\n</ul>\n\n<p><b></b></p>\n\n<pre><code>var bufferp = this.bufferp;\nvar width = this.options.width;\nvar height = this.options.height;\n</code></pre>\n\n<ul>\n<li><p>There are some variables (such as <code>x</code> and <code>y</code> which you haven't declared as local with <code>var</code>).</p></li>\n<li><p>What is the point of <code>(Math.random() * 32767) / 32767</code>? As far as I can tell it does nothing.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-21T08:55:02.400", "Id": "10206", "ParentId": "10201", "Score": "1" } }, { "body": "<p>(Math.random() * 32767) / 32767 - induced giggles. :)</p>\n\n<p>(Not very helpful I know but hey, โ€˜we canโ€™t all be Astronautsโ€™)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-12-23T10:29:04.220", "Id": "349306", "Score": "1", "body": "This looks a comment to [RoToRa's answer](https://codereview.stackexchange.com/a/10206/93149) - just comment there, and or post your own [answer](https://codereview.stackexchange.com/help/how-to-answer)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-12-23T10:12:58.827", "Id": "183492", "ParentId": "10201", "Score": "-2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-21T02:36:33.080", "Id": "10201", "Score": "3", "Tags": [ "javascript", "optimization" ], "Title": "Optimization of a javascript class flame effect" }
10201
<p>I've come up with a simple Datasource design which allows me to quickly create Datasources and even abstract it behind Interfaces. Of course I ask myself if I can do something better.</p> <p>The goal of these classes is to have a simple and easily exchangeable layer which just returns Objects. By easily exchangeable I mean that it can be extracted into an Interface and can then be easily swapped.</p> <p>Please assume the following things:</p> <ul> <li>CustomConnection is derived from IDbConnection, Third-Party.</li> <li>CustomConnection is not thread-safe.</li> <li>CustomCommand supports named parameters.</li> <li>Item is an arbitrary class holding <em>something</em>.</li> <li>The layout of Item matches that of the database (Properties == Constructor == Columns).</li> </ul> <hr> <pre><code>public class DataSource : IDisposable { private Object sync = new Object(); private CustomConnection connection; private CustomCommand itemGetter; private CustomCommand itemSearcher; public DataSource(string server, string database, string username, string password) { connection = new CustomConnection("ConnectionStringGoesHere"); } // Yes, I'm aware that this might throw an exception. public void Open() { connection.Open(); CheckConnection(); // Create the commands itemGetter = connection.CreateCommand(); itemGetter.CommandText = @" SELECT someColumn, secondColumn, thirdColumn FROM someTable WHERE someOtherColumn = @UNIQUE OR evenMoreColumns = @UNIQUE LIMIT 1;"; itemGetter.Parameters.Add("UNIQUE", CustomDbType.VarChar); itemSearcher = connection.CreateCommand(); itemSearcher.CommandText = @" SELECT someColumn, secondColumn, thirdColumn FROM someTable WHERE someOtherColumn LIKE @SEARCH OR evenMoreColumns LIKE @SEARCH OR manyMoreColumns LIKE @SEARCH;"; itemSearcher.Parameters.Add("SEARCH", CustomDbType.VarChar); } public Item GetItem(string unique) { lock(sync) { CheckConnection(); if (string.IsNullOrEmpty(unique)) { return null; } itemGetter.Parameters["UNIQUE"].Value = unique; using (CustomDataReader reader = itemGetter.ExecuteReader()) { if (reader.Read()) { int field = 0; return new Item( (string)reader[field++], (int)reader[field++], (decimal)reader[field++]); } } return null; } } public Item[] GetItems(string search) { lock(sync) { CheckConnection(); if (string.IsNullOrEmpty(search)) { return new Item() {}; } itemSearcher.Parameters["SEARCH"].Value = search; List&lt;Item&gt; items = new List&lt;Item&gt;(); using (CustomDataReader reader = itemSearcher.ExecuteReader()) { while (reader.Read()) { int field = 0; items.Add(new Item( (string)reader[field++], (int)reader[field++], (decimal)reader[field++])); } } return items.ToArray(); } } protected void CheckConnection() { if (connection == null) { throw new Exception("Connection is null!"); } if (connection.State == System.Data.ConnectionState.Broken || connection.State == System.Data.ConnectionState.Closed) { throw new Exception("Connection is unusable!"); } } #region IDisposable Member private bool disposed; public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!this.disposed) { if (disposing) { if (itemGetter != null) { itemGetter.Dispose(); itemGetter = null; } if (itemSearcher != null) { itemSearcher.Dispose(); itemSearcher = null; } if (connection != null) { connection.Dispose(); connection = null; } } disposed = true; } } #endregion } } </code></pre> <hr> <p>In the mean time I've "refined(?)" my approach by using some sort of lazy creation for the queries, so that those get only created if it is necessary.</p> <p>Checking of the connection is also gone, as it added nothing of value to it.</p> <pre><code>public class DataSource : IDisposable { private Object sync = new Object(); private CustomConnection connection; private CustomCommand itemGetter; private CustomCommand itemSearcher; public DataSource(String server, String database, String username, String password) { this.connection = new CustomConnection("ConnectionStringGoesHere"); } public void Open() { connection.Open(); } public Item GetItem(String unique) { lock(sync) { if (itemGetter == null) { itemGetter = connection.CreateCommand(); itemGetter.CommandText = @" SELECT someColumn, secondColumn, thirdColumn FROM someTable WHERE someOtherColumn = @UNIQUE OR evenMoreColumns = @UNIQUE LIMIT 1;"; itemGetter.Parameters.Add("UNIQUE", CustomDbType.VarChar); } if (String.IsNullOrEmpty(unique)) { return null; } itemGetter.Parameters["UNIQUE"].Value = unique; using (CustomDataReader reader = itemGetter.ExecuteReader()) { if (reader.Read()) { int field = 0; return new Item( (String)reader[field++], (int)reader[field++], (decimal)reader[field++]); } } return null; } } public Item[] GetItems(String search) { lock(sync) { if (itemSearcher == null) { itemSearcher = connection.CreateCommand(); itemSearcher.CommandText = @" SELECT someColumn, secondColumn, thirdColumn FROM someTable WHERE someOtherColumn LIKE @SEARCH OR evenMoreColumns LIKE @SEARCH OR manyMoreColumns LIKE @SEARCH;"; itemSearcher.Parameters.Add("SEARCH", CustomDbType.VarChar); } if (String.IsNullOrEmpty(search)) { return new Item() {}; } itemSearcher.Parameters["SEARCH"].Value = search; List&lt;Item&gt; items = new List&lt;Item&gt;(); using (CustomDataReader reader = itemSearcher.ExecuteReader()) { while (reader.Read()) { int field = 0; items.Add(new Item( (String)reader[field++], (int)reader[field++], (decimal)reader[field++])); } } return items.ToArray(); } } #region IDisposable Member private bool disposed; public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!this.disposed) { if (disposing) { if (itemGetter != null) { itemGetter.Dispose(); } if (itemSearcher != null) { itemSearcher.Dispose(); } if (connection != null) { connection.Dispose(); } } disposed = true; } } #endregion } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-21T10:25:05.940", "Id": "16234", "Score": "0", "body": "Have you considered using one of the simple one-file ORMs such as Dapper instead?\n\nhttp://code.google.com/p/dapper-dot-net/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-21T10:29:43.833", "Id": "16236", "Score": "0", "body": "@Den: Yes, but at the moment the target is .NET 2.0. So every ORM I've seen so far fell flat." } ]
[ { "body": "<p>You can move parameter checks out of locks:</p>\n\n<pre><code>public Item[] GetItems(string search)\n{\n if (string.IsNullOrEmpty(search))\n return new Item() {};\n\n lock(sync)\n {\n CheckConnection();\n\n itemSearcher.Parameters[\"SEARCH\"].Value = search;\n\n List&lt;Item&gt; items = new List&lt;Item&gt;();\n using (CustomDataReader reader = itemSearcher.ExecuteReader())\n {\n while (reader.Read())\n {\n int field = 0;\n items.Add(new Item(\n (string)reader[field++],\n (int)reader[field++],\n (decimal)reader[field++]));\n }\n }\n\n return items.ToArray();\n }\n}\n</code></pre>\n\n<p>Also, I think you are missing finalizer in your Dispose pattern.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-21T10:57:33.653", "Id": "16237", "Score": "1", "body": "Why do you need locking at all by the way? Can't you create commands each time?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-21T10:51:47.997", "Id": "10210", "ParentId": "10207", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-21T10:04:37.607", "Id": "10207", "Score": "0", "Tags": [ "c#" ], "Title": "Simple Datasource design using connections derived from System.Data.IDbConnection" }
10207
<p>I've written a small function which displays a div related to an anchor element using data attributes.</p> <p>The data attribute is used to match the class of the relevant div which is then displayed whilst the others are hidden.</p> <p>All very basic, however I'm wondering if there is anyway to improve it? Is there a better solution than using the data attribute? Any best practices?</p> <pre><code>$(&quot;.tabs li a&quot;).click(function() { var cssClass = &quot;.&quot; + $(this).data(&quot;class&quot;); // Add active class to current tab, remove from siblings $(this).addClass(&quot;active&quot;).parent().siblings().find(&quot;a&quot;).removeClass(&quot;active&quot;); // Find the associated content and show it, hide its siblings $(&quot;.tabs-content&quot;).find(cssClass).show().siblings().hide(); return false; }); </code></pre> <p><a href="http://jsfiddle.net/Damian/JveaJ/" rel="nofollow noreferrer">jsfiddle example here</a></p> <hr /> <h3>Edit</h3> <p>This ended up being re-written for production using classes instead of data attributes, like so:</p> <pre><code>$(&quot;.tabs li a&quot;).click(function() { var cssClass = &quot;.&quot; + $(this).attr(&quot;class&quot;); $('.tabs a.active').removeClass(&quot;active&quot;); // Find the previously active tab and remove it $(this).addClass(&quot;active&quot;); // Add active class to current tab $(&quot;.tabs-content&quot;).find('&gt; div').hide(); // Hide the all tab divs $(&quot;.tabs-content&quot;).find(cssClass).show() // Find the associated div and display it return false; });โ€‹ </code></pre> <p><a href="http://jsfiddle.net/Damian/JveaJ/12/" rel="nofollow noreferrer">Updated jsfiddle</a></p>
[]
[ { "body": "<p><code>$(\".tabs-content\").find(cssClass).show().siblings().hide();</code> is confusing and not easy to read.</p>\n\n<p>Otherwise it seems to be working. As for best practices:</p>\n\n<ul>\n<li>Make sure your content is accessible to non JS users, such as search engines or browsers without JS.</li>\n<li>Consider using the <a href=\"http://twitter.github.com/bootstrap/javascript.html#tabs\" rel=\"nofollow\">Bootstrap tab plugin</a> or <a href=\"http://jqueryui.com/demos/tabs/\" rel=\"nofollow\">jQuery UI tab functionality</a>. Of course if you don't already use one of those, keep your simple jQuery function.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-21T17:46:10.337", "Id": "16270", "Score": "0", "body": "Thanks Cygal, I've broken the confusing line down into two lines ([jsfiddle updated](http://jsfiddle.net/Damian/JveaJ/)). I'm using the modernizr library so I can add rules to display the content to non JS users. I've also built the site using [ZURB's foundation framework](http://foundation.zurb.com/) which includes a tab plugin, I just have to use IDs rather than classes in my markup.." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-21T14:06:43.957", "Id": "10218", "ParentId": "10211", "Score": "1" } }, { "body": "<p>Agree with cygal, I would however use the id(#hash) to call the tabcontent</p>\n\n<pre><code>var tabs = function(){\n\n var tabContent = $(\".tabcontent\"),\n tabMenu = $(\"ul.tabs\");\n\n tabContent.hide().filter(\":first\").show();\n\n $(\"ul.tabs li a\").on('click', function(){\n\n tabMenu.find(\"li\").removeClass(\"active\");\n\n $(this).parent().addClass(\"active\");\n\n tabContent.filter(this.hash).fadeIn('slow'); \n\n return false;\n\n }).filter(\":first\").click(); //trigger click on first anchor so active class is added\n}\n\n//invoke\ntabs();\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-21T21:07:28.117", "Id": "10228", "ParentId": "10211", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-21T11:07:34.177", "Id": "10211", "Score": "2", "Tags": [ "javascript", "jquery", "html" ], "Title": "jQuery tabs improvement" }
10211
<p>I just wrote some code that is very representative of a recurring theme (in my coding world lately): repeated logic leads to an instinct to eliminate duplication which results in something that is more complex the tradeoff seems wrong to me (the examples of the negative side aren't worth posting - but this is probably the 20th console utility I've written in the past 12 months).</p> <p>I'm curious if I'm missing some techniques or if this is really just on of those "experience tells you when to do what" type of issues.</p> <p>Here's the code... I'm tempted to leave it as is, even though there will be about 20 of those if-blocks when I'm done. </p> <pre><code>static void Main(string[] sargs) { try { var urls = new DirectTrackRestUrls(); var restCall = new DirectTrackRestCall(); var logger = new ConsoleLogger(); Args args = (Args)Enum.Parse(typeof(Args), string.Join(",", sargs)); if (args.HasFlag(Args.Campaigns)) { var getter = new ResourceGetter(logger, urls.ListAdvertisers, restCall); restCall.UriVariables.Add("access_id", 1); getter.GotResource += new ResourceGetter.GotResourceEventHandler(getter_GotResource); getter.GetResources(); SaveResources(); } if (args.HasFlag(Args.Advertisers)) { var getter = new ResourceGetter(logger, urls.ListAdvertisers, restCall); restCall.UriVariables.Add("access_id", 1); getter.GotResource += new ResourceGetter.GotResourceEventHandler(getter_GotResource); getter.GetResources(); SaveResources(); } if (args.HasFlag(Args.CampaignGroups)) { var getter = new ResourceGetter(logger, urls.ListCampaignGroups, restCall); getter.GotResource += new ResourceGetter.GotResourceEventHandler(getter_GotResource); getter.GetResources(); SaveResources(); } } catch (Exception e) { Console.WriteLine(e.InnerException); Console.WriteLine(e.StackTrace); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-20T21:38:02.960", "Id": "16239", "Score": "1", "body": "As phrased this question would appear to be better asked on Stack Overflow, however, with a change of wording (\"How can I/should I improve this code\") then it would be suitable for Code Review. As it stands there's a very good chance it will get closed here." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-20T21:41:09.660", "Id": "16240", "Score": "0", "body": "I realized that after I saw the answers... but I did get a good answer, for my purposes I'm happy (although it may not have served the collective in the optimal way)" } ]
[ { "body": "<p>Why not something like...</p>\n\n<pre><code>static void Main(string[] sargs)\n{\n try\n {\n var urls = new DirectTrackRestUrls();\n var restCall = new DirectTrackRestCall();\n var logger = new ConsoleLogger();\n Args args = (Args)Enum.Parse(typeof(Args), string.Join(\",\", sargs));\n if (args.HasFlag(Args.Campaigns))\n {\n GetAndSaveResources(urls.ListAdvertisers, true);\n } \n if (args.HasFlag(Args.Advertisers))\n {\n GetAndSaveResources(urls.ListAdvertisers, true);\n }\n if (args.HasFlag(Args.CampaignGroups))\n {\n GetAndSaveResources(urls.ListCampaignGroups, false);\n }\n }\n catch (Exception e)\n {\n Console.WriteLine(e.InnerException);\n Console.WriteLine(e.StackTrace);\n }\n}\n\nvoid GetAndSaveResources(IList list, bool setAccessId) {\n var getter = new ResourceGetter(logger, list, restCall);\n if (setAccessId)\n restCall.UriVariables.Add(\"access_id\", 1);\n getter.GotResource += new ResourceGetter.GotResourceEventHandler(getter_GotResource);\n getter.GetResources();\n SaveResources();\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-20T21:08:29.407", "Id": "16241", "Score": "0", "body": "This doesn't currently have proper variable scoping...the getter should probably come out of the function, and get passed in." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-20T21:24:12.827", "Id": "16242", "Score": "0", "body": "i've never seen the function keyword in c# - is that real?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-20T21:36:08.200", "Id": "16243", "Score": "1", "body": "hey I just wanted to thank you - i re-wrote it your way and it's better - i had been going down the road of using containers to auto construct objects, but your DRY style is the piece of the puzzle I was not considering" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-20T21:49:37.953", "Id": "16244", "Score": "0", "body": "@Gabriel, ya, get rid of that `function`. I've been coding too much in javascript lately." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-20T21:00:38.683", "Id": "10215", "ParentId": "10214", "Score": "6" } }, { "body": "<blockquote>\n <p>\"I'm curious if I'm missing some techniques or if this is really just on of those \"experience tells you when to do what\" type of issues.\". </p>\n</blockquote>\n\n<p>There are tools that will show you where you've duplicated code. Look into Atomiq or CodeRush if you're using Visual Studio.</p>\n\n<p>Aside from that, Chad's reply looks to have refactored your code in a <a href=\"http://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow\">DRY</a> manner. You should be obsessive about not copying and pasting code because it causes huge maintainability issues.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-21T15:44:48.770", "Id": "16256", "Score": "0", "body": "Yes, every time you copy/paste in code, it should be cause for pause." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-20T21:09:43.830", "Id": "10216", "ParentId": "10214", "Score": "3" } } ]
{ "AcceptedAnswerId": "10215", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-20T20:54:19.757", "Id": "10214", "Score": "3", "Tags": [ "c#" ], "Title": "How to deal with elimination of duplicate logic vs. cost of complexity increase?" }
10214
<p>I just began to study Scala (coming from Python I had quite a few problems with types) and I want to know if my first code to solve a real problem is nicely done or if there is some points that need to be redone.</p> <p>The problem I had to solve is for an homework but my code is already working, I just want to know if it be more <em>Scalish</em>:</p> <blockquote> <p><strong>Problem description</strong></p> <p>We have \$k\$ containers, where \$3 โ‰ค k โ‰ค 10\$. Container \$i\$ has a certain integer capacity \$c_i &gt; 0\$ (of liters of water). Initially, container \$i\$ contains an integer amount \$a_i โ‰ฅ 0\$ of water. We are allowed to perform only one kind of operations: Take one container \$i\$, and pour its contents into a different container \$j\$. Pouring stops when either \$i\$ becomes empty, or \$j\$ becomes full (so after the operation either \$a_i = 0\$ or \$a_j = c_j\$).</p> <p>Is it possible to achieve a certain target configuration, and, if so, how?</p> <p>For instance, let's assume we have three containers with capacities \$10L\$, \$7L\$, and \$4L\$. Initially, the \$7L\$ and \$4L\$ container are full, while the \$10L\$ container is empty. The question is if we can achieve that the \$4L\$ container contains exactly \$2L\$ of water.</p> <p>With our notation, we have \$k = 3\$, \$c_1 = 10\$, \$c_2 = 7\$, \$c_3 = 4\$, \$a_1 = 0\$, \$a_2 = 7\$, and \$a_3 = 4\$. The question is: Is it possible to reach \$a_3 = 2\$?</p> <p>The answer is yes, and here is a possible sequence of moves (displayed in reverse order):</p> <pre><code>2 7 2 2 5 4 6 5 0 6 1 4 10 1 0 4 7 0 0 7 4 </code></pre> </blockquote> <p>I solved the problem using BFS on a graph I'm building at every step.</p> <pre><code>import collection.mutable.HashSet import collection.mutable.Queue import collection.mutable.ArraySeq import scala.io.Source import java.io.File case class Container(capacity: Int, filled: Int) { // overload + and - methods def +(toAdd: Int) = { assert (filled + toAdd &lt;= capacity, { println("Too much water in container")}) new Container(capacity, filled + toAdd) } def -(toSub: Int) = { assert (filled - toSub &gt;= 0, { println("Not enough water in container")}) new Container(capacity, filled - toSub) } // how much can we pour into an other container ? def howMuchToPour(other: Container) = math.min(filled, other.capacity - other.filled) // just print the filling level when printing a Container override def toString(): String = filled.toString; } case class State(containers : ArraySeq[Container]) { var parent:State = _ // returns all the ancesters of a State def ancesters() : List[State] = if (Option(parent) != None) parent :: parent.ancesters else List[State]() // returns a new State with i-th container poured into j-th container // no check if it's possible or not def pour(i: Int, j: Int, q: Int) = { val new_containers = containers.slice(0, containers.length) // make a copy new_containers(i) = containers(i) - q new_containers(j) = containers(j) + q val ns = State(new_containers) ns.parent = this ns } override def toString(): String = containers map{_ toString} mkString "\t" def next_states() = for { i &lt;- (0 until containers.length); j &lt;- (0 until containers.length) q = containers(i) howMuchToPour containers(j) if (i !=j) &amp;&amp; q &gt; 0 } yield pour(i, j, q) } object Pouring { def _bfs(start: State, condition: (State) =&gt; Boolean) : List[State] = { val q = Queue[State]() val seen = HashSet[State]() q += start seen += start while (q.length &gt; 0) { val s = q.dequeue() if (condition(s)) return s :: s.ancesters s.next_states().foreach(ns =&gt; { if (!seen.contains(ns)) { q += ns seen += ns } }) } List[State]() } def solve(problem:Seq[Array[Int]]) { val state = State(problem(1).zip(problem(2)).map(x =&gt; Container(x._1, x._2))) val cond_funcs = for { (filled, index) &lt;- problem(3).zipWithIndex .filter(x =&gt; x._1 != 0) } yield (x:State) =&gt; x.containers(index).filled == filled _bfs(state, (x) =&gt; cond_funcs.forall(_(x))) .reverse .foreach(s =&gt; println(s)) } def main (args: Array[String]) = { solve(Array(Array(3), Array(10, 7, 4), Array(0, 7, 4), Array(0, 0, 2))) } } </code></pre> <p>The points that I think can be improved but don't know how:</p> <ul> <li>The parent member of <code>State</code> is a <code>var</code>. Would it be possible to instantiate an object <code>State</code> with a parent member? I tried but I couldn't since the first State has no parent.</li> <li>This could probably be done using iterators, but I don't know much about that yet.</li> </ul>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-22T12:23:59.547", "Id": "16305", "Score": "0", "body": "`new Container(capacity, filled + toAdd)` -> no `new` needed for case classes." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-16T03:23:25.827", "Id": "18906", "Score": "0", "body": "Trying to learn from the code that's presented here. What's the purpose of the following line val state = State(problem(1).zip(problem(2)).map(x => Container(x._1, x._2))). I understand the zip but I am confused about the map and how it applies over the State class?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-16T04:23:25.750", "Id": "18907", "Score": "0", "body": "nevermind..I read the statement wrong. The zip and the corresponding map is passed as an argument in the State. I missed the params enclosing the operation." } ]
[ { "body": "<p>It seems pretty reasonable, actually. I'm confused by the <code>ArraySeq</code>. Also, I'd rewrite this:</p>\n\n<pre><code> if (Option(parent) != None) parent :: parent.ancesters\n else List[State]()\n</code></pre>\n\n<p>As</p>\n\n<pre><code> Option(parent).map(parent =&gt; parent :: parent.ancesters).getOrElse(List[State]())\n</code></pre>\n\n<p>That is, <em>if</em> used <code>parent</code> as you did. I'd make it an <code>Option</code> instead, and initialize it at creation.</p>\n\n<p>I'm not sure <code>Iterator</code> would help you here, but <code>Stream</code> might. I just don't think it is a particular good fit for BFS, but it might just be ignorance on my part.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-22T05:33:37.150", "Id": "16295", "Score": "0", "body": "OK. I looked up for Option and I think this is actually what I wanted.\n\nI've put :\n`case class State(containers : ArraySeq[Container], parent: Option[State] = None) {`\n\n`def ancesters() : List[State] = this.parent match { \n case Some(parent) => parent :: parent.ancesters\n case None => List[State]()\n }`\n\nNow my first state is created without \"parent\" parameter and when I create a new State when pouring:\n\n`State(new_containers, Option(this))`\n\nI think this is good right ?\n\nThank you very much for the advice :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-22T06:18:46.393", "Id": "16297", "Score": "0", "body": "I had also to redefine hashCode and equals in order not take account of member \"parent\"." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-22T13:13:11.753", "Id": "16308", "Score": "0", "body": "@PatrickBrowne Instead of modifying `hashCode` and `equals`, you could have `parent` on a second parameter list. IIRC, only stuff in the first parameter list is taken into account on the auto-generated methods." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-24T14:28:18.590", "Id": "16406", "Score": "0", "body": "I don't see how I can put parent in a second parameter list. As I understood, in Scala when you want to add another constructor, it has to call the first constructor and this is why you have to put the most generic constructor first. In my case, the most generic constructor is the one with parent so I can't put it as the second one. Am I wrong ?\n\nBy the way, I used ArraySeq because one ArraySeq is considered equal with another if they have the same content. This is not true for Array." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-24T14:39:07.047", "Id": "16408", "Score": "0", "body": "@PatrickBrowne `case class State(containers : ArraySeq[Container])(parent: Option[State] = None)`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-24T14:42:02.630", "Id": "16409", "Score": "0", "body": "@PatrickBrowne And, as for `ArraySeq`, the thing is that this is an unusual collection. If you don't want to mutate it, `Vector` would be more indicated. If you do want to mutate it, one of the `Buffer` classes is usually more appropriate." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-24T15:09:00.990", "Id": "16410", "Score": "0", "body": "OK, it works with a second parameter list and the ArrayBuffer but I somewhat find the syntax val a = State(elements)(parent) a bit weird :) Anyway, thank you very much for your time and answers !" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-22T00:51:48.843", "Id": "10233", "ParentId": "10224", "Score": "2" } }, { "body": "<p>The algorithm is more important than code style. I haven't given it much thought, but it seems that this might be solvable with dynamical programming, or some more efficient method than brute force search. Also, the brute force search algorithm will run for ever if there is no solution. I implemented below a slightly modified version of your algorithm, where I keep track of visited states. It increases performance and it does terminate.</p>\n\n<p>As mentioned in another answer, it's better to use <code>List</code> or <code>Stream</code> rather than arrays. Your loops over array indices are very un-functional.</p>\n\n<p>You did use immutable data structures, except <code>ArraySeq</code>.</p>\n\n<p>Instead of your main <code>while</code>-loop, I am using a recursive function. It's always possible to get rid of loops (for/while) using recursive functions. It's not wrong at all to use a <code>while</code>-loop; it's just more \"functional\" to use a recursive function. Even more \"functional\" than using recursive functions is to use the collection operations such as <code>list.map</code>, <code>list.foreach</code>, <code>list.foldLeft</code>, <code>list.filter</code>, etc.</p>\n\n<p>Here is my solution (using the same brute force search algorithm, but keeping track of visited states):</p>\n\n<pre><code>object PourSolution extends App {\n\n case class Container(id: String, capacity: Int)\n type State = Map[Container, Int]\n type Move = (Container, Container) // (from, to)\n\n // Only moves where source is non-empty and destination is non-full.\n def possibleMoves(state: State): List[Move] = {\n val containers = state.keys.toList\n for {\n s &lt;- containers\n t &lt;- containers\n if (s != t &amp;&amp; state(s) != 0 &amp;&amp; state(t) != t.capacity)\n } yield (s, t)\n }\n\n def applyMove(state: State, move: Move): State = {\n val from = move._1\n val to = move._2\n val remainingCapacity = to.capacity - state(to)\n val transfer = math.min(state(from), remainingCapacity)\n if (transfer == 0) state\n else state ++ List(from -&gt; (state(from) - transfer), to -&gt; (state(to) + transfer))\n }\n\n // Performs a breadth-first-search.\n // Warning: the moves in the returned list are in reversed order.\n def solve(initState: State, targetState: State): Option[List[Move]] = {\n require(!doesMatch(initState))\n require(targetState.nonEmpty)\n\n lazy val targetStateAsSet = targetState.toSet\n def doesMatch(state: State): Boolean = (state.toSet &amp; targetStateAsSet) == targetStateAsSet\n\n @tailrec\n def loop(states: List[(State, List[Move])], statesNextDepth: List[(State, List[Move])], visitedStates: Set[State]): Option[List[Move]] =\n (states, statesNextDepth) match {\n case (Nil, Nil) =&gt; None\n case (Nil, statesNextDepth) =&gt; loop(statesNextDepth, Nil, visitedStates)\n case ((state, moves) :: tail, statesNextDepth) =&gt;\n val nextMoves = possibleMoves(state)\n val nextStates: List[(State, List[Move])] = nextMoves.map(move =&gt; (applyMove(state, move), move :: moves))\n val newNextStates = nextStates.filter(p =&gt; !visitedStates.contains(p._1))\n val exactSolution = newNextStates.find { case ((s, _)) =&gt; doesMatch(s) }\n if (exactSolution.isDefined)\n exactSolution.map(_._2)\n else\n loop(tail, newNextStates ::: statesNextDepth, visitedStates ++ newNextStates.map(_._1))\n }\n loop(List((initState, Nil)), Nil, Set(initState))\n }\n\n val c0 = Container(\"c0\", 10)\n val c1 = Container(\"c1\", 7)\n val c2 = Container(\"c2\", 4)\n val initialState = Map(c0 -&gt; 0, c1 -&gt; 7, c2 -&gt; 4)\n val targetState = Map(c2 -&gt; 2)\n\n val solution = solve(initialState, targetState)\n\n solution match {\n case None =&gt; println(\"No solution\")\n case Some(reversedMoves) =&gt;\n val moves = reversedMoves.reverse\n moves.foreach(println)\n val movesWithState = moves.scanLeft(initialState)(applyMove(_, _))\n movesWithState.foreach(println)\n }\n}\n</code></pre>\n\n<p>Note that I use one list of the states at the current depth and another list for the states at the next depth. I did this because otherwise one would need a FIFO queue (all the states of the current depth are at the head of the queue), but I'm not sure that there is an efficient immutable implementation of such a queue.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-25T20:06:47.613", "Id": "55265", "ParentId": "10224", "Score": "2" } } ]
{ "AcceptedAnswerId": "55265", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-21T17:31:22.283", "Id": "10224", "Score": "5", "Tags": [ "scala", "homework", "breadth-first-search" ], "Title": "Pouring water problem" }
10224
<p>I have an API that takes a class as a configuration parameter, but I don't want to load the class (I'm using Rails) at the time that I'm setting up the API. I figured I could get around this by passing it an object that acts like the class in every way (by delegating to it) but doesn't actually reference the class, and thus load the class. until it us used.</p> <p>This is what it expects:</p> <pre><code>MyAPI.configure.model = UserModel </code></pre> <p>But I'd like to give it something like:</p> <pre><code>MyAPI.configure.model = -&gt;{ UserModel } </code></pre> <p>This is what I have. It works as well as expected but I have a feeling I take better advantage of Ruby's features and/or the standard library.</p> <pre><code>def lazy_delegate(&amp;block) delegate = BasicObject.new def delegate.method_missing(message, *args) @target ||= @target_block.call @target.send message, *args end def delegate.__target__=(block) @target_block = block end delegate.__target__ = block delegate end </code></pre> <p>I'm using this like:</p> <pre><code>MyAPI.configure.model = lazy_delegate{ UserModel } </code></pre> <p>Is there a better way to accomplish this? Does Ruby's standard library have anything that would make this cleaner?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-25T08:13:05.030", "Id": "16426", "Score": "1", "body": "I don't get it? What is your question?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-26T23:23:59.423", "Id": "16525", "Score": "0", "body": "Question is \"Is there a better way to accomplish this? Does Ruby's standard library have anything that would make this cleaner?\". I added it explicitly. Thanks" } ]
[ { "body": "<p>You could pass in a string instead of a proc and use <code>Object.const_get()</code>.</p>\n\n<pre><code>class_const = Object.const_get 'String'\n=&gt; String\nclass_const.new \"hello\"\n=&gt; \"hello\"\n</code></pre>\n\n<p>With a <code>call</code>-able constructor.</p>\n\n<pre><code>constructor = class_const.public_method :new\n=&gt; #&lt;Method: Class#new&gt;\nconstructor.call \"ohai\"\n=&gt; \"ohai\"\n</code></pre>\n\n<p>You need to guard against NameErrors.</p>\n\n<pre><code>Object.const_get('NotThere')\nNameError: uninitialized constant NotThere\n</code></pre>\n\n<p>A lazy load method to build the dependency (Error checking elided for clarity).</p>\n\n<pre><code>def model\n @model ||= build_model('arg1', 'arg2')\nend\n\ndef build_model(*args)\n Object.const_get(self.configure.model_name).send(:new, *args)\nend\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-28T12:44:40.390", "Id": "10399", "ParentId": "10226", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-21T18:24:19.503", "Id": "10226", "Score": "3", "Tags": [ "ruby", "object-oriented" ], "Title": "Delegating to a lazily loaded object in Ruby" }
10226
<p>Prompted by <a href="https://stackoverflow.com/questions/9783943/increasing-decreasing-sequence">this question</a> on Stack Overflow, I wrote an implementation in Python of the <a href="http://en.wikipedia.org/wiki/Longest_increasing_subsequence" rel="nofollow noreferrer">longest increasing subsequence problem</a>. In a nutshell, the problem is: given a sequence of numbers, remove the fewest possible to obtain an increasing subsequence (the answer is not unique).</p> <p>Perhaps it is best illustrated by example:</p> <pre><code>&gt;&gt;&gt; elems [25, 72, 31, 32, 8, 20, 38, 43, 85, 39, 33, 40, 98, 37, 14] &gt;&gt;&gt; subsequence(elems) [25, 31, 32, 38, 39, 40, 98] </code></pre> <p>The algorithm iterates over the input array, <code>X</code>, while keeping track of the length longest increasing subsequence found so far (<code>L</code>). It also maintains an array <code>M</code> of length <code>L</code> where <code>M[j]</code> = "the index in <code>X</code> of the final element of the best subsequence of length <code>j</code> found so far" where <em>best</em> means the one that ends on the lowest element.</p> <p>It also maintains an array <code>P</code> which constitutes a linked list of indices in <code>X</code> of the best possible subsequences (e.g. <code>P[j], P[P[j]], P[P[P[j]]] ...</code> is the best subsequence ending with <code>X[j]</code>, in reverse order). <code>P</code> is not needed if only the <em>length</em> of the longest increasing subsequence is needed.</p> <p>The code below works, but I am sure it could be made shorter and / or more readable. Can any more experienced Python coders offer some suggestions?</p> <pre><code>from random import randrange from itertools import islice def randomSeq(max): while True: yield randrange(max) def randomList(N,max): return list(islice(randomSeq(max),N)) ## Returns the longest subsequence (non-contiguous) of X that is strictly increasing. def subsequence(X): L = 1 ## length of longest subsequence (initially: just first element) M = [0] ## M[j] = index in X of the final member of the lowest subsequence of length 'j' yet found P = [-1] for i in range(1,X.__len__()): ## Find largest j &lt;= L such that: X[M[j]] &lt; X[i]. ## X[M[j]] is increasing, so use binary search over j. j = -1 start = 0 end = L - 1 going = True while going: if (start == end): if (X[M[start]] &lt; X[i]): j = start going = False else: partition = 1 + ((end - start - 1) / 2) if (X[M[start + partition]] &lt; X[i]): start += partition j = start else: end = start + partition - 1 if (j &gt;= 0): P.append(M[j]) else: P.append(-1) j += 1 if (j == L): M.append(i) L += 1 if (X[i] &lt; X[M[j]]): M[j] = i ## trace subsequence back to output result = [] trace_idx = M[L-1] while (trace_idx &gt;= 0): result.append(X[trace_idx]) trace_idx = P[trace_idx] return list(result.__reversed__()) l1 = randomList(15,100) </code></pre> <p>See the revised version below, in <a href="https://codereview.stackexchange.com/a/134449/12390">this answer</a>.</p>
[]
[ { "body": "<pre><code>from random import randrange\nfrom itertools import islice\n\ndef randomSeq(max):\n</code></pre>\n\n<p>The python style guide recommend that you use space_with_underscores for function names</p>\n\n<pre><code> while True: yield randrange(max)\n\n\n\ndef randomList(N,max):\n return list(islice(randomSeq(max),N))\n</code></pre>\n\n<p>I suspect that's not a really efficient way to produce a random list. I think the following may be a better option:</p>\n\n<pre><code>return [randrange(max) for x in range(N)]\n</code></pre>\n\n<p>I've not done any benchmarking so I may be wrong.</p>\n\n<pre><code>## Returns the longest subsequence (non-contiguous) of X that is strictly increasing.\ndef subsequence(X):\n L = 1 ## length of longest subsequence (initially: just first element)\n M = [0] ## M[j] = index in X of the final member of the lowest subsequence of length 'j' yet found\n P = [-1]\n</code></pre>\n\n<p>Consider using names instead of these single letter variables.</p>\n\n<pre><code> for i in range(1,X.__len__()):\n</code></pre>\n\n<p>Don't use <code>x.__len__()</code> use <code>len(x)</code></p>\n\n<pre><code> ## Find largest j &lt;= L such that: X[M[j]] &lt; X[i].\n ## X[M[j]] is increasing, so use binary search over j.\n</code></pre>\n\n<p>This whole bit about the binary search would do well in a seperate function so as not the clutter the subsequence implementation. Actually python already provides a binary search function in the bisect module.</p>\n\n<pre><code> j = -1\n start = 0\n end = L - 1\n going = True\n while going:\n if (start == end):\n</code></pre>\n\n<p>You don't need those parens</p>\n\n<pre><code> if (X[M[start]] &lt; X[i]):\n j = start\n going = False\n</code></pre>\n\n<p>Use <code>break</code>. <code>break</code> isn't pretty when you can avoid it, but setting booleans flags is worse. </p>\n\n<pre><code> else:\n partition = 1 + ((end - start - 1) / 2)\n</code></pre>\n\n<p>Notice how you only use <code>start + partition</code>? Calculate the middle element instead. It'll make this whole section a bit neater.</p>\n\n<pre><code> if (X[M[start + partition]] &lt; X[i]):\n start += partition\n j = start\n else:\n end = start + partition - 1\n\n if (j &gt;= 0):\n P.append(M[j])\n else:\n P.append(-1)\n\n j += 1\n if (j == L):\n M.append(i)\n L += 1\n if (X[i] &lt; X[M[j]]):\n M[j] = i\n\n ## trace subsequence back to output\n result = []\n trace_idx = M[L-1]\n while (trace_idx &gt;= 0):\n result.append(X[trace_idx])\n trace_idx = P[trace_idx]\n\n return list(result.__reversed__())\n</code></pre>\n\n<p>use <code>reversed(list)</code></p>\n\n<pre><code>l1 = randomList(15,100)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-21T22:26:46.650", "Id": "10231", "ParentId": "10230", "Score": "5" } }, { "body": "<p><a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a> is the python style guide. To improve your style a start is to run the <a href=\"http://pypi.python.org/pypi/pep8\" rel=\"nofollow noreferrer\"><code>pep8</code></a> script against your file. Other style \"problems\" you'll have to find them yourself (or ask here on core review :)</p>\n\n<h2>Comments and docstrings</h2>\n\n<p>Check the PEP8 session <a href=\"http://www.python.org/dev/peps/pep-0008/#comments\" rel=\"nofollow noreferrer\">Comments</a>.</p>\n\n<p>This:</p>\n\n<pre><code>## Returns the longest subsequence (non-contiguous) of X that is strictly increasing.\ndef subsequence(X):\n</code></pre>\n\n<p>Should be a docstring:</p>\n\n<pre><code>def subsequence(X):\n \"\"\"Returns the longest subsequence (non-contiguous) of X that is strictly\n increasing.\n\n \"\"\"\n</code></pre>\n\n<h2>Variable names</h2>\n\n<p>I know that you kept the wikipedia variable names, but you should try to make your script conistent with itself. So, squeeze your variable name imagination, and choose something short, sweet and meaningful. You can always leave a note at the beginning, linking to the wikipedia page and say which variable is which.</p>\n\n<p>With this:</p>\n\n<pre><code>L = 1 ## length of longest subsequence (initially: just first element)\n</code></pre>\n\n<p>I'd do:</p>\n\n<pre><code># length of longest subsequence (initially: just first element)\nlen_longest = 1\n</code></pre>\n\n<p>Since the comment was a bit too long to be an inline comment I moved it. A good name for <code>X</code> might be <code>seq</code>. For <code>M</code> maybe <code>pos_smallest</code> and for <code>P</code> <code>pos_predecessor</code> or something like that, maybe with a better understanding of the underling algorithm you can find better names :)</p>\n\n<h2><a href=\"http://docs.python.org/library/functions.html#range\" rel=\"nofollow noreferrer\"><code>range()</code></a> and <a href=\"http://docs.python.org/library/functions.html#xrange\" rel=\"nofollow noreferrer\"><code>xrange()</code></a></h2>\n\n<p>Check the link above and you'll see that one is a list and the other an itertor (genrator).</p>\n\n<p>So, this:</p>\n\n<pre><code>for i in range(1,len(X)):\n</code></pre>\n\n<p>Should be:</p>\n\n<pre><code>for i in xrange(1, len(seq)):\n</code></pre>\n\n<p>Note that in Python 3 <code>xrange()</code> become <a href=\"http://docs.python.org/py3k/library/functions.html#range\" rel=\"nofollow noreferrer\"><code>range()</code></a>.</p>\n\n<h2>Reverse a list</h2>\n\n<p>This line:</p>\n\n<pre><code>return list(reversed(result))\n</code></pre>\n\n<p>Should be:</p>\n\n<pre><code>return result[::-1]\n</code></pre>\n\n<p>Other than being more clear, it will be Python 3 compatible.</p>\n\n<h2>Useless brackets are useless</h2>\n\n<p>Python is not C so don't put brackets everywhere.</p>\n\n<p>Here:</p>\n\n<pre><code>while (trace_idx &gt;= 0):\n</code></pre>\n\n<p>Could just be:</p>\n\n<pre><code>while trace_idx &gt;= 0:\n</code></pre>\n\n<p>Do the same thing in another couple of places.</p>\n\n<h2>Binary search</h2>\n\n<p>Your use of <code>bisect_left</code> looks really strange:</p>\n\n<pre><code>j = bisect_left([X[M[idx]] for idx in range(L)], X[i])\n</code></pre>\n\n<p>And even more the previous version:</p>\n\n<pre><code>while True:\n if (start == end):\n if (X[M[start]] &lt; X[i]):\n j = start\n break\n else:\n partition = 1 + ((end - start - 1) / 2)\n if (X[M[start + partition]] &lt; X[i]):\n start += partition\n j = start\n else:\n end = start + partition - 1\n</code></pre>\n\n<p>Which could have easily been:</p>\n\n<pre><code>while start != end:\n partition = 1 + (end - start - 1) / 2\n if X[M[start + partition]] &lt; X[i]:\n start += partition\n j = start\n else:\n end = start + partition - 1\n\nif X[M[start]] &lt; X[i]:\n j = start\n</code></pre>\n\n<p>But you shouldn't do it like that anyway. Take a look at <a href=\"https://stackoverflow.com/q/212358/1132524\">Binary Search in Python</a>, there are both solution, the accepted is in \"pure\" Python (the one that I like the most) and there's the one with <code>bisect_left</code>. If you care about performances time them both.</p>\n\n<p>This is just a pointing and I would have really liked to give you the code of the binary search, but you didn't really explained how your algorithm works (and it's quite different from the one showed in the <a href=\"http://en.wikipedia.org/wiki/Longest_increasing_subsequence#Efficient_algorithms\" rel=\"nofollow noreferrer\">wikipedia article</a>), so I wasn't able to improve yours without changing its core.</p>\n\n<p>Usually what one should do is instantiate at the beginning the entire <code>M</code> and <code>P</code> list, something like:</p>\n\n<pre><code>M = [0] * len(seq)\n</code></pre>\n\n<p>So you won't have to deal with <code>append</code> and so on... that are quite hard to follow.<br>\nI couldn't also get around your <code>-1</code> offestes, are they really necessary? That's the main different I've found with the \"official\" algorithm.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-22T18:36:41.267", "Id": "16321", "Score": "0", "body": "The reason for growing `head` (previously `M`) as the algorithm proceeds is that it need not grow to the size of `seq`, and in fact can end up much smaller. But yes, it could just be allocated initially to be the size of `seq`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-22T18:50:36.540", "Id": "16323", "Score": "0", "body": "The core idea of the algorithm is that `seq[head[idx]]` (formerly `X[M[j]]`) stays sorted on `idx` -- yes it looks a bit odd, but I can't think of a better way to write it..." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-22T11:45:04.260", "Id": "10245", "ParentId": "10230", "Score": "4" } }, { "body": "<p><em>Note: some of the suggestions here concern the revised version of the code, that was posted as this <a href=\"https://codereview.stackexchange.com/a/134449/12390\">other answer</a>.</em></p>\n\n<h2>List comprehension in bisect</h2>\n\n<p>You could rewrite:</p>\n\n<pre><code>j = bisect_left([seq[head[idx]] for idx in xrange(len(head))], seq[i])\n</code></pre>\n\n<p>trivially as:</p>\n\n<pre><code>j = bisect_left([seq[k] for k in head], seq[i])\n</code></pre>\n\n<p>There's nothing to gain with the original approach.</p>\n\n<p>Or, if you make <code>seq</code> a <code>numpy.array</code>, then you could use:</p>\n\n<pre><code>j = bisect_left(seq[head], seq[i])\n</code></pre>\n\n<h2>If-statements in the for-loop</h2>\n\n<p>You don't really need to check <code>if seq[i] &lt; seq[head[j]]</code>.</p>\n\n<p>From <a href=\"https://docs.python.org/3/library/bisect.html#bisect.bisect_left\" rel=\"nofollow noreferrer\"><code>bisect_left</code></a> line we know that <code>all(seq[i] &lt;= v for v in seq[head][j:])</code>, so your check is equivalent to <code>if seq[i] != seq[head[j]]</code>.</p>\n\n<p>But I see no reason why you can't update <code>head[j] = i</code> in such case. Values in <code>seq[head]</code> stay the same, since <code>seq[i] == seq[head[j]]</code>. It also won't affect predecessor paths of longer subsequences.</p>\n\n<p>On the other hand, <code>j == len(head)</code> implies that <code>seq[i] == seq[head[j]]</code>, so maybe you just meant:</p>\n\n<pre><code>if j == len(head): head.append(i)\nelse: head[j] = i\n</code></pre>\n\n<p>to avoid unnecessary assignments. And that's ok. But in this particular case, I propose to ask forgiveness, not permission:</p>\n\n<pre><code>try: head[j] = i\nexcept: head.append(j)\n</code></pre>\n\n<h2>Parentheses</h2>\n\n<p>Also, you don't need the parentheses in <code>while (trace_idx &gt;= 0):</code>, this should be just:</p>\n\n<pre><code>while trace_idx &gt;= 0:\n</code></pre>\n\n<h2>Generating random numbers</h2>\n\n<p>You don't need <code>randomList</code> if you use <code>numpy</code>:</p>\n\n<pre><code>from numpy.random import randint\n\nl1 = list(randint(100, size=15))\n</code></pre>\n\n<h2>Miscellaneous suggestions</h2>\n\n<ul>\n<li><p>You may consider renaming the function to include the full name.</p></li>\n<li><p>You may consider handling the empty sequence correctly.</p></li>\n<li><p>I think it is possible to have a better name for the <code>head</code> variable.</p></li>\n<li><p>Using <code>None</code> gives better readability to mark that there are no predecessors.</p></li>\n<li><p>In some applications, it may be beneficial to return indices instead\nof actual values.</p></li>\n<li><p>It is possible to generate the indices in correct order directly, using recursion.</p></li>\n</ul>\n\n<p>Here's the function with all remarks applied:</p>\n\n<pre><code>def longest_increasing_subsequence(seq):\n if not seq: return seq\n\n lastoflength = [0] # end position of subsequence with given length\n predecessor = [None] # penultimate element of l.i.s. ending at given position\n\n for i in range(1, len(seq)):\n # seq[i] can extend a subsequence that ends with a smaller element\n j = bisect_left([seq[k] for k in lastoflength], seq[i])\n # update existing subsequence of length j or extend the longest\n try: lastoflength[j] = i\n except: lastoflength.append(i)\n # remember element before seq[i] in the subsequence\n predecessor.append(lastoflength[j-1] if j &gt; 0 else None)\n\n # return indices ..., p(p(p(i))), p(p(i)), p(i), i\n def trace(i):\n if i is not None:\n yield from trace(predecessor[i])\n yield i\n return list(trace(lastoflength[-1]))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-07-10T13:36:12.380", "Id": "251480", "Score": "2", "body": "Hi, and welcome to Code Review! Sorry about the mess around this question and your suggested edit. The question is from old days, when we did yet actively discourage users from revising the code in their question. Revising the question creates a mess, as it invalidates existing answers, and invites new answers that are not comparable to the existing ones... The recommended practice today is to post revised code as a new question, so this kind of thing doesn't happen anymore with more recent posts (2014 and later). Hope you'll enjoy the site nonetheless!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-07-09T17:36:46.180", "Id": "134383", "ParentId": "10230", "Score": "3" } }, { "body": "<p>Here's the revised code, based on the suggestions from code reviews, excluding <a href=\"https://codereview.stackexchange.com/users/110989/arekolek\">@arekolek</a>'s <a href=\"https://codereview.stackexchange.com/a/134383/12390\">answer</a>, which appears to be a review of this revised code here.</p>\n\n<pre><code>from random import randrange\nfrom bisect import bisect_left\n\n\ndef randomList(N, max):\n return [randrange(max) for x in xrange(N)]\n\n\ndef subsequence(seq):\n \"\"\"Returns the longest subsequence (non-contiguous) of seq that is\n strictly increasing.\n\n \"\"\"\n # head[j] = index in 'seq' of the final member of the best subsequence \n # of length 'j + 1' yet found\n head = [0]\n # predecessor[j] = linked list of indices of best subsequence ending\n # at seq[j], in reverse order\n predecessor = [-1]\n for i in xrange(1, len(seq)):\n ## Find j such that: seq[head[j - 1]] &lt; seq[i] &lt;= seq[head[j]]\n ## seq[head[j]] is increasing, so use binary search.\n j = bisect_left([seq[head[idx]] for idx in xrange(len(head))], seq[i])\n\n if j == len(head):\n head.append(i)\n if seq[i] &lt; seq[head[j]]:\n head[j] = i\n\n predecessor.append(head[j - 1] if j &gt; 0 else -1)\n\n ## trace subsequence back to output\n result = []\n trace_idx = head[-1]\n while (trace_idx &gt;= 0):\n result.append(seq[trace_idx])\n trace_idx = predecessor[trace_idx]\n\n return result[::-1]\n\n\nl1 = randomList(15, 100)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-07-10T13:29:25.767", "Id": "134449", "ParentId": "10230", "Score": "2" } } ]
{ "AcceptedAnswerId": "10231", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-21T21:34:29.410", "Id": "10230", "Score": "7", "Tags": [ "python", "dynamic-programming" ], "Title": "Python implementation of the longest increasing subsequence" }
10230
<p>I think this code cannot be shortened much, especially because I only consider two cases. But maybe there's a language construct that I don't know that would help.</p> <pre><code>if (subControl.inverted) { newValue = subControl.value+(float)(1.0f/(float)subControl.decorator.ticks); if (newValue &gt; 1) newValue = 0; } else { newValue = subControl.value-(float)(1.0f/(float)subControl.decorator.ticks); if (newValue &lt; 0) newValue = 1; } </code></pre> <p>Some of the <code>(floats)</code> are gratuitous, which is irrelevant.</p> <p><strong>Edit</strong>: The code could look like this, which helps. However, I guess this is the result of reading the answers already ;)</p> <pre><code>if (subControl.inverted) { newValue = subControl.value+(float)(1.0f/(float)subControl.decorator.ticks); } else { newValue = subControl.value-(float)(1.0f/(float)subControl.decorator.ticks); } if (newValue &gt; 1) newValue = 0; if (newValue &lt; 0) newValue = 1; </code></pre>
[]
[ { "body": "<p>Not a lot shorter, but a bit...</p>\n\n<pre><code>float ticks = (float)(1.0f/(float)subControl.decorator.ticks);\nnewValue = subControl.value + subControl.inverted ? ticks : - ticks;\n\nif (subControl.inverted &amp;&amp; newValue &gt; 1) {\n newValue = 0;\n} else if (!subControl.inverted &amp;&amp; newValue &lt; 0){\n newValue = 1;\n}\n</code></pre>\n\n<p>You could make it even shorter if the you are restricting the values to just 0 and 1.</p>\n\n<p>EDIT: you say in a comment, that it should be between 0 and 1, so...</p>\n\n<pre><code>if (newValue &gt; 1) {\n newValue = 0;\n} else if (newValue &lt; 0){\n newValue = 1;\n}\n</code></pre>\n\n<p>Which is fewer characters if not fewer lines, and imo clearer in intent.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-22T15:56:53.203", "Id": "16312", "Score": "0", "body": "Really, I might even be able to simplify the last bit, since `newValue = MAX(0, newValue)` and `newValue = MIN(1, newValue)` regardless of whether it's inverted or not. I mean, the thing is constrained to 0 to 1 and flips at end of range. So your code is really tight and, thanks to using one more variable, really easy to read." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-22T04:25:57.237", "Id": "10238", "ParentId": "10232", "Score": "4" } }, { "body": "<p>If you don't mind using the <a href=\"http://www.techotopia.com/index.php/Objective-C_Operators_and_Expressions#The_Ternary_Operator\" rel=\"nofollow\">ternary operator</a>, I suppose you could do something like this:</p>\n\n<pre><code>if (subControl.inverted) {\n newValue = subControl.value+(float)(1.0f/(float)subControl.decorator.ticks);\n newValue = newValue &gt; 1 ? 0 : newValue;\n} else {\n newValue = subControl.value-(float)(1.0f/(float)subControl.decorator.ticks);\n newValue = newValue &lt; 0 ? 1 : newValue;\n}\n</code></pre>\n\n<p>Or shorten it further to:</p>\n\n<pre><code>newValue = subControl.value + (subControl.inverted?1:-1) * (float)(1.0f/(float)subControl.decorator.ticks);\nif (subControl.inverted) {\n newValue = newValue &gt; 1 ? 0 : newValue;\n} else {\n newValue = newValue &lt; 0 ? 1 : newValue;\n}\n</code></pre>\n\n<p>And if you really want to get funky:</p>\n\n<pre><code>newValue = subControl.value + (subControl.inverted?1:-1) * (float)(1.0f/(float)subControl.decorator.ticks);\nnewValue = subControl.inverted ? (newValue &gt; 1 ? 0 : newValue)\n : (newValue &lt; 0 ? 1 : newValue);\n</code></pre>\n\n<p>...Not that I think this last version is good - it's a bit harder to follow, and I probably wouldn't use it myself. But it's shorter, which is what you wanted, and I don't know if I can make it any shorter.</p>\n\n<hr>\n\n<p>If this were golf, here would be the hole-in-one:</p>\n\n<pre><code>newValue = subControl.inverted ? ((subControl.value + (subControl.inverted?1:-1) * (float)(1.0f/(float)subControl.decorator.ticks))&gt; 1 ? 0 : ((subControl.value + (subControl.inverted?1:-1) * (float)(1.0f/(float)subControl.decorator.ticks))&lt; 0 ? 1 : (subControl.value + (subControl.inverted?1:-1) * (float)(1.0f/(float)subControl.decorator.ticks))) );\n</code></pre>\n\n<p>cleaned up a bit:</p>\n\n<pre><code>newValue = subControl.inverted ?\n (\n (subControl.value + (subControl.inverted?1:-1) * (float)(1.0f/(float)subControl.decorator.ticks))&gt; 1\n ? 0\n :\n (\n (subControl.value + (subControl.inverted?1:-1) * (float)(1.0f/(float)subControl.decorator.ticks))&lt; 0\n ? 1\n :\n (subControl.value + (subControl.inverted?1:-1) * (float)(1.0f/(float)subControl.decorator.ticks))\n )\n );\n</code></pre>\n\n<p>And remember: Just because you <em>can</em> doesn't mean you <em>should!</em></p>\n\n<p>(I haven't tested this last one, BTW)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-22T15:52:29.357", "Id": "16311", "Score": "0", "body": "Fascinating, I didn't know (or remember) that the ternary operator is so versatile. The last one isn't SO bad, really." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-22T15:58:09.490", "Id": "16313", "Score": "0", "body": "As I said down below to @jmoreno, I really don't care whether it's inverted or not in the last part: if it's past one it's always 0 (loops around) and if it's below 0 it's 1 (same)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-22T16:10:59.410", "Id": "16314", "Score": "0", "body": "@Yar: Would it be correct to say in English \"If newValue is positive OR zero, then set it to 1, ELSE (if negative) set it to 1\"?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-22T16:16:27.267", "Id": "16315", "Score": "0", "body": "No! The new value could be between zero and one. I just want it to wrap around if it's beyond the limits." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-22T16:26:06.320", "Id": "16317", "Score": "1", "body": "@Yar: If it's between 0 and 1, it's still a positive value. Oh wait, I think the English translation should have been: \"If newValue is larger than 1, then set it to 0, ELSE (if less than 0) set it to 1\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-22T18:32:57.773", "Id": "16320", "Score": "0", "body": "Yes that's what I wanted." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-22T15:38:37.347", "Id": "10249", "ParentId": "10232", "Score": "2" } }, { "body": "<p>I think the code you posted (<em>first version</em>) is the most readable version of what you're trying to do, and that's really more important than getting your code smaller.</p>\n\n<p>The only thing I would change is, <a href=\"https://codereview.stackexchange.com/a/10238/8891\">as jmoreno suggested</a>, use a variable to hold the <code>ticks</code> and then add or subtract depending on the value of <code>inverted</code>. But I would keep the <code>if</code> blocks as you have them in the first version of your code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-23T14:11:18.903", "Id": "16372", "Score": "0", "body": "I agree. My code is also more efficient than my second version (in the edit to my question) which would run both `if`. Obviously it's VERY unlikely that saving an `if` matters in terms of performance, but it's a point to keep in mind." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-22T20:28:22.040", "Id": "10262", "ParentId": "10232", "Score": "1" } } ]
{ "AcceptedAnswerId": "10238", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-21T23:34:31.223", "Id": "10232", "Score": "0", "Tags": [ "objective-c" ], "Title": "Shorten This Code with... blocks?" }
10232
<p>I have a ASP.NET Web Forms project, and I want to build calls to .aspx pages in a strongly-typed fashion. I ended up rolling my own serializer that takes simple structs and saves them to/loads them from the query string. What do you think? Is my approach sane? Is there an accepted alternative I don't know about? Any feedback on the code?</p> <p>Here's what building a call to a particular page looks like:</p> <pre><code>var fooParams= new FooPage.Parameters { NodeID = nodeId, FooString = "the foo string" }; string url = MyHelper.BuildCall(FooPage.URL, fooParams); //url: ~/dir/FooPage.aspx?NodeID=5&amp;FooString=the%20foo%20string </code></pre> <p>FooPage:</p> <pre><code>public partial class FooPage : System.Web.UI.Page { public const string URL = "~/Dir/FooPage.aspx"; public struct Parameters { public long? NodeID; public string FooString; public int? OtherParam; } protected Parameters Params; protected void Page_Load(object sender, EventArgs e) { Params = MyHelper.DeserializeFromNameValueCollection&lt;Parameters&gt;(Request.Params); //... //use Params.NodeID, Params.FooString, etc.. } } </code></pre> <p>Serialize/Deserialize to/from NameValueCollection:</p> <pre><code>public static void SerializeToNameValueCollection&lt;T&gt;(NameValueCollection nameValueCollection, T @object) where T : struct { Type type = typeof(T); var fields = type.GetFields(); foreach (var field in fields) { string key = field.Name; var value = field.GetValue(@object); if (value != null) nameValueCollection.Add(key, value.ToString()); } } public static T DeserializeFromNameValueCollection&lt;T&gt;(NameValueCollection nameValueCollection) where T : struct { T result = new T(); Type type = typeof(T); var fields = type.GetFields(); foreach (var field in fields) { string key = field.Name; string stringValue = nameValueCollection[key]; if (stringValue != null) { object value; var baseType = Nullable.GetUnderlyingType(field.FieldType); if (baseType != null) { value = Convert.ChangeType(stringValue, baseType); } else { value = Convert.ChangeType(stringValue, field.FieldType); } field.SetValueDirect(__makeref(result), value); } } return result; } </code></pre> <p>Format NameValueCollection into query string:</p> <pre><code>public static string BuildCall&lt;T&gt;(string url, T queryStringParams) where T : struct { var queryStringBuilder = HttpUtility.ParseQueryString(""); UrlHelper.SerializeToNameValueCollection(queryStringBuilder, queryStringParams); string queryString = queryStringBuilder.ToString(); return url + "?" + queryString; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-02-08T17:52:21.987", "Id": "222197", "Score": "0", "body": "The line that parses an empty string seems a bit of a hack to get a NamveValueCollection. `var queryStringBuilder = HttpUtility.ParseQueryString(\"\");` Is there a reason for this?" } ]
[ { "body": "<p>One of my favorite patterns for handling URL parameters in WebForms is the WebNavigator - <a href=\"http://polymorphicpodcast.com/shows/webnavigator/\" rel=\"nofollow\">http://polymorphicpodcast.com/shows/webnavigator/</a></p>\n\n<p>If you're going through these kinds of Strongly-typed interactions for passing parameters between pages, maybe it is time you check out ASP .NET MVC - your solution looks a lot like model-binding.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-29T04:56:59.737", "Id": "16638", "Score": "0", "body": "This is great, I didn't know about the WebNavigator pattern! I would LOVE to use MVC (and MVC did inspire this approach), but unfortunately the product I'm working on can't afford the time it'd take to do the switch." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-29T03:11:15.507", "Id": "10424", "ParentId": "10234", "Score": "2" } } ]
{ "AcceptedAnswerId": "10424", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-22T01:53:58.017", "Id": "10234", "Score": "4", "Tags": [ "c#", ".net", "asp.net", "parsing", "reflection" ], "Title": "Query String Serializer" }
10234
<p>I've written this brief function for calculating which calendar year a student would be in Year 1 based on their DOB (date of birth). In 1998 there was a change in the DOB cut points for starting Year 1, hence the need for a function. </p> <pre><code>year1 &lt;- function(x){ if(x &lt;= as.Date("1996-12-31")) {out &lt;- as.numeric(format(x, "%Y")) +6} if(x &gt;= as.Date("1997-07-01")) {ifelse(as.numeric(format(x, "%m")) &gt;=07 , out &lt;- as.numeric(format(as.Date(x), "%Y")) + 7, out &lt;- as.numeric(format(x, "%Y")) + 6)} if(x &gt;= as.Date("1997-01-01") &amp; x &lt;= as.Date("1997-06-30")) {out &lt;- 2003} return(out) } </code></pre> <p>An example of the results:</p> <pre><code>&gt; year1(as.Date("1996-02-15")) [1] 2002 &gt; year1(as.Date("1999-02-15")) [1] 2006 </code></pre> <p>I plan to run it like this:</p> <pre><code>&gt; test &lt;- c(as.Date("1985-09-15"),as.Date("1999-02-15"),as.Date("2004-08-15")) &gt; sapply(test,year1) [1] 1991 2006 2011 </code></pre> <p>I have a lot of data to run this over, and the use of so many <code>if</code>s and assigning the result to <code>out</code> just to write it seems pretty redundant, but I couldn't think of a better way to do it.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-22T04:32:54.570", "Id": "16293", "Score": "0", "body": "I see, primary school in Australia for children six to seven years old is called year 1." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-22T04:36:05.817", "Id": "16294", "Score": "0", "body": "it's different in different states, in WA it used to be a case that at the start (say January) of Year 1 kids were aged between 5 and 6, with the change in 1997 it is now the case that kids are aged between 5.5 and 6.5 at the start of Year 1." } ]
[ { "body": "<p>I think this is equivalent to your function.</p>\n\n<pre><code>year1 &lt;- function(dob) as.numeric(format(dob, \"%Y\")) + 6 +\n (as.Date(\"1997-07-01\") &lt;= dob &amp; 7 &lt;= as.numeric(format(dob, \"%m\")))\n</code></pre>\n\n<p>You would run it like this.</p>\n\n<pre><code>&gt; test &lt;- c(as.Date(\"1985-09-15\"),as.Date(\"1999-02-15\"),as.Date(\"2004-08-15\"))\n&gt; year1(test)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-22T05:38:59.260", "Id": "16296", "Score": "0", "body": "It is also worth pointing out that this function is vectorized where the original wasn't. You demonstrate that in the example, but I wanted to point it out explicitly." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-22T05:26:13.490", "Id": "10239", "ParentId": "10235", "Score": "3" } }, { "body": "<p>Your first and third condition can be collapsed into one, which just leaves a single split point. As such, you can use <code>ifelse</code>.</p>\n\n<pre><code>year1 &lt;- function(x) {\n year &lt;- as.numeric(format(x, \"%Y\"))\n ifelse(x &lt;= as.Date(\"1997-06-30\"), year+6, year+7)\n}\n</code></pre>\n\n<p>This is also vectorized, so you can use it like:</p>\n\n<pre><code>test &lt;- as.Date(c(\"1985-09-15\", \"1999-02-15\", \"2004-08-15\", \"1996-02-15\"))\nyear1(test)\n</code></pre>\n\n<p>which gives</p>\n\n<pre><code>&gt; year1(test)\n[1] 1991 2006 2011 2002\n</code></pre>\n\n<p>EDIT:</p>\n\n<p>The code I gave was wrong; it did not agree with the original code in many of the cases. Here is an updated version which does:</p>\n\n<pre><code>year1 &lt;- function(x){\n year &lt;- as.numeric(format(x, \"%Y\"))\n ifelse(x &lt;= as.Date(\"1997-06-30\"),\n year + 6,\n ifelse(as.numeric(format(x, \"%m\")) &gt;=07 , \n year + 7, \n year + 6))\n}\n</code></pre>\n\n<p>You can squeeze a little more out of it by not bothering with the assignment to year and factoring that out of the <code>ifelse</code></p>\n\n<pre><code>year1 &lt;- function(x){\n as.numeric(format(x, \"%Y\")) +\n ifelse(x &lt;= as.Date(\"1997-06-30\"),\n 6,\n ifelse(as.numeric(format(x, \"%m\")) &gt;=07 , \n 7, \n 6))\n}\n</code></pre>\n\n<hr>\n\n<p>Benchmarking:</p>\n\n<pre><code>year1.nzcoops &lt;- function(x){\n if(x &lt;= as.Date(\"1996-12-31\")) {out &lt;- as.numeric(format(x, \"%Y\")) +6}\n if(x &gt;= as.Date(\"1997-07-01\")) {ifelse(as.numeric(format(x, \"%m\")) &gt;=07 , out &lt;- as.numeric(format(as.Date(x), \"%Y\")) + 7, out &lt;- as.numeric(format(x, \"%Y\")) + 6)} \n if(x &gt;= as.Date(\"1997-01-01\") &amp; x &lt;= as.Date(\"1997-06-30\")) {out &lt;- 2003}\n return(out)\n}\nyear1.Brian &lt;- function(x){\n year &lt;- as.numeric(format(x, \"%Y\"))\n ifelse(x &lt;= as.Date(\"1997-06-30\"),\n year + 6,\n ifelse(as.numeric(format(x, \"%m\")) &gt;=07 , \n year + 7, \n year + 6))\n}\n\nyear1.BrianB &lt;- function(x){\n as.numeric(format(x, \"%Y\")) +\n ifelse(x &lt;= as.Date(\"1997-06-30\"),\n 6,\n ifelse(as.numeric(format(x, \"%m\")) &gt;=07 , \n 7, \n 6))\n}\n\nyear1.minopret &lt;- function(dob) as.numeric(format(dob, \"%Y\")) + 6 +\n (as.Date(\"1997-07-01\") &lt;= dob &amp; 7 &lt;= as.numeric(format(dob, \"%m\")))\n</code></pre>\n\n<p>More comprehensive test data:</p>\n\n<pre><code>test &lt;- as.Date(\"1985-09-15\")+(0:10000)\n</code></pre>\n\n<p>Checking results:</p>\n\n<pre><code>res.nzcoops &lt;- sapply(test, year1.nzcoops)\nres.Brian &lt;- year1.Brian(test)\nres.BrianB &lt;- year1.BrianB(test)\nres.minopret &lt;- year1.minopret(test)\n\n&gt; identical(res.nzcoops, res.Brian)\n[1] TRUE\n&gt; identical(res.nzcoops, res.BrianB)\n[1] TRUE\n&gt; identical(res.nzcoops, res.minopret)\n[1] TRUE\n</code></pre>\n\n<p>Timing comparisons:</p>\n\n<pre><code>&gt; library(\"rbenchmark\")\n&gt; benchmark(sapply(test, year1.nzcoops),\n+ year1.Brian(test),\n+ year1.BrianB(test),\n+ year1.minopret(test),\n+ order = \"relative\",\n+ replications = 10)\n test replications elapsed relative user.self\n4 year1.minopret(test) 10 0.12 1.000000 0.12\n3 year1.BrianB(test) 10 0.14 1.166667 0.14\n2 year1.Brian(test) 10 0.16 1.333333 0.14\n1 sapply(test, year1.nzcoops) 10 74.95 624.583333 74.85\n sys.self user.child sys.child\n4 0.00 NA NA\n3 0.00 NA NA\n2 0.01 NA NA\n1 0.02 NA NA\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-22T06:36:57.183", "Id": "16298", "Score": "0", "body": "Cheers, I have so many timelines written down working out start/finish ages for difference calendar years and school years I couldn't see the forest for the trees." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-22T05:46:32.170", "Id": "10240", "ParentId": "10235", "Score": "2" } } ]
{ "AcceptedAnswerId": "10240", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-22T03:03:40.660", "Id": "10235", "Score": "3", "Tags": [ "datetime", "r" ], "Title": "Calculating calendar year for a student based on DOB" }
10235
<p>This is a pagination program that works perfectly fine. I want to be able to save this code and reuse it whenever I need it as a method in jQuery (read: <code>$(myData).pagination()</code>).</p> <p>jQuery:</p> <pre><code>$(document).ready(function(){ var post = $(".note &gt; li") var page= 1; var postsPerPage = 5; var numPages = Math.ceil(post.length/postsPerPage) for(j=0;j&lt;numPages;j++){ //render menu $(".paginationIndex").append("&lt;li&gt;&lt;a href='#' class='pageNum'&gt;"+(j+1)+"&lt;/a&gt;&lt;/li&gt;") } $(".paginationIndex li:first-child a").addClass("active") //add active class to page_1 $(".pageNum").click(function(e){ e.preventDefault(); $(".pageNum").removeClass("active") $(this).addClass("active") page = parseInt($(this).html()) pagination(page, postsPerPage) // execute onclick }) var pagination = function(p, ppp){ //root function $.each(post, function(i,v){ i &lt; ppp*p &amp;&amp; i&gt;=ppp*(p-1)?$(this).show():$(this).hide(); }) } pagination(page, postsPerPage) }) </code></pre> <p>HTML:</p> <pre><code>&lt;ul class="note"&gt; &lt;li&gt; some content 1........ &lt;/li&gt; &lt;li&gt; some content 2........ &lt;/li&gt; &lt;li&gt; some content 3........ &lt;/li&gt; &lt;/ul&gt; &lt;ul class="paginationIndex"&gt; &lt;!-- children rendered with jQuery--&gt; &lt;/ul&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-22T12:50:11.707", "Id": "16307", "Score": "0", "body": "There is a really good tutorial at http://docs.jquery.com/Plugins/Authoring" } ]
[ { "body": "<p>Without going the whole plugin route (to which I would suggest using the jQueryUI widget design), I have made a few modifications to clean up your code:</p>\n\n<p><a href=\"http://jsfiddle.net/KALpP/2/\" rel=\"nofollow\">Commented version over at jsfiddle</a></p>\n\n<pre><code>(function ($, Math) { \n $(function () { \n var $posts = $(\".note &gt; li\"), \n page = 1,\n pageSize = 2, //you would want to change this back to 5\n numPages = Math.ceil($posts.length/pageSize),\n j, \n $paging = $(\".paginationIndex\"), \n $lastactive, \n s = '';\n\n for(j=0;j&lt;numPages;j++) { \n s+=\"&lt;li&gt;&lt;a href='#Page+\";\n s+=(j+1); \n s+=\"' class='pageNum' title='Go to page \";\n s+=(j+1); \n s+=\"'&gt;\";\n s+=(j+1);\n s+=\"&lt;/a&gt; &lt;/li&gt;\"; \n }\n $paging.append(s);\n\n $lastactive = $paging.find(\"li:first-child a\").addClass(\"active\"); \n\n $paging.on('click', 'a', function(e) { \n e.preventDefault();\n $lastactive.removeClass(\"active\"); \n $lastactive = $(this).addClass(\"active\");\n page = +$lastactive.html(); \n pagination(); \n });\n\n var pagination = function() {\n $posts.hide().slice(pageSize*(page-1), pageSize*page).show();\n };\n\n pagination();\n });\n}(jQuery, Math));\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-26T11:03:34.690", "Id": "17875", "Score": "0", "body": "+1. Thanks so much. I like your coding style. One thing... why did you pass the `Math` object parameter to the wrapping IIFE?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-26T12:58:22.080", "Id": "17971", "Score": "0", "body": "As a general practice, I like to pass in all globals that I use. Here I could have passed in `Math.ceil` instead (I'm about 50/50 on that being a good idea or not). It makes it easy to see what dependencies the JavaScript has." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-25T22:46:48.463", "Id": "11179", "ParentId": "10246", "Score": "2" } } ]
{ "AcceptedAnswerId": "11179", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-22T12:15:16.173", "Id": "10246", "Score": "2", "Tags": [ "javascript", "jquery", "performance", "html", "pagination" ], "Title": "Reusable pagination" }
10246
<p>I'm trying to implement a custom made 2D geometry library. Originally I was looking at the problem of intersections of many circles but wanted to widen the scope of the code to deal with many future geometry based problems.</p> <p>I already have a vector (2D) class defined. I wish to derive all my other geometrical entities from <code>Shape</code>. These will include 0D objects, 1D objects (and 2D objects, though i think this is best achieved through a custom made <code>IArea</code> interface supported by for example closed loops (1D objects) and special polygons, figures (i.e. <code>Circle</code>)).</p> <p>In this question I want to focus on the best way to define a 1D Path, but first my definitions for 0D objects. </p> <p><code>Node</code> will be my 0D base class <code>Segment</code> (<code>Node</code> to <code>Node</code>), <code>SingleEndSegment</code> (<code>Node</code> to infinity) and <code>Curve</code> (no nodes) will be my 1D base classes (I have some misgivings over the best way to define these). The links between <code>Node</code>s can be line vectors, circular arcs, any type of curve function really, though initially just lines and circular arcs.</p> <p>One important point to note hear is that I'd like <code>Segment</code> and <code>SingleEndSegment</code> to be free from Internal Nodes. Meaning, if I want to add a <code>Node</code> along a <code>Segment</code>, I need to convert it to two <code>Segment</code>s. It's important that if I do this and I have a reference to this object in, say, a <code>Polygon</code> (made up of <code>LineSegment</code>s derived from <code>Segment</code>), then the <code>Polygon</code> object takes account of this change. On the other hand, I'd like curves to contain a list of <code>Node</code>s along them (i.e. a <code>Line</code> has a reference list of its intersections).</p> <p>Thinking about this now, I am not sure whether to derive the <code>Segment</code> classes and <code>SingleEndSegment</code> classes from <code>Curve</code> classes (i.e. <code>LineSegment : Line : Shape and ArcSegment : Circle : Shape</code>) or in my current approach from an abstract <code>Segment</code> class. I can't have both without perhaps creating a <code>Segment</code> interface.</p> <p>I will define a <code>Node</code> to contain a vector and an ordered <code>List</code> of the <code>Segment</code>s or <code>SingleEndSegments</code> which connect at it:</p> <pre><code>public class Node { private vector m_point; private List&lt;Segment&gt; m_links; } </code></pre> <p>As <code>Intersection</code>s of <code>Circle</code>s and <code>Line</code>s are key to my main geometry focus, I must derive an <code>Intersection</code> class from <code>Node</code> which also defines the two <code>Curve</code>s which pass through it (though they would perhaps also be available through the <code>Segment</code>s).</p> <pre><code>public class Intersection : Node { private Curve[] m_curves = new Curve[2]; //some code } </code></pre> <p>Now onto the 1D objects (I have <code>Start</code> and <code>End</code> because I may consider some notion of direction at a later date):</p> <pre><code> public abstract class Segment : Shape { private Node m_start; private Node m_end; public Node Start { get { return m_start; } set { m_start = value; } } public Node End { get { return m_end; } set { m_end = value; } } public Segment() : base() { Start = null; End = null; } public Segment(Node s, Node e) : base() { Start = s; End = e; } } </code></pre> <p>An example of a derived class would be:</p> <pre><code> public class LineSegment : Segment { private vector m_vector; public vector Vec { get { return m_vector; } set { m_vector = value; } } } </code></pre> <p>Note that in my current implementation I have a vector whereas, I could have <code>LineSegment</code> contain a <code>Line</code> (which naturally possesses the vector of its direction).</p> <p>But I'd also like to have a derived abstract class called <code>IntersectionSegment</code> between two known intersection points (to be the base of <code>IntersectionLineSegment</code>). I could do this as follows, but would ideally prefer to deal with the <code>Node</code>s being Intersections in a better way. How can I best do that?</p> <pre><code> public abstract class IntersectionSegment : Segment { private Intersection m_inters_start; public Intersection Start { get { return m_inters_start; } set { m_inters_start = value; } } } </code></pre> <p>Not ideal.</p> <p>Now the main trouble I'm having comes in defining a <code>Path</code> as a collection of <code>Segment</code>s:</p> <pre><code>public class Path&lt;T&gt; : IEnumerable&lt;T&gt; where T : Segment { private List&lt;T&gt; segments = new List&lt;T&gt;(); public List&lt;T&gt; Segments { set { segments = value;} get { return this.segments; } } public T this[int pos] { get { return (T)segments[pos]; } set { segments[pos] = value; } } public Path() { this.Segments = new List&lt;T&gt;(); } public Path(List&lt;T&gt; s) { this.Segments = s; } public void AddSegment(T s) {Segments.Add(s);} public int Count {get {return Segments.Count;}} IEnumerator&lt;T&gt; IEnumerable&lt;T&gt;.GetEnumerator() { return Segments.GetEnumerator();} IEnumerator IEnumerable.GetEnumerator() { return Segments.GetEnumerator(); } } </code></pre> <p>I'm having major problems working out how to define derived types from this <code>Path</code> and how to use this generic Path in an efficient way.</p> <p>One key method I wish to implement is an <code>Intersection</code> (method here not 0D object defined above) of say a <code>Line</code> with a (closed) <code>Path</code>. I'll need to check the <code>Intersection</code> with all <code>Segment</code>s and I'd like to under certain conditions replace a <code>Segment</code> within a <code>Path</code> with a <code>LineSegment</code> and an altered version of the existing <code>Segment</code>, maintaining the order of the <code>Path</code> <code>Segment</code>s.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-22T19:10:49.130", "Id": "16324", "Score": "0", "body": "Consider using auto-properties with `get; private set;` in the `Segment` class. I would also chain constructors like so: `public Segment() : this(s: null, e: null)`. Finally, can you post at least the signature of the methods that you need to create? Not many people will read this question in its entirety." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-23T22:47:06.017", "Id": "16395", "Score": "0", "body": "Just a question, Have you looked at WPF? Path in the WPF is not sufficient for what you need? I am just asking so we don't reinvent the wheel." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-24T01:00:37.273", "Id": "16397", "Score": "0", "body": "This is a heck of a project. Take a look at the implementation of the Asymptote language / tool. http://sourceforge.net/scm/?type=svn&group_id=120000" } ]
[ { "body": "<p>First of all I really would like to have a good computational library in C#, will be your OS?\nAnyway my two cents:</p>\n\n<ul>\n<li>I really appreciate the fact you are considering circular segmants to\n( arcs ), if you manage to use it properly everywere (\ndistance/intersection, offseting ) this would be great.</li>\n<li><p>I'm not sure I want all the object in that library deriving from shape, leave object for the algorithms, try to keep the geometrics entities as small as possible</p></li>\n<li><p>The pat too, leave it as an entity apart. It will be something like a linked list ( leveraging the fact the end point of a single segment is necessarily the start of the next one ) and differentiate each segment type ( line, arc ) with a plain old enum. This probably will sound as a not good OOP, but trust me it will pay back much more.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-25T12:11:09.687", "Id": "10318", "ParentId": "10247", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-22T13:54:51.470", "Id": "10247", "Score": "7", "Tags": [ "c#", "computational-geometry" ], "Title": "Implementing a collection class to represent a Path of Segments" }
10247
<p>I'm working with some strange APIs that requires the dates to be sent in the YYYYMMDD format.</p> <p>I was thinking of doing something like this:</p> <pre><code>string date = string.Concat(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day); </code></pre> <p>Is there a better practice?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-22T18:50:08.157", "Id": "16322", "Score": "5", "body": "Be careful when calling `DateTime.Now` several times like this. For example, if `DateTime.Now.Month` is called just before the midnight of 31 January and `DateTime.Now.Day` after the midnight, you will get the date like `20120101`. It's unlikely, but certainly possible." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T20:26:08.507", "Id": "455700", "Score": "1", "body": "This is already 'answered', but the main difference between their method and yours is how 1 digit months and dates will be handled. Yours would print 201911 for 1st Jan 2019, whereas the others will print 20190101" } ]
[ { "body": "<p>Yes there is: <a href=\"http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx\">Date Formatting</a></p>\n\n<pre><code>var dateString = DateTime.Now.ToString(\"yyyyMMdd\");\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-22T16:13:09.990", "Id": "10252", "ParentId": "10250", "Score": "19" } }, { "body": "<p>Another option would be to create an extension methods like:</p>\n\n<pre><code>public static class DateTimeExtensions\n{\n public static string ToYMD(this DateTime theDate)\n {\n return theDate.ToString(\"yyyyMMdd\");\n }\n\n public static string ToYMD(this DateTime? theDate)\n {\n return theDate.HasValue ? theDate.Value.ToYMD() : string.Empty;\n }\n}\n</code></pre>\n\n<p>You would use it like:</p>\n\n<pre><code>var dateString = DateTime.Now.ToYMD();\n</code></pre>\n\n<p>The extension implemented also works for Nullable DateTime values. </p>\n\n<p>If you are doing a lot of work with these 'yyyyMMdd' formatted DateTime values, the extension method has the benefit of less typing.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-05T04:24:08.237", "Id": "10636", "ParentId": "10250", "Score": "5" } } ]
{ "AcceptedAnswerId": "10252", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-22T16:10:26.387", "Id": "10250", "Score": "4", "Tags": [ "c#", "strings", "datetime", "formatting" ], "Title": "Formatting a datetime string in the YYYYMMDD format" }
10250