body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<pre><code>SELECT TOP 1 l.ID FROM Leads l WHERE l.ID NOT IN (SELECT LeadID FROM LeadFollowups) AND l.ID NOT IN (SELECT LeadID FROM LeadsWorking) AND l.ID NOT IN (SELECT LeadID FROM LeadsDead) AND l.ID NOT IN (SELECT LeadID FROM LeadHolds) AND l.ID &gt;= (RAND() * (SELECT MAX(ID) FROM Leads)) ORDER BY l.QualityScore DESC </code></pre> <p>I have a table growing by a 10 to 100 thousand rows a day. I have several tables to track actions of the current leads that shouldn't be included when grabbing the new lead. My query is pretty quick now, but as this grows is <code>NOT IN</code> the most efficient solution for this? Especially if I get in to the range of ~10 million rows in the Leads table?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-25T16:57:45.923", "Id": "73719", "Score": "1", "body": "what does `l.ID >= (RAND() * (SELECT MAX(ID) FROM Leads))` and why do you need this?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-25T17:04:49.210", "Id": "73720", "Score": "0", "body": "Before adding the QualityScore calculation, I was just returning a random row with that line." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-25T18:30:40.107", "Id": "73744", "Score": "0", "body": "so you weren't even checking the rows less than some random ID?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-21T00:01:45.030", "Id": "135179", "Score": "0", "body": "Is `LeadID` nullable in any of the columns in the various LeadX tables? If so you [should consider `NOT EXISTS`](http://stackoverflow.com/a/11074428/73226) or explicitly adding `WHERE LeadID IS NOT NULL`" } ]
[ { "body": "<blockquote>\n <p>My query is pretty quick now, but as this grows is NOT IN the most efficient solution for this?</p>\n</blockquote>\n\n<p>I expect it would be quicker if you had an indexed <code>Status</code> field in the <code>Leads</code> table (so that records in the <code>LeadsDead</code> table had a corresponding <code>Status=Dead</code> in the <code>Leads</code> table); and quicker still if <code>Status</code> were a clustered index, so that all the leads with a given <code>Status</code> were contiguous in the <code>Leads</code> table.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-25T18:29:36.433", "Id": "73743", "Score": "1", "body": "if only we could go back in time and slap the person creating the database structure (in some cases) and tell them the right way to do it." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-25T16:56:17.593", "Id": "42782", "ParentId": "42781", "Score": "6" } }, { "body": "<h2>EDIT:</h2>\n\n<p>If you can, you should add a column to your leads table, something like <code>beingHandled</code> (boolean/bit) then you could write a query that would set it once for all the records which might take a little bit of time but it only needs to be run once.</p>\n\n<p>After you have done this you can query this table super simple</p>\n\n<pre><code>SELECT leads.ID\nFROM Leads AS leads\nWHERE beingHandled = true\n</code></pre>\n\n<p>Then you just need to keep this table up to date with your {application?}.</p>\n\n<p>Let the application handle picking a random lead from the data set of leads that haven't been handled. In my opinion, asking a RDBMS to randomly pick a record seems completely wrong, I see that a database was created to organize data and not scramble it. </p>\n\n<p>You also never mention if the record that was returned is going to be added to one of the tables that are mentioned in the where clause, <strong>so you could return the same result twice</strong>.</p>\n\n<p>I assume that your application is handling the part of creating the record in the other tables, so why not let the application also update the <code>Leads</code> table <code>beingHandled</code> value to <code>true</code> as well.</p>\n\n<hr>\n\n<hr>\n\n<p>Can you pick an ID and say anything less than that ID doesn't need to be checked?</p>\n\n<p>I think that you will lose a little bit of performance by running the random function, probably not much, but if you can eliminate all the records older than some date, that would speed up the query by not having to run through so many records in the first place. </p>\n\n<p>so this line of SQL,</p>\n\n<pre><code>AND l.ID &gt;= (RAND() * (SELECT MAX(ID) FROM Leads))\n</code></pre>\n\n<p>Smells Badly to me</p>\n\n<p>you are saying that you only want to check more recent leads, what if this line of code says</p>\n\n<pre><code>l.ID &gt;= ({123455}) -- Translated after code does it's thing\n</code></pre>\n\n<p>and there are only <code>123456</code> Records?</p>\n\n<hr>\n\n<p>let's also think about this for a minute, </p>\n\n<p>same line of code in the where statement,</p>\n\n<p>the query comes to a row and checks all the where statements, which means that it is picking a different random ID for every record that it checks, this can't be accurate, and probably isn't what you intend this line of code to do. </p>\n\n<p><strong>you should look into changing this line of code</strong></p>\n\n<pre><code>AND l.ID &gt;= (RAND() * (SELECT MAX(ID) FROM Leads))\n</code></pre>\n\n<hr>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-25T17:00:12.633", "Id": "42783", "ParentId": "42781", "Score": "4" } }, { "body": "<p>If your data is correctly indexed with the ID column from each table as the primary key, then I don't see this query slowing down much as the data grows.</p>\n\n<p>You are worrying prematurely, I think.... but, the purpose of the query is complicated... it is almost as if you are tying to find a random lead to prompt people to look in to 'next'.... where that lead has not been handled in some way yet.</p>\n\n<p>I think you may have better performance with a cursor.... (in a stored procedure?). </p>\n\n<p>Still, even if you have to do the large checks of all the 'handled' leads, you may find it faster to do just the one 'big' subselect instead of multiple smaller ones. you will need to test this on your system to get an idea of the performance.</p>\n\n<pre><code>with (\n SELECT LeadID FROM LeadFollowups\n UNION\n SELECT LeadID FROM LeadsWorking\n UNION\n SELECT LeadID FROM LeadsDead\n UNION\n SELECT LeadID FROM LeadHolds\n) as handled\nselect TOP 1 leads.ID\nfrom Leads leads\nwhere leads.ID &gt;= (RAND() * (SELECT MAX(ID) FROM Leads))\n and leads.ID not in (select LeadID from handled)\nORDER BY leads.QualityScore DESC\n</code></pre>\n\n<p>I don't like that your query can return zero results when the <code>RAND()</code> value is large... and all higher ID's are handled.</p>\n\n<p>As a cursor / procedure, it will process much less data, and, as a consequence, it will likely be faster. The big difference is that it will terminate early (when it has found a valid answer), rather than calculating all the valid answers, and selecting one of them.</p>\n\n<p>It could be something like:</p>\n\n<pre><code>declare @leadid as int;\ndeclare @count as int = 0;\n\ndeclare LEADCURSOR cursor for\nselect leads.ID\nfrom Leads leads\nwhere leads.ID &gt;= (RAND() * (SELECT MAX(ID) FROM Leads))\nORDER BY leads.QualityScore DESC\n\nopen LEADIDS\n\nfetch next from LEADIDSinto @leadid\nwhile @@FETCH_STATUS = 0\nbegin\n\n select @count = count(*)\n from LeadFollowups, LeadsWorking, LeadsDead, LeadHolds\n where LeadFollowups.leadID = @leadid\n and LeadsWorking.leadID = @leadid\n and LeadsDead.leadID = @leadid\n and LeadHolds.leadID = @leadid\n\n if (@count = 0)\n BREAK\n\n fetch next from LEADIDSinto @leadid\nend\nclose LEADIDS\ndeallocate LEADIDS\n\nif (@count &lt;&gt; 0)\n set @leadid = null\n\nselect @leadid\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-25T18:12:10.380", "Id": "73734", "Score": "0", "body": "I am skeptical that the cursor processes much less data. For one thing, it's querying the various anti-join tables zero or more times, possible very many times." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-25T18:20:41.203", "Id": "73736", "Score": "0", "body": "Perhaps that UNION could be a materialized view." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-25T18:20:55.163", "Id": "73737", "Score": "0", "body": "@JonofAllTrades - With the `>=` condition on the `RAND()` function, I don't believe that SQLServer can use that as a deterministic predicate as it compiles the SQL Plan. Thus, the query, at best, because of the NOT IN, becomes a index-scan of Leads.ID, with nested-loop index-probe for each sub-table... Thus, *every* LeadID is scanned before it can satisfy the `TOP 1`... With the cursor approach we do the same thing, but start from the 'right place', and terminate early." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-25T18:22:45.173", "Id": "73738", "Score": "0", "body": "My suspicion/hope (and why I recommend *trying it* ) is that the there will be much fewer cursor loops than nested-loops. This will depend on data distributions, usage patterns, etc." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-25T18:26:42.493", "Id": "73739", "Score": "0", "body": "There's still the repeated scanning of the anti-tables. Why not capture the set of disallowed lead IDs once? I'd probably dump it into a temp table rather than materialize it as Chris suggested, but any approach that avoids re-querying the same data will surely scale better." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-25T18:27:44.157", "Id": "73740", "Score": "0", "body": "I do see your point about reducing the loops, for sure, I just don't see why it's necessary to loop at all. Wish I had the exact data to test!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-25T18:27:48.250", "Id": "73741", "Score": "0", "body": "@JonofAllTrades - I disagree that there are repeated scanns of the anti-tables .... each anti-table will have a single index-probe per loop. (assuming it has the logical index on LeadID)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-25T18:29:11.820", "Id": "73742", "Score": "0", "body": "Sorry, yes, I was using \"scans\" sloppily. Repeated *examinations*; in this case, probings - IF those fields are indexed. They probably are." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-25T21:46:18.127", "Id": "73786", "Score": "1", "body": "Thanks for the comments. You are exactly correct in the purpose of the function, to pull a random lead to work that is free." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-25T21:53:24.093", "Id": "73790", "Score": "0", "body": "With the current 800,000 rows in the leads, and an average of 5,000 rows in each of the \"anti\"-tables, it is running very well. I just wanted to make sure the software wouldn't get killed in the coming months." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-25T21:54:38.693", "Id": "73791", "Score": "0", "body": "This means very little to me, but if it will satisfy your curiosity: http://i.imgur.com/iwtPhN0.png" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-19T01:25:01.763", "Id": "102693", "Score": "0", "body": "Unions and cursors? I really doubt that either would produce a better query plan. The Union *might*. Maybe." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-20T23:59:32.480", "Id": "135178", "Score": "0", "body": "\"With the >= condition on the RAND() function, I don't believe that SQLServer can use that as a deterministic predicate\" this is an incorrect assumption. `RAND` is a runtime constant in SQL Server, it can certainly be evaluated once and used in a seek." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-21T00:51:06.390", "Id": "135185", "Score": "0", "body": "Yes that's true. If the optimal plan shape would vary due to selectivity then one possible approach would be to store the result of `(RAND() * (SELECT MAX(ID) FROM Leads))` in a variable then use `OPTION (RECOMPILE)` to get SQL Server to take account of the value." } ], "meta_data": { "CommentCount": "14", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-25T18:00:48.623", "Id": "42791", "ParentId": "42781", "Score": "5" } } ]
{ "AcceptedAnswerId": "42791", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-25T16:50:25.743", "Id": "42781", "Score": "8", "Tags": [ "optimization", "sql", "sql-server", "random" ], "Title": "WHERE NOT IN SQL Performance" }
42781
<p>I'm working on this method in Java, which is giving me the factors of a number. I'll be using this method a lot, and I was wondering if there isn't a better way of doing it. Like, with just one loop. Although this code works great and it returns what I expect, I just want to know if there's a better workaround.</p> <p>The method: </p> <pre><code>public static void main(String[] args) { System.out.print("Enter a positive number: "); Scanner scanner = new Scanner (System.in); int number = scanner.nextInt(); int count; for (int i = 2; i&lt;=(number); i++) { count=0; while (number % i == 0) { number /= i; count++; } if (count == 0) continue; System.out.println(i+ "**" + count); } } </code></pre> <p>The output I'm expecting:</p> <pre><code>number = 288; 2**5 3**2 </code></pre>
[]
[ { "body": "<ol>\n<li><p>Apache Commons Math has a similar function: <a href=\"http://commons.apache.org/proper/commons-math/apidocs/org/apache/commons/math3/primes/Primes.html#primeFactors%28int%29\" rel=\"nofollow\"><code>Primes.primeFactors()</code></a></p>\n\n<pre><code>Primes.primeFactors(288)\n</code></pre>\n\n<p>Returns a list with the following elements:</p>\n\n<pre><code>[2, 2, 2, 2, 2, 3, 3]\n</code></pre>\n\n<p>It open-source, check the implementation (<a href=\"http://svn.apache.org/viewvc/commons/proper/math/trunk/src/main/java/org/apache/commons/math3/primes/Primes.java?view=markup#l118\" rel=\"nofollow\">source1</a>, <a href=\"http://svn.apache.org/viewvc/commons/proper/math/trunk/src/main/java/org/apache/commons/math3/primes/SmallPrimes.java?view=markup\" rel=\"nofollow\">source2</a>) and it contains a lot of optimization. (For example, instead of iterating it all of the numbers, at the beginning it uses an array with the first 512 primes to make it faster.)</p>\n\n<p>So it seems faster but it needs some additional work if you want to use your original format. (Converting the list to the <code>P**F</code> format.</p>\n\n<p>(See also: <em>Effective Java, 2nd edition</em>, <em>Item 47: Know and use the libraries</em> The author mentions only the JDK's built-in libraries but I think the reasoning could be true for other libraries too.)</p></li>\n<li><p>You don't need the parentheses around <code>number</code> here:</p>\n\n<pre><code>for (int i = 2; i&lt;=(number); i++) {\n</code></pre></li>\n<li><p>This kind of formatting is very hard to read:</p>\n\n<pre><code>if (count == 0) continue;\n System.out.println(i+ \"**\" + count);\n</code></pre>\n\n<p>It looks like that <code>println</code> would depend on the condition.</p>\n\n<p>(According to the <a href=\"http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-142311.html#449\" rel=\"nofollow\">Code Conventions for the Java Programming Language</a> <code>if</code> statements always should use braces.)</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-25T17:58:46.800", "Id": "73729", "Score": "0", "body": "That's great, it's an improvement. About `primeFactors()`, would it be better to use that method, instead of my original post?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-25T18:10:13.207", "Id": "73732", "Score": "0", "body": "@LCH: It depends on the requirements/context. If I could I would use the Apache library to reduce maintenance work but there might be legal or other constraints. (Furthermore, I guess they are better on primes than me. Read the Effective Java chapter, it contains a lot of arguments to consider.) It's open-source, so you can copy just the relevant parts of the library code (there might be licence restrictions)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-25T18:13:12.090", "Id": "73735", "Score": "0", "body": "Thank you very much for your time, and your great answer. I'd definitely read the Effective Java Chapter, and keep learning about this particular \"factors subject\". Thanks again." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T04:25:49.693", "Id": "74412", "Score": "1", "body": "no, you still have to loop to the square root of the (updated) number, only. Because it might be a prime. And it will be, if the largest prime factor of original number is non-repeating." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T11:51:18.910", "Id": "74424", "Score": "0", "body": "@WillNess: Good point, thanks! It deserves an answer. Would you write it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T11:58:02.987", "Id": "74425", "Score": "0", "body": "it's easier if you just tweak yours. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T12:02:28.630", "Id": "74428", "Score": "0", "body": "@WillNess: Then I will have to check your answers for good ones and upvote some of them :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T12:14:33.893", "Id": "74430", "Score": "0", "body": "only if you find them good enough. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T12:34:29.590", "Id": "74434", "Score": "0", "body": "@WillNess: http://codereview.stackexchange.com/a/43134/7076" } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-25T17:51:58.210", "Id": "42787", "ParentId": "42786", "Score": "7" } }, { "body": "<p>Even if looping from <code>2</code> to <code>sqrt(number)</code> is an optimization as suggested by palacsint, you would run better by looping as long as <code>number &gt; 1</code>:</p>\n\n<pre><code>for (int i = 2; number &gt; 1; i++) {\n ...\n}\n</code></pre>\n\n<p>Since you are only working on relatively small numbers (<code>Integer.MAX_VALUE</code> or less), you should also consider using a prime number table instead of trying each and every divisor from <code>2</code> to <code>sqrt(number)</code>. There are roughly 4.800 prime numbers less than <code>sqrt(Integer.MAX_VALUE)</code>, which cover all possible factors. Keeping them in an array of ints and testing only those numbers as possible factors should also gain some performance.</p>\n\n<p>Better factorizing algorithms than this brute force approach are not known.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-25T22:04:05.003", "Id": "73793", "Score": "1", "body": "The rise of jarnbjo... ;) Come visit us over in our [chat room](http://chat.stackexchange.com/rooms/8595/the-2nd-monitor) sometime." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-25T22:19:59.027", "Id": "73794", "Score": "0", "body": "\"_Better factorizing algorithms than this brute force approach are not known._\"; of course [there](http://en.wikipedia.org/wiki/Integer_factorization) are! In the context (31-bit numbers), I would recommend [Pollard's rho](http://en.wikipedia.org/wiki/Pollard%27s_rho_algorithm)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-25T22:54:49.550", "Id": "73798", "Score": "0", "body": "@fgrieu: Isn't Pollard's rho algorithm indeterminate? It is perhaps suitable to search for a factor, given that it is acceptable that the algorithm stops when no factor has been found within a reasonable time, but at least in theory, the algorithm may run forever without finding a correct factor." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T07:17:15.017", "Id": "73837", "Score": "0", "body": "You are correct that Pollard's rho is a probabilistic algorithm; yet using it allows enormous speedup in practice in the average case, and it is possible to make a deterministic algorithm using some trial division, and say 30% of the effort on a derandomized Pollard's rho, that will at worst take 1/(1-30%)=143% of the time of trial division, and much less than 100% on average. Even if we want to stick to fully deterministic algorithms, there are variants of Fermat factoring, like [this](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.96.9310&rep=rep1&type=pdf)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-25T18:46:21.163", "Id": "42797", "ParentId": "42786", "Score": "10" } }, { "body": "<blockquote>\n <p>which is giving me the factors of a number</p>\n</blockquote>\n\n<p>Since english is not your native language I think you meant to say <em>prime factors</em> of a number. However if you want to get <strong>number of factors for a number</strong>, your method will help you. Since any number can be written as multiple of prime number the number of factor of a prime number can be written as</p>\n\n<blockquote>\n <p>N = P<sub>1</sub><sup>a</sup> * P<sub>2</sub><sup>b</sup> *\n P<sub>3</sub><sup>c</sup> * ... P<sub>m</sub><sup>m</sup></p>\n \n <p>[P<sub>1</sub>, P<sub>2</sub>, P<sub>3</sub>, ... , P<sub>m</sub> are\n all prime number]</p>\n</blockquote>\n\n<p>then</p>\n\n<p>number of divisors</p>\n\n<blockquote>\n <p>d(N) = (a+1) * (b+1) * (c+1) ... (m+1)</p>\n</blockquote>\n\n<p>More reading from <a href=\"http://mathschallenge.net/library/number/number_of_divisors\" rel=\"nofollow\">MathsChallenge</a>.</p>\n\n<p><sub> Leaving implementation as your homework </sub></p>\n\n<hr>\n\n<p>There is only one <code>continue</code> with one <code>if</code> so you can guess <code>continue</code> is redundant.</p>\n\n<pre><code>if (count != 0)\n System.out.println(i + \"**\" + count);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T20:39:55.840", "Id": "42978", "ParentId": "42786", "Score": "2" } }, { "body": "<p>To summarize <em>Will Ness</em>'s comment:</p>\n\n<blockquote>\n <p>no, you still have to loop to the square root \n of the (updated) number, only. Because it might \n be a prime. And it will be, if the largest \n prime factor of original number is non-repeating.</p>\n</blockquote>\n\n<p>Here is an updated method:</p>\n\n<pre><code>public static List&lt;Integer&gt; factorize(int number) {\n final List&lt;Integer&gt; factors = newArrayList();\n for (int i = 2; i * i &lt;= number; i++) {\n while (number % i == 0) {\n number /= i;\n factors.add(i);\n }\n }\n if (number &gt; 1) {\n factors.add(number);\n }\n return factors;\n}\n</code></pre>\n\n<p>It's possible to change multiplication in <code>i * i &lt;= number</code> to square root:</p>\n\n<pre><code>public static List&lt;Integer&gt; factorize2(int number) {\n final List&lt;Integer&gt; factors = newArrayList();\n int root = (int) Math.sqrt(number);\n for (int i = 2; i &lt;= root; i++) {\n while (number % i == 0) {\n number /= i;\n factors.add(i);\n root = (int) Math.sqrt(number);\n }\n // root = (int) Math.sqrt(number); // sqrt could be here also\n }\n if (number &gt; 1) {\n factors.add(number);\n }\n return factors;\n}\n</code></pre>\n\n<p>I haven't done any performance test (nor checked the <a href=\"https://en.wikipedia.org/wiki/Big_O_notation\" rel=\"nofollow\">O</a> of <code>sqrt</code>) to decide which <em>solution</em> is faster. (I still would use Apache Commons Math.)</p>\n\n<p>The method was modified to return a list of factors instead of printing them for easier testing:</p>\n\n<pre><code>@Test\npublic void testFactorize() {\n for (int i = 2; i &lt; 100000; i++) {\n final List&lt;Integer&gt; factors = PrimeFactor.factorize(i);\n final List&lt;Integer&gt; expectedFactors = Primes.primeFactors(i);\n assertEquals(\"\" + i, expectedFactors, factors);\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T12:41:09.597", "Id": "74437", "Score": "0", "body": "i*i is faster than sqrt, is what is commonly said." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T12:51:05.933", "Id": "74438", "Score": "0", "body": "@WillNess: I know that (note the word *solution* in the original text;) but I was not sure because `sqrt` is inside the while loop and might have not run the same times as `i*i`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T12:54:22.420", "Id": "74439", "Score": "1", "body": "it's good if you test this, then we'd know for sure. I'm just saying, Ive seen it stated several times that using the i*i way is faster than the other way." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T12:33:41.407", "Id": "43134", "ParentId": "42786", "Score": "3" } } ]
{ "AcceptedAnswerId": "42787", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-25T17:38:08.020", "Id": "42786", "Score": "11", "Tags": [ "java", "algorithm", "primes" ], "Title": "Factorizing integers" }
42786
<p>I made a program in Python and wanted it to be faster, so I wrote it on C# because it's compiled. To my surprise, the Python program is much faster. I guess there is something wrong with my C# code, but it is pretty simple and straightforward, so I don't know. They are structured about the same way.</p> <p><strong>C#:</strong></p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Diagnostics; //This program generates a string of random lowercase letters and matches it to the user's input //It does this until it gets a match //It also displays the closest guess so far and the time it took to guess namespace Monkey { class Program { static string userinput() { //Takes user input, makes sure it is all lowercase letters, returns string string input; while(true) { input = Console.ReadLine(); if (Regex.IsMatch(input, @"^[a-z]+$")) { return input; } } } static string generate(int len) { //generates string of random letters, returns the random string Random rnd = new Random(); string alpha = "abcdefghijklmnopqrstuvwxyz"; int letterInt; StringBuilder sb = new StringBuilder(); for (int i = 0; i &lt; len; i++) { letterInt = rnd.Next(26); sb.Append(alpha[letterInt]); } return sb.ToString(); } static int count(int len, string s, string g) { //returns number of letters that match user input int same = 0; for (int i = 0; i &lt; len; i++) { if(g[i] == s[i]) { same++; } } return same; } static void Main(string[] args) { Console.WriteLine("They say if you lock a monkey in a room with a typewriter and enough time,"); Console.WriteLine("the monkey would eventually type a work of Shakespeare."); Console.WriteLine("Let's see how well C# does..."); Console.WriteLine("Enter a word"); Console.WriteLine("(3 letters or less is recommended)"); string solution = userinput(); int size = solution.Length; bool success = false; string guess = null; int correct; int best = 0; Stopwatch watch = Stopwatch.StartNew(); while (!success) { guess = generate(size); correct = count(size, solution, guess); if (correct == size) { success = true; } else if (correct &gt; best) { Console.Write("The best guess so far is: "); Console.WriteLine(guess); best = correct; } } watch.Stop(); TimeSpan ts = watch.Elapsed; Console.WriteLine("Success!"); Console.Write("It took " + ts.TotalSeconds + " seconds for the sharp C to type "); Console.WriteLine("\"" + guess + "\""); Console.ReadLine(); } } } </code></pre> <p><strong>Python:</strong></p> <pre><code>import random import time #This program generates a string of random letters and matches it with the user's string #It does this until it's guess is the same as the user's string #It also displays closest guess so far and time it took to guess def generate(): # generate random letter for each char of string for c in range(size): guess[c] = random.choice(alpha) def count(): # count how many letters match same = 0 for c in range(size): if guess[c] == solution[c]: same += 1 return same print("They say if you lock a monkey in a room with a typewriter and enough time,") print("the monkey would eventually type a poem by Shakespeare") print("Let's see how well a python does...'") user = "" badinput = True while badinput: # Make sure user only inputs letters user = input("Enter a word\n(5 letters or less is recommended)\n") if user.isalpha(): badinput = False solution = list(user.lower()) size = len(solution) guess = [""] * size alpha = list("abcdefghijklmnopqrstuvwxyz") random.seed() success = False best = 0 # largest number of correct letters so far start = time.time() # start timer while not success: # if number of correct letters = length of word generate() correct = count() if correct == size: success = True elif correct &gt; best: print("The best guess so far is: ", end="") print("".join(guess)) best = correct finish = time.time() # stop timer speed = finish - start print("Success!") print("It took " + str(speed) + " seconds for the python to type ", end="") print("\"" + "".join(guess) + "\"") input() </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-25T18:45:22.620", "Id": "73745", "Score": "3", "body": "I guess I had better get back to typing up some Macbeth!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-25T22:50:13.617", "Id": "73813", "Score": "1", "body": "You may find this question on StackOverflow useful as well as it discusses pros and cons of instantiating a StringBuilder object: http://stackoverflow.com/questions/550702/at-what-point-does-using-a-stringbuilder-become-insignificant-or-an-overhead" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T07:13:47.897", "Id": "73835", "Score": "26", "body": "**Use a profiler to answer a performance question**. Anything else is guessing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T15:57:40.437", "Id": "73906", "Score": "0", "body": "@EricLippert, sage advice, certainly -- but in this particular case would profiling actually help? He'd see that all the time is spent in generate() and count() and that neither is unusually slow -- but that is not illuminating, it's precisely what we would expect to see if it was operating properly. Without understanding the consequences of repeated Random creation, the specific logical reason for why the program is so slow is elusive." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T16:12:54.803", "Id": "73908", "Score": "11", "body": "@agentnega: You see what you're doing there, right? **You are guessing**. Your guesses are good, educated guesses that are probably right, but they are still guesses. For all we know the reason that the C# program is slow is because there's something wrong with the `Console.WriteLine` causing the output to block or some such thing. I have profiled a lot of C# programs in my day and very frequently -- well over 10% of the time -- my initial guess about the cause of a slowdown is utterly wrong. Engineers solve problems by reasoning about *facts*, not *guesses*." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T03:06:36.363", "Id": "74011", "Score": "1", "body": "You say \"I wrote it on C#, because it's compiled\"; Python is also normally compiled." } ]
[ { "body": "<p>In your python code you use a character array as your <code>guess</code>. In your C# code you build a <code>StringBuffer</code> instead. Try using a <code>char[]</code> instead.</p>\n\n<p>Since you are on Code Review - I'll also give some thoughts about your code:</p>\n\n<p><strong>Naming Conventions</strong> - C# method naming is <code>PascalCase</code>, and python function naming in <code>snake_case</code>, so - <code>UserInput()</code> and <code>user_input():</code> respectively.</p>\n\n<p><strong>Meaningful names</strong> - <code>generate</code> and <code>count</code> do not convey well the meaning of the code in them <code>GenerateRandomString</code> and <code>CountSimilarLetters</code> is better. Same goes for <code>alpha</code>, <code>len</code>, <code>g</code>, <code>s</code>, etc.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-25T19:17:05.937", "Id": "73750", "Score": "1", "body": "You have `camelCase` and `PascalCase` confused, but at least you use them right. Though `camelCase` doesn't use underscores either - it just looks like a camel." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-25T19:19:07.870", "Id": "73751", "Score": "0", "body": "@Magus, fixed, thanks CamelCase can be used for both upper and lower first chars(http://en.wikipedia.org/wiki/CamelCase), and the pascal_case was a typo..." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-25T18:36:22.003", "Id": "42795", "ParentId": "42792", "Score": "9" } }, { "body": "<p>I don't know <a href=\"/questions/tagged/python\" class=\"post-tag\" title=\"show questions tagged &#39;python&#39;\" rel=\"tag\">python</a> so I'll focus on the <a href=\"/questions/tagged/c%23\" class=\"post-tag\" title=\"show questions tagged &#39;c#&#39;\" rel=\"tag\">c#</a> code.</p>\n\n<ul>\n<li>Your program is coded upside down. One would expect <code>void Main</code> at the top, with the more specialized code below.</li>\n<li>Method names in C# are expected to consistently follow <em>PascalCasing</em> convention. Only your <code>Main</code> method does that, and if you were to adopt a <em>camelCasing</em> convention, <code>userinput</code> would be better off called <code>userInput</code>.</li>\n<li>It doesn't feel right that the <code>Count</code> method doesn't infer the number of iterations from the length of the string(s) it's given, and doesn't do anything to verify whether the index is legal, which at first glance seems like asking for an <code>IndexOutOfRangeException</code>.</li>\n</ul>\n\n<p>Performance-wise, I think you'll need to factor out the randomness from your tests for any benchmarking to mean anything.</p>\n\n<p>Using <code>StringBuilder</code> was a good call.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-25T19:29:45.310", "Id": "73756", "Score": "0", "body": "It is random, but if you run them both, the python is consistently much faster than the C#. Thanks for the tips. I put the methods at the bottom and changed the names." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-25T19:35:03.803", "Id": "73758", "Score": "5", "body": "Same if you take the creation of the `rnd` and `sb` objects outside the loop as @vals as pointed out? I suspect a seeding issue with all the instances of `Random` you're creating. Possibly you run the program 10K times and it runs 10K times with the same \"random\" sequence. Also C# is Jit-compiled from IL code, so yeah it's compiled, but to an *intermediate language* - there's the CLR doing its job, too. Not sure how fair your comparison is." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-25T20:04:31.013", "Id": "73763", "Score": "2", "body": "YES! the random initializing inside the method was the problem. Thanks, for pointing that out. Stepping through it in the debugger wasn't catching it. And yes, I know about C# and the way it compiles." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-25T21:08:07.987", "Id": "73771", "Score": "0", "body": "@user2180125 in all fairness, it's really vals' answer that caught the performance issue. If you're accepting my answer for the code review, I'll take it; but if you're accepting my answer for the advice about taking instantiation out of the loop, vals' answer should have the checkmark ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-25T21:34:30.537", "Id": "73780", "Score": "1", "body": "@Mat'sMug Never mind, I should have written a more thorough answer :-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-25T21:37:11.997", "Id": "73783", "Score": "0", "body": "By the way, I am unsure about C#, were the objects ever deleted in the original code ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-25T21:38:57.983", "Id": "73784", "Score": "0", "body": "@vals they'd be eligible for garbage-collection as soon as they're out of scope." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T06:22:28.450", "Id": "73830", "Score": "0", "body": "@user2180125, see [Jon Skeet's explanation](http://csharpindepth.com/Articles/Chapter12/Random.aspx) about why/how the repeated creation of a Random object results in getting the same stream of (not-)random numbers." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T15:22:20.473", "Id": "73902", "Score": "0", "body": "@Mat'sMug I didn't check vals answer because he said to take the Random out just for a general performance boost. You found a specific error in the code that taking it out fixed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T15:26:12.130", "Id": "73904", "Score": "0", "body": "@bobpal that's utterly cool, one more upvote on vals' answer and he gets [one of the sites' rarest gold badges](http://codereview.stackexchange.com/help/badges/49/populist)!" } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-25T18:41:56.583", "Id": "42796", "ParentId": "42792", "Score": "20" } }, { "body": "<p>If you want performance, don't create objects in the inner loop:</p>\n\n<pre><code> static string generate(int len)\n {\n Random rnd = new Random(); // creating a new object\n string alpha = \"abcdefghijklmnopqrstuvwxyz\";\n int letterInt;\n StringBuilder sb = new StringBuilder(); // creating a new object\n ....\n\n }\n</code></pre>\n\n<p>create them once and reuse them</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-25T18:50:43.160", "Id": "73746", "Score": "0", "body": "Ugh. How did I miss that! Good catch!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-25T18:51:28.617", "Id": "73747", "Score": "0", "body": "The objects are created once every user input, hardly a performance issue..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-25T19:40:31.353", "Id": "73759", "Score": "5", "body": "@UriAgassi they're not. Objects are created at each iteration of the while loop, which runs after the user input." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-25T19:44:31.133", "Id": "73760", "Score": "0", "body": "@Mat'sMug you are right, missed that :-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T00:10:54.477", "Id": "73815", "Score": "0", "body": "+1 (late, I know, I [ran out of ammo](http://meta.codereview.stackexchange.com/a/1515/23788) early today!), but despite the upvotes, this is pretty much a *SO-Style* answer; on CR we prefer answers that *review* the OP's code - not necessarily long answers redacted in 2 hours, but while addressing OP's performance concerns (for example), consider commenting on *any aspect of the code*, including naming, formatting, best practices, etc. That said, welcome to soon-to-be-500 milestone!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T09:22:43.370", "Id": "73850", "Score": "0", "body": "I disagree with the conclusion. Object creation in a modern, OO, garbage collected, JITted language like C# or Java is so fast as to be one of the cheapest operations you can perform. Creating many ephemeral objects is already a generational GC's best case, and object pooling is almost always the wrong solution except for objects which are atypically expensive to create, such as Random. Don't object pool or reuse by default, only do it when there's actually an issue." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T17:30:10.420", "Id": "73914", "Score": "0", "body": "@Mat'sMug I somehow knew about the differences between OP and Code review, but I don't know C# enough to give advice about formatting and best practices. Anyway, highly surprised about my success !!!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T17:34:21.827", "Id": "73915", "Score": "3", "body": "@Phoshi I think that my use of the plural *reuse them* make you believe that I was suggesting using a pool of objects. My suggestion was much easier; just create one object of class Random and one of class StringBuilder, and them meant the 2 objects." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T09:15:54.197", "Id": "74030", "Score": "0", "body": "@vals: It was more the general statement \"don't create objects in the inner loop, create them once and reuse them\" that made me think you were saying it as a rule rather than advice for this specific case. For this case specifically you are, of course, absolutely correct, and even without performance issues creating Randoms in a tight loop has potential issues with creating the same pseudorandom numbers!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T11:16:02.460", "Id": "74041", "Score": "0", "body": "@Phoshi I ran a profiler on the C# code. 82% of the time was spent in Random.ctor. So object creation here is not cheap because it dose much more than allocate the memory for the object." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T11:20:18.337", "Id": "74042", "Score": "3", "body": "@Andris: \"Don't object pool or reuse by default, only do it when there's actually an issue\". Random has *semantic* issues, never mind speed issues, and should never be created in a tight loop. This does not hold for the vast majority of objects, though." } ], "meta_data": { "CommentCount": "11", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-25T18:47:12.057", "Id": "42798", "ParentId": "42792", "Score": "50" } }, { "body": "<p>I'd look at compiling your regex and having it as a class-level member for optimal reuse. Also lift the random number generator out the same way, as it's never good practice to continually regenerate it.</p>\n\n<p>old code:</p>\n\n<pre><code> static string userinput()\n {\n //Takes user input, makes sure it is all lowercase letters, returns string\n string input;\n\n while(true)\n {\n input = Console.ReadLine();\n\n if (Regex.IsMatch(input, @\"^[a-z]+$\"))\n {\n return input;\n }\n }\n }\n\n private static string generate(int len)\n {\n // generates string of random letters, returns the random string\n Random rnd = new Random();\n string alpha = \"abcdefghijklmnopqrstuvwxyz\";\n StringBuilder sb = new StringBuilder();\n int letterInt;\n\n for (int i = 0; i &lt; len; i++)\n {\n letterInt = rnd.Next(26);\n sb.Append(alpha[letterInt]);\n }\n\n return sb.ToString();\n }\n</code></pre>\n\n<p>new code:</p>\n\n<pre><code> private static readonly Regex regex = new Regex(@\"^[a-z]+$\", RegexOptions.Compiled);\n private static readonly Random rnd = new Random();\n\n static string userinput()\n {\n //Takes user input, makes sure it is all lowercase letters, returns string\n string input;\n\n while(true)\n {\n input = Console.ReadLine();\n\n if (regex.IsMatch(input))\n {\n return input;\n }\n }\n }\n\n private static string generate(int len)\n {\n // generates string of random letters, returns the random string\n const string alpha = \"abcdefghijklmnopqrstuvwxyz\";\n StringBuilder sb = new StringBuilder();\n int letterInt;\n\n for (int i = 0; i &lt; len; i++)\n {\n letterInt = rnd.Next(26);\n sb.Append(alpha[letterInt]);\n }\n\n return sb.ToString();\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-25T23:43:21.187", "Id": "73809", "Score": "1", "body": "If the strings are `123a56` and `123b56` then your count will be 3 and the OP's count will be 5." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-25T23:55:24.700", "Id": "73811", "Score": "0", "body": "@ChrisW dangit, it screws up the \"best so far\" display. Whoops. Correcting." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-25T23:39:32.717", "Id": "42825", "ParentId": "42792", "Score": "8" } }, { "body": "<p>To answer the question of why your c# code is so slow.</p>\n\n<p>It's this line. According to a profiler ~90% of the execution time is being taken up by recreating the Random object. You'll notice your python code only uses the random rather than recreates it.</p>\n\n<pre><code>Random rnd = new Random();\n</code></pre>\n\n<p>if you change the generate method to:</p>\n\n<pre><code> static Random rnd = new Random();\n\n static string generate(int len)\n {\n //generates string of random letters, returns the random string\n string alpha = \"abcdefghijklmnopqrstuvwxyz\";\n int letterInt;\n StringBuilder sb = new StringBuilder();\n\n for (int i = 0; i &lt; len; i++)\n {\n letterInt = rnd.Next(26);\n sb.Append(alpha[letterInt]);\n }\n\n return sb.ToString();\n }\n</code></pre>\n\n<p>These changes will show similar perf for both languages.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T11:31:56.657", "Id": "42858", "ParentId": "42792", "Score": "20" } }, { "body": "<p>Here's a late commentary on your Python program.</p>\n\n<hr>\n\n<p>I know no C#. To be honest, though, I'm truly surprised that the C# isn't faster, because what you have written is <em>not</em> how to implement a fast variant in Python.</p>\n\n<p>In Python, you'll want to use Numpy if things are getting slow. In fact, you'll want something like:</p>\n\n<pre><code>\"\"\"\nThis program generates a string of random letters and matches it with the user's string.\nIt does this until its guess is the same as the user's string.\nIt also displays closest guess so far and time it took to guess.\n\"\"\"\n\nimport numpy\nimport time\nfrom string import ascii_lowercase\n\n# Everything is ASCII, which is what the \"c\" means.\nletters = numpy.array(list(ascii_lowercase), dtype=\"c\")\n\ndef brute_force(solution):\n \"\"\"\n BRRUUUUTTTEEE FFOOORRRCCCEEEE!!!!\n\n Repeatedly guess at a solution until it matches.\n \"\"\"\n\n # Convert to char array\n solution = numpy.array(list(solution.casefold()), dtype=\"c\")\n\n best = 0\n while True:\n # Do loads of guesses (100000) at once\n guesses = numpy.random.choice(letters, (100000, len(solution)))\n\n # Check all of the characters for equality, and count the number\n # of correct for each row\n corrects = (guesses == solution).sum(axis=1)\n\n # Gets the highest-so-far at each point\n maximums = numpy.maximum.accumulate(corrects)\n\n # Gets how much the maximum increased\n changes = numpy.diff(maximums)\n\n # Indexes of the increases\n # numpy.where returns a tuple of one element, so unpack it\n [when_increased] = numpy.where(changes &gt; 0)\n # Need to increase by one, because these are indexes into\n # the differences whilst we want indexes into the final array\n # for the *increased* (not increasing) elements\n when_increased += 1\n\n for index in when_increased:\n guess = guesses[index]\n correct = corrects[index]\n\n if correct &gt; best:\n yield str(guess, encoding=\"ascii\")\n best = correct\n\n if correct == len(solution):\n return\n\n\nprint(\"They say if you lock a monkey in a room with a typewriter and enough time,\")\nprint(\"the monkey would eventually type a poem by Shakespeare\")\nprint(\"Let's see how well a python does...'\")\n\nwhile True:\n print(\"Enter a word\")\n print(\"(5 letters or less is recommended)\")\n user_input = input()\n\n # Make sure user only inputs letters\n if user_input.isalpha():\n break\n\nstart = time.time()\n\nfor solution in brute_force(user_input):\n print(\"The best guess so far is: \", solution)\n\nelapsed_time = time.time() - start\n\nprint(\"Success!\")\nprint(\"It took \", elapsed_time, \" seconds for the python to type \", repr(solution))\n</code></pre>\n\n<p>It might look more intimidating but there are only ~30 lines of logic there, most of which are trivial.</p>\n\n<p>The basic idea is to make loads of random choices in bulk:</p>\n\n<pre><code>guesses = numpy.random.choice(letters, (100000, len(solution)))\n</code></pre>\n\n<p>which is fast. This makes a 100000xN matrix, eg. for N=3:</p>\n\n<pre><code>h s l\nw t x\na m e\ni x t\n ⋮\n</code></pre>\n\n<p>Then you can calculate the number correct for each row by comparing each row to the solution (<code>guesses == solution</code>) giving a <code>bool</code> array, and you can sum each row (<code>.sum(axis=1)</code>) to get the number correct.</p>\n\n<p>The extra parts from there (<code>numpy.diff</code>) serve to <em>pretend</em> we did this sequentially, although we did not. It's not relevant in most real-world circumstances, where one can just print the best answer from that bunch.</p>\n\n<p>Overall this is much faster than the original (>10x), and most of the time is spent in <code>numpy.random.choice</code>, implying it's not possible to meaningfully speed up further without replacing the high-quality random numbers that Numpy generates.</p>\n\n<p>So don't go thinking that Python is slow because it's interpreted and dynamic. It's perfectly possible to have a high-quality implementation run fast with these kinds of programs.</p>\n\n<hr>\n\n<p>Since this is Code Review, I'll also point out some things that you should be improving on:</p>\n\n<ul>\n<li><p><strong>Docstrings</strong>, not <em>comments</em>.</p>\n\n<p>Write</p>\n\n<pre><code>\"\"\"\nThis program generates a string of random letters and matches it with the user's string.\nIt does this until its guess is the same as the user's string.\nIt also displays closest guess so far and time it took to guess.\n\"\"\"\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code># This program generates a string of random letters and matches it with the user's string.\n# It does this until its guess is the same as the user's string.\n# It also displays closest guess so far and time it took to guess.\n</code></pre>\n\n<p>This might sound meaninglessly fussy, but it helps introspection.</p></li>\n<li><p>Reduce your usage of globals. Functions should (almost) <em>never</em> share state; it should be passed between them. Trust me on this. It means that you can reuse them and move them around without worrying about dependencies, for one. It also allows local changes to stay local.</p></li>\n<li><p>Try and clump IO in one place. If you look at my variant, all the printing is localized and the logic is separated. This modularizes the program, so you can move things around and mess with logic without having \"things\" in your way all of the time.</p></li>\n<li><p><code>random.seed()</code> with no value given is pointless here. It should only be used after <code>random.seed(some_value)</code> to <em>remove</em> the seed.</p></li>\n<li><p>This code:</p>\n\n<pre><code>done = False\nwhile not done:\n if ...:\n done = True\n</code></pre>\n\n<p>is much better written</p>\n\n<pre><code>while True:\n if ...:\n break\n</code></pre>\n\n<p>Some people disagree. <em>They are wrong.</em></p></li>\n<li><p>Things like</p>\n\n<pre><code>for c in range(size):\n guess[c] = random.choice(alpha)\n</code></pre>\n\n<p>where you're visiting each item in turn, are much better written without indexes, like:</p>\n\n<pre><code>guess[:] = [random.choice(alpha) for _ in range(size)]\n</code></pre>\n\n<p>although this really should be</p>\n\n<pre><code>def generate(size):\n \"\"\"Generate random letter for each character of string.\"\"\"\n return [random.choice(alpha) for _ in range(size)]\n</code></pre>\n\n<p>if you use my prior advice.</p>\n\n<p>The same goes for <code>count</code>, which can be</p>\n\n<pre><code>sum(g==s for g, s in zip(guess, solution))\n</code></pre></li>\n<li><p><strong>Don't</strong> meaninglessly preallocate values, like <code>guess = [\"\"] * size</code>. It just hides bugs.</p>\n\n<p>If you ever find you need to do that, you're probably not following my advice about not using globals.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-26T16:03:59.503", "Id": "51760", "ParentId": "42792", "Score": "2" } } ]
{ "AcceptedAnswerId": "42796", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-25T18:08:47.077", "Id": "42792", "Score": "28", "Tags": [ "c#", "python", "performance", "strings", "validation" ], "Title": "Matching a generated string of random letters to an input" }
42792
<p>I have a need to read properties from soapUI using groovy and writing them to Excel. I initially had a <a href="https://stackoverflow.com/questions/21935285/how-to-write-data-to-excel-using-scriptom-in-groovy">problem with writing to Excel</a>, but I was able to solve that. Now I want to know if my solution is correct from a best practice perspective and can it be optimized to work faster.</p> <p>I use Groovy and scriptom to write and read data from Excel. The logical flow:</p> <ol> <li>construct a column name and property name map 2.loop through all test cases in a test suite 3.for each test case, construct a property and property value map for all property test steps.</li> <li>Construct a col name and col ID map</li> <li>construct a col name and prop value map</li> <li>construct a col ID and prop value map</li> <li>write data to Excel</li> </ol> <p></p> <pre><code>/* * Function to write data to excel * tcmap = [#:[col num:col value]] * xlPath = complete path to the excel file * dtSheet = data sheet name */ def write2Excel(tcMap, xlPath, dtSheet){ def xl def wb def rng if(tcMap == null || tcMap.size() == 0){ return false } if(xlPath.size() != 0){ def f = new File(xlPath) if(!(f.exists() &amp;&amp; f.isFile())){ return false } }else{ return false } if(dtSheet.size() == 0 ){ return false } xl = new ActiveXObject('Excel.Application') if(xl == null){ return false } wb = xl.Workbooks.Open(xlPath) if(wb == null){ return false } rng = wb.Sheets(dtSheet) int rowMax = rng.UsedRange.Rows.Count.toInteger() tcMap.eachWithIndex(){row, i -&gt; //one key for each property test step rowMax++ row.value.eachWithIndex(){ data, j -&gt; //col num to value mapping log.info data.key + ":" + data.value log.info "data.value == \"\": " + (data.value == "") //write data to excel def val = data.value rng.Cells(rowMax,data.key.toInteger()).Value = data.value } } //save and close xl.DisplayAlerts = false wb.Save xl.DisplayAlerts = true wb.Close(false,null,false) xl.Quit() Scriptom.releaseApartment() } /* * Function to generate a map with data for a test case, including * data from multiple property test steps * colHeadMap = [col name: col#] * colPropMap = [step#:[col name: prop vale]] * rowData = [[#:[col#:prop value]] */ def genRowData(testCaseName, colHeadMap,colPropMap){ def rowData = [:] int mKey = 1 if(testCaseName == null || colHeadMap == null || colPropMap == null){ log.info "null check" return rowData } if(testCaseName.size() == 0 || colHeadMap.size() == 0 || colPropMap.size() == 0){ log.info "size check" return rowData } colPropMap.eachWithIndex(){ pRow, k -&gt; //loop through all test steps which have properties def tmp = [:] pRow.value.eachWithIndex() { p, j -&gt; //loop through all properties in a test step def colNum = colHeadMap[p.key] tmp.put(colNum,p.value) } //handle test case, stepnumber columns colNum = colHeadMap["TestCase_Name"] tmp.put(colNum,testCaseName) colNum = colHeadMap["Step_No"] int stpNo = 1 + k.toInteger() tmp.put(colNum,stpNo) rowData.put(k.toString(),tmp) } return rowData } /* * Function to generate a property and property value map for a test case */ def genPropMap(tCase,propStep){ def propMap = [:] def tcType = "class com.eviware.soapui.impl.wsdl.testcase.WsdlTestCase" int k = 1 if(tCase == null){ log.info "tCase null" return propMap } def tCaseClass = tCase.getClass().toString() if(!tCaseClass.equalsIgnoreCase(tcType)){ return propMap } def tSteps = tCase.getTestStepsOfType((java.lang.Class)propStep) if(tSteps.size() == 0){ return propMap } for(ts in tSteps){ def tStepProp = ts.getPropertyList() if(tStepProp.size() == 0){ return propMap } def tMap = [:] for(prop in tStepProp){ tMap.put(prop.getName(),prop.getValue()) } propMap.put(k.toString(),tMap) k = k+1 } return propMap } /* * Function to create a map of col header and col number */ def genColHeadingMap(xlPath, dtSheet){ def colHead = [:] def xl = new ActiveXObject('Excel.Application') assert xl != null, "Excel object not initalized" //open excel def wb = xl.Workbooks.Open(xlPath) //get column name in a list def rng = wb.Sheets(dtSheet).UsedRange //get Column count int iColumn = rng.Columns.Count.toInteger() for(int i = 1;i&lt;=iColumn;i++){ def cValue = rng.Cells(1,i).Value if(cValue != null){ colHead.put(cValue,i.toString()) } } xl.DisplayAlerts = false wb.Save xl.DisplayAlerts = true wb.Close(false,null,false) xl.Quit() Scriptom.releaseApartment() return colHead } /* * Function generates a map of excel col heading and property value * colMap = [colname:propname] * propMap = [stepNo:[propName:propValue]] */ def genColPropMap(colMap,propMap){ def rowMap = [:] if(colMap == null){ return rowMap } if(colMap.size() == 0){ return rowMap } if(propMap == null){ return rowMap } //loop through all the property steps int stp = 1 def tmp = [:] for(prop in propMap){ //loop through all the properties for(p in prop.value){ //find col name for the property name def colName = colMap.find{ it.value == p.key}?.key if(colName != null){ tmp.put(colName,p.value) } } rowMap.put(stp.toString(),tmp) stp++ } return rowMap } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T23:16:17.990", "Id": "73975", "Score": "1", "body": "Is there a hard requirement to read/write in xsl/xslx format? For instance, Excel can read/write data in CSV format, which is FAR easier to work with, IMO." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T01:16:34.597", "Id": "74005", "Score": "0", "body": "I'd have to agree with @Graham on this. Even if Excel file formats are required, it would be far easier to write a CSV, and then just use Excel for a quick import and save file-format conversion." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T10:55:13.913", "Id": "74038", "Score": "0", "body": "I am trying to put related data in a single excel and have designed it such that there are multiple sheets in one excel. CSV is a good option but how do i handle multiple sheets? I would like to make it easier from a non tech person to be able to edit this excel." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-25T18:35:57.453", "Id": "42794", "Score": "2", "Tags": [ "excel", "groovy" ], "Title": "Code to write data to Excel" }
42794
<p>I needed to impose on a Python method the following locking semantics: the method can only be run by one thread at a time. If thread B tries to run the method while it is already being run by thread A, then thread B immediately receives a return value of <code>None</code>.</p> <p>I wrote the following decorator to apply these semantics:</p> <pre><code>from threading import Lock def non_blocking_lock(fn): fn.lock = Lock() @wraps(fn) def locker(*args, **kwargs): if fn.lock.acquire(False): try: return fn(*args, **kwargs) finally: fn.lock.release() return locker </code></pre> <p>This works in my testing so far. Does anyone notice any gotchas or have any suggestions for improvements?</p> <h2>Revised version</h2> <p>After the suggestions by @RemcoGerlich, I have added a docstring and kept the lock local to the decorator:</p> <pre><code>from threading import Lock def non_blocking_lock(fn): """Decorator. Prevents the function from being called multiple times simultaneously. If thread A is executing the function and thread B attempts to call the function, thread B will immediately receive a return value of None instead. """ lock = Lock() @wraps(fn) def locker(*args, **kwargs): if lock.acquire(False): try: return fn(*args, **kwargs) finally: lock.release() return locker </code></pre>
[]
[ { "body": "<p>I think this will work fine and it's very close to how I would write it myself.</p>\n\n<p>A few small things come to mind:</p>\n\n<ul>\n<li><p>There's no documentation of any kind that explains what the semantics are, and they're not explicit either (the return None if the lock isn't acquired is entirely implicit). I would put the short explanation you put in this question into a docstring, and/or add an explicit <code>else: return None</code> to the if statement.</p></li>\n<li><p>is there any reason why the lock object is exposed to the outside world by making it a property of the function (<code>fn.lock</code>) ? I would simply make it a local variable, so that it's hidden. But I'm not sure.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T14:49:52.883", "Id": "73894", "Score": "0", "body": "Thank you for your feedback! I’ve amended my original code and added it to the question, for posterity." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-25T20:32:28.380", "Id": "42807", "ParentId": "42802", "Score": "6" } } ]
{ "AcceptedAnswerId": "42807", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-25T19:52:35.600", "Id": "42802", "Score": "8", "Tags": [ "python", "concurrency" ], "Title": "A non-blocking lock decorator in Python" }
42802
<p>As request of Simon's comment:</p> <p><strong>Direction.java</strong></p> <pre><code>package net.woopa.dungeon.datatypes; import java.util.Random; public enum Direction { NORTH, EAST, SOUTH, WEST; private static Random rnd = new Random(); static public Direction randomDirection() { return Direction.values()[rnd.nextInt(4)]; } // Rotate 90 degrees clockwise public Direction rotate90() { return values()[(ordinal() + 1) % 4]; } // Rotate 180 degrees public Direction rotate180() { return values()[(ordinal() + 2) % 4]; } // Rotate 270 degrees clockwise (90 counterclockwise) public Direction rotate270() { return values()[(ordinal() + 3) % 4]; } public Boolean isHorizontal() { return this == EAST || this == WEST; } public Boolean isVertical() { return this == NORTH || this == SOUTH; } public int dx(int steps) { if (this == EAST) { return steps; } if (this == WEST) { return -steps; } return 0; } public int dy(int steps) { if (this == NORTH) { return steps; } if (this == SOUTH) { return -steps; } return 0; } public int forwards_x(int n) { if (this == EAST) { return n + 1; } if (this == WEST) { return n - 1; } return n; } public int forwards_y(int n) { if (this == NORTH) { return n + 1; } if (this == SOUTH) { return n - 1; } return n; } public int backwards_x(int n) { if (this == EAST) { return n - 1; } if (this == WEST) { return n + 1; } return n; } public int backwards_y(int n) { if (this == NORTH) { return n - 1; } if (this == SOUTH) { return n + 1; } return n; } public int left_x(int n) { if (this == NORTH) { return n - 1; } if (this == SOUTH) { return n + 1; } return n; } public int left_y(int n) { if (this == EAST) { return n + 1; } if (this == WEST) { return n - 1; } return n; } public int right_x(int n) { if (this == NORTH) { return n + 1; } if (this == SOUTH) { return n - 1; } return n; } public int right_y(int n) { if (this == EAST) { return n - 1; } if (this == WEST) { return n + 1; } return n; } } </code></pre> <p>What are your thoughts about this class? The main grip I have personally is the <code>left_y</code>, <code>right_x</code>, etc methods. The code works, and here is some example of its usage below. But I feel there may be a better way?</p> <p><strong>Example usage:</strong></p> <pre><code>Direction dir = Direction.randomDirection(); if (grid.get(dir.left_x(x), dir.left_y(y)).equals(CoreMaterial.WALL) &amp;&amp; grid.get(dir.right_x(x), dir.right_y(y)).equals(CoreMaterial.WALL) &amp;&amp; grid.get(dir.backwards_x(x), dir.backwards_y(y)).equals(CoreMaterial.FLOOR) &amp;&amp; grid.get(dir.forwards_x(x), dir.forwards_y(y)).equals(CoreMaterial.FLOOR)) { StandardMethods.build_door(dir, new Vector2D(x, y), CoreMaterial.CAKE, grid); } </code></pre> <p>The above example has a location (x,y) for a door on a grid and then checks around it to ensure that there are doors either side and floors the other two either sides?</p> <hr> <p><strong>Symbols:</strong></p> <p><code>.</code> = floor</p> <p><code>#</code> = wall</p> <p><code>+</code> = door</p> <p><strong>Example:</strong></p> <pre><code>.#. .+. .#. </code></pre> <p>This would be okay for the placing of the door.</p>
[]
[ { "body": "<p>It is better to replace </p>\n\n<pre><code>return Direction.values()[rnd.nextInt(4)];\n</code></pre>\n\n<p>with something like</p>\n\n<pre><code>return Direction.values()[rnd.nextInt(Direction.values().length)];\n</code></pre>\n\n<p>for it to not break if you decide to add something like <code>NORTH_EAST</code>.</p>\n\n<p>I don't understand what functions like <code>dx(int steps)</code> are supposed to do, but it could be much easier to represent a direction as a vector. For example, rotation becomes simple multiplication, your methods are much more readable and robust. Also I don't understand why do you not use a Point-like class.</p>\n\n<p>Also it is not logical for a direction to house its very own object of Random class.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-25T23:06:48.333", "Id": "73801", "Score": "0", "body": "dx(int steps) requires a bit more context. Think of a 2D grid of points. I have a point say (x,y) and a direction, x is the horizontal plane and y in the vertical plane. dx(int steps) will move my (x,y) point that many steps in the x direction. Thus if the direction is in the vertical plane (North/South) it won't move my value of x. \n\nWriting this comment has made me realize that yes using a vector will be so much simpler... I will switch to this as suggested.\n\nThanks for the suggestions I will move Random too." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-25T22:06:51.793", "Id": "42819", "ParentId": "42817", "Score": "10" } }, { "body": "<p>I don't think that a <code>Direction</code> enum is sufficient to model your problem. <code>Direction</code> should just be a list of four cardinal directions. What you need is a <code>Cursor</code> or <code>Character</code> object that represents a position and heading on a grid. (Unfortunately, <code>Character</code> clashes with <code>java.lang.Character</code>, so you'll need to pick a different name.)</p>\n\n<p>Your code should look more or less like this. Design your <code>Cursor</code> class accordingly to make it work.</p>\n\n<pre><code>Cursor cur = new Cursor(grid, x, y, Direction.random());\nif ( CoreMaterial.WALL.equals(cur.getLeft()) &amp;&amp;\n CoreMaterial.WALL.equals(cur.getRight()) &amp;&amp;\n CoreMaterial.FLOOR.equals(cur.getBack()) &amp;&amp;\n CoreMaterial.FLOOR.equals(cur.getFront()) ) {\n StandardMethods.buildDoor(cur, CoreMaterial.CAKE);\n}\n</code></pre>\n\n<p>When you're done, the <code>Direction</code> enum should be pretty minimal — just a list of four cardinal directions and a <code>.random()</code> static method.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T10:02:17.763", "Id": "74034", "Score": "0", "body": "I really like this idea of a cursor, to me it just makes more sense than the forward_x, left_y methods etc. The only problem I see compared with rolfl's answer is that it won't be as efficient as a result as you would have to create a new object everytime you wished to use it. Maybe I just need better naming conventions for rolfl's answer." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-25T23:07:52.430", "Id": "42822", "ParentId": "42817", "Score": "5" } }, { "body": "<p>There are two things I think worth mentioning here:</p>\n\n<ul>\n<li>use of random</li>\n<li>magic numbers in enums</li>\n</ul>\n\n<h2>Random</h2>\n\n<p>Even though the <code>java.util.Random</code> class is thread-safe, it is not a great idea to use them in a multi-threaded context. As your class is an enum, it is likely that at some point it may be used in a threaded context (if it is not already). You should consider changing your code:</p>\n\n<blockquote>\n<pre><code>private static Random rnd = new Random();\n</code></pre>\n</blockquote>\n\n<p>to instead be (note also that this is 'final', and this is a <code>java.util.concurrent.ThreadLocalRandom</code>):</p>\n\n<pre><code>private static final ThreadLocalRandom rnd = ThreadLocalRandom.current();\n</code></pre>\n\n<p>This will give you better scalability in the future (or the present if you are already multi-threaded.</p>\n\n<h2>Enum Magic Numbers</h2>\n\n<p>Enums are a great concept in Java, and, it is one of those places where I believe magic numbers (special values with little apparent context or meaning) are really useful, and are OK.</p>\n\n<p>You can embed 'magic' in with the enums and not worry too much about the readability... enums are supposed to be magic things.... So, I would consider code like the following:</p>\n\n<pre><code>import java.util.concurrent.ThreadLocalRandom;\n\npublic enum Direction {\n\n // use magic numbers to set the ordinal (used for rotation),\n // and the dx and dy of each direction.\n NORTH(0, 0, 1),\n EAST(1, 1, 0),\n SOUTH(2, 0, -1),\n WEST(3, -1, 0);\n\n private static final ThreadLocalRandom rnd = ThreadLocalRandom.current();\n\n static public Direction randomDirection() {\n return Direction.values()[rnd.nextInt(4)];\n }\n\n private final int r90index, r180index, r270index;\n private final boolean horizontal, vertical;\n private final int dx, dy;\n\n private Direction(int ordinal, int dx, int dy) {\n // from the ordinal, dx, and dy, we can calculate all the other constants.\n this.dx = dx;\n this.dy = dy;\n this.horizontal = dx != 0;\n this.vertical = !horizontal;\n this.r90index = (ordinal + 1) % 4; \n this.r180index = (ordinal + 2) % 4; \n this.r270index = (ordinal + 3) % 4; \n }\n\n\n // Rotate 90 degrees clockwise\n public Direction rotate90() {\n return values()[r90index];\n }\n\n // Rotate 180 degrees\n public Direction rotate180() {\n return values()[r180index];\n }\n\n // Rotate 270 degrees clockwise (90 counterclockwise)\n public Direction rotate270() {\n return values()[r270index];\n }\n\n public Boolean isHorizontal() {\n return horizontal;\n }\n\n public Boolean isVertical() {\n return vertical;\n }\n\n public int dx(int steps) {\n return dx * steps;\n }\n\n public int dy(int steps) {\n return dy * steps;\n }\n\n public int forwards_x(int n) {\n return n + dx;\n }\n\n public int forwards_y(int n) {\n return n + dy;\n }\n\n public int backwards_x(int n) {\n return n - dx;\n }\n\n public int backwards_y(int n) {\n return n - dy;\n }\n\n public int left_x(int n) {\n // if we are E/W facing, our left/right 'x' co-ords are still 'x'\n // if we are N/S facing, our left/right 'x' is `-dy`\n return n - dy;\n }\n\n public int left_y(int n) {\n // see left_x comments for the idea\n return n + dx;\n }\n\n public int right_x(int n) {\n // see left_x comments for the idea\n return n + dy;\n }\n\n public int right_y(int n) {\n // see left_x comments for the idea\n return n - dx;\n }\n}\n</code></pre>\n\n<p>The code above is very efficient. There are no conditionals in the methods, they will likely all be inlined in to the calling code. The 'smarts' are all contained within the enum, it 'just works'.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T12:15:52.650", "Id": "74046", "Score": "0", "body": "I like the efficiency of this class and the fact it doesn't require me to change any of the other code in the project. I did however add `public Vector2D getFront(Vector2D vec) {\nreturn new Vector2D(this.forwards_x(vec.getX()), this.forwards_y(vec.getY()));}...` as I liked 200_success's naming convention, the simplicity and it didn't have any noticable drop in performance." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T00:08:37.283", "Id": "42828", "ParentId": "42817", "Score": "12" } }, { "body": "<p>An enum is a nice simple way to represent cardinal directions. No problem there. All the functions you've provided are valuable to consumers. No problem there.</p>\n\n<p>But within the class, when you implement all those functions, the enum is getting in the way and making things complicated. The enum is there for your users, not for you. I would suggest you internally use a representation that makes more sense, like 2D coordinates. You have a lot of math that will make more sense with 2D coordinates.</p>\n\n<p>A simple way to do that is to translate enums to coordinates for internal math, and back to enums for results.</p>\n\n<pre><code>private int[][] coordinates = new int[][] {\n new int[] {0,1, 0}, // NORTH (the third element maps back to the enum)\n new int[] {1,0, 1}, // EAST\n new int[] {0,-1, 2}, // SOUTH\n new int[] {-1,0, 3} // WEST\n};\npublic int[] toCoordinates(Direction d) {\n return coordinates[d.ordinal()];\n}\npublic static Direction coordinatesToEnum(int[] c) {\n return Direction.values(c[2]);\n}\n\npublic Boolean isVertical() {\n return this.toCoordinates()[1] == 0;\n}\npublic Direction rotate180() {\n int[] c = this.toCoordinates();\n int result = new int[] { c[0]*-1, c[1]*-1 };\n return coordinatesToEnum(result);\n}\n// and so forth.\n</code></pre>\n\n<p>(This also allows your users to convert easily to coordinate system if that's better for them. Up to you whether you document that.)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T00:50:18.777", "Id": "42830", "ParentId": "42817", "Score": "7" } }, { "body": "<p>Rename <code>rotate90</code>, <code>rotate180</code>, and <code>rotate270</code> as <code>right</code>, <code>reverse</code>, and <code>left</code>, respectively. Don't use degrees unless you have to, and in this case they have nothing to do with this geometry system.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T11:57:09.600", "Id": "73868", "Score": "0", "body": "Furthermore, it's ambiguous whether `rotate90` means \"right\" (compass heading convention) or \"left\" (mathematicians' convention)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T01:05:05.643", "Id": "42831", "ParentId": "42817", "Score": "3" } } ]
{ "AcceptedAnswerId": "42828", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-25T21:56:22.967", "Id": "42817", "Score": "14", "Tags": [ "java", "enum" ], "Title": "Direction enum class" }
42817
<p>I've just finished writing my first game: a clone of the classic Pong game for Linux and Mac only. You will need SDL 2.0, SDL_ttf 2.0 and SDL_Mixer 2.0 to compile it. The complete project can be found <a href="https://github.com/chaficnajjar/pong">here</a>.</p> <p>My experience with C++ and game development in general is fairly limited and I would like to know what could be improved in my code.</p> <p>Some questions I have:</p> <ol> <li>Would it be better to use OOP?</li> <li>Should I be using headers?</li> <li>Should I divide the code into multiple files?</li> </ol> <p></p> <pre><code>/* * Pong game * Author: Chafic Najjar &lt;chafic.najjar@gmail.com&gt; * Note: Origin of the coordinate system is the upper left corner of the screen */ #include &lt;SDL2/SDL.h&gt; // SDL library #include &lt;SDL2/SDL_ttf.h&gt; // SDL font library #include &lt;SDL2/SDL_mixer.h&gt; // SDL sound library #include &lt;cmath&gt; // abs() #include &lt;ctime&gt; // rand() #include &lt;iostream&gt; using namespace std; SDL_Window* window; // holds window properties SDL_Renderer* renderer; // holds rendering surface properties SDL_Texture* font_image_score1; // holds text indicating player 1 score (left) SDL_Texture* font_image_score2; // holds text indicating palyer 2 score (right) SDL_Texture* font_image_winner; // holds text indicating winner SDL_Texture* font_image_restart; // holds text suggesting to restart the game SDL_Texture* font_image_launch1; // holds first part of text suggesting to launch the ball SDL_Texture* font_image_launch2; // holds second part of text suggesting to launch the ball Mix_Chunk *paddle_sound; // holds sound produced after ball collides with paddle Mix_Chunk *wall_sound; // holds sound produced after ball collides with wall Mix_Chunk *score_sound; // holds sound produced when updating score SDL_Color dark_font = {67, 68, 69}; // dark grey SDL_Color light_font = {187, 191, 194}; // light grey bool done = false; // true when player exits game // Screen resolution int SCREEN_WIDTH = 640; int SCREEN_HEIGHT = 480; // Controllers bool mouse = true; bool keyboard = false; // Mouse coordinates; int mouse_x, mouse_y; // Paddle lengths const int PADDLE_WIDTH = 10; const int PADDLE_HEIGHT = 60; // Paddle position int left_paddle_x = 40; int left_paddle_y = SCREEN_HEIGHT / 2 - 30; int right_paddle_x = SCREEN_WIDTH - (40+PADDLE_WIDTH); int right_paddle_y = SCREEN_HEIGHT / 2 - 30; // Launch ball bool launch_ball = false; // Ball dimensions const int BALL_WIDTH = 10; const int BALL_HEIGHT = 10; // Ball position int x_ball = SCREEN_WIDTH / 2; int y_ball = SCREEN_HEIGHT / 2; // Ball movement int ball_dx = 0; // movement in pixels over the x-axis for the next frame (speed on the x-axis) int ball_dy = 0; // movement in pixels over the y-axis for the next frame (speed on the y-axis) int speed = 8; // ball speed = √(dx²+dy²) int hit_count = 0; // counts the number of hits of the ball with the right paddle // after three hits, speed increases by one float angle = 0.0f; // angle on collision with paddle bool bounce = false; // true when next frame renders ball after collision impact (ball has bounced) // Match score int score1 = 0; int score2 = 0; bool left_score_changed = true; // indicates when rendering new score is necessary bool right_score_changed = true; // indicates when rendering new score is necessary // Prediction int final_predicted_y; // predicted ball position on y-axis after right paddle collision (used for paddle AI) // Font names string fonts[] = {"Lato-Reg.TTF", "FFFFORWA.TTF"}; void renderTexture(SDL_Texture *tex, SDL_Renderer *ren, SDL_Rect dst, SDL_Rect *clip = nullptr) { SDL_RenderCopy(ren, tex, clip, &amp;dst); } void renderTexture(SDL_Texture *tex, SDL_Renderer *ren, int x, int y, SDL_Rect *clip = nullptr) { SDL_Rect dst; dst.x = x; dst.y = y; if (clip != nullptr){ dst.w = clip-&gt;w; dst.h = clip-&gt;h; } else SDL_QueryTexture(tex, NULL, NULL, &amp;dst.w, &amp;dst.h); renderTexture(tex, ren, dst, clip); } SDL_Texture* renderText(const string &amp;message, const string &amp;fontFile, SDL_Color color, int fontSize, SDL_Renderer *renderer) { TTF_Font *font = TTF_OpenFont(fontFile.c_str(), fontSize); SDL_Surface *surf = TTF_RenderText_Blended(font, message.c_str(), color); SDL_Texture *texture = SDL_CreateTextureFromSurface(renderer, surf); SDL_FreeSurface(surf); TTF_CloseFont(font); return texture; } // Imprecise prediction of ball position on the y-axis after right paddle collision int predict() { // Find slope float slope = (float)(y_ball - y_ball+ball_dy)/(x_ball - x_ball+ball_dx); // Distance between paddles int paddle_distance = right_paddle_x - (left_paddle_x+PADDLE_WIDTH); // Prediction without taking into consideration upper and bottom wall collisions int predicted_y = abs(slope * -(paddle_distance) + y_ball); // Calculate number of reflexions int number_of_reflexions = predicted_y / SCREEN_HEIGHT; // Predictions taking into consideration upper and bottom wall collisions if (number_of_reflexions % 2 == 0) // Even number of reflexions predicted_y = predicted_y % SCREEN_HEIGHT; else // Odd number of reflexsion predicted_y = SCREEN_HEIGHT - (predicted_y % SCREEN_HEIGHT); return predicted_y; } // Get user input void input() { SDL_Event event; // stores next event to be processed // Queuing events while(SDL_PollEvent(&amp;event)) { // Track mouse movement if (event.type == SDL_MOUSEMOTION) SDL_GetMouseState(&amp;mouse_x, &amp;mouse_y); // Clicking 'x' or pressing F4 if (event.type == SDL_QUIT) done = true; // Pressing a key if (event.type == SDL_KEYDOWN) switch(event.key.keysym.sym) { // Pressing ESC exits from the game case SDLK_ESCAPE: done = true; break; // Pressing space will launch the ball if it isn't already launched case SDLK_SPACE: if (!launch_ball) { int direction = 1+(-2)*(rand()%2); // either 1 or -1 angle = rand()%120-60; // between -60 and 59 ball_dx = direction*speed*cos(angle*M_PI/180.0f); // speed on the x-axis ball_dy = speed*sin(angle*M_PI/180.0f); // speed on the y-axis // Find slope float slope = (float)(y_ball - y_ball+ball_dy)/(x_ball - x_ball+ball_dx); // Distance between left paddle and center int paddle_distance = SCREEN_WIDTH/2 - (left_paddle_x+PADDLE_WIDTH); // Predicting where the left paddle should go in case ball is launched left final_predicted_y = abs(slope * -(paddle_distance) + y_ball); launch_ball = true; } break; // Pressing F11 to toggle fullscreen case SDLK_F11: int flags = SDL_GetWindowFlags(window); if(flags &amp; SDL_WINDOW_FULLSCREEN) SDL_SetWindowFullscreen(window, 0); else SDL_SetWindowFullscreen(window, SDL_WINDOW_FULLSCREEN); break; } } } // Check if collision with left paddle occurs in next frame bool checkLeftCollision() { if (!(x_ball + ball_dx &lt;= left_paddle_x + PADDLE_WIDTH)) return false; if (x_ball &lt; left_paddle_x) return false; if (!(y_ball + BALL_WIDTH &gt;= left_paddle_y &amp;&amp; y_ball &lt;= left_paddle_y + PADDLE_HEIGHT)) return false; return true; } // Check if collision with right paddle occurs in next frame bool checkRightCollision() { if (!(x_ball + BALL_WIDTH + ball_dx &gt;= right_paddle_x)) return false; if (x_ball &gt; right_paddle_x + PADDLE_WIDTH) return false; if (!(y_ball + BALL_WIDTH &gt; right_paddle_y &amp;&amp; y_ball &lt;= right_paddle_y + PADDLE_HEIGHT)) return false; return true; } // Update game values void update() { // Right paddle follows the player's mouse movement on the y-axis if (mouse == true) right_paddle_y = mouse_y; /* Basic AI */ // Ball on the left 3/5th side of the screen and going left if (x_ball &lt; SCREEN_WIDTH*3/5 &amp;&amp; ball_dx &lt; 0) { // Follow the ball if (left_paddle_y + (PADDLE_HEIGHT - BALL_HEIGHT)/2 &lt; final_predicted_y-2) left_paddle_y += speed/8 * 5; else if (left_paddle_y + (PADDLE_HEIGHT - BALL_HEIGHT)/2 &gt; final_predicted_y+2) left_paddle_y -= speed/8 * 5; } // Ball is anywhere on the screen but going right else if (ball_dx &gt;= 0) { // Left paddle slowly moves to the center if (left_paddle_y + PADDLE_HEIGHT / 2 &lt; SCREEN_HEIGHT/2) left_paddle_y += 2; else if (left_paddle_y + PADDLE_HEIGHT / 2 &gt; SCREEN_HEIGHT/2) left_paddle_y -= 2; } /* Paddle-wall collision */ // No need to anticipate the right paddle going above the screen, mouse coordinates cannot be negative // Right paddle shouldn't be allowed to go below the screen if (right_paddle_y + PADDLE_HEIGHT &gt; SCREEN_HEIGHT) right_paddle_y = SCREEN_HEIGHT - PADDLE_HEIGHT; // Left paddle shouldn't be allowed to go above the screen if (left_paddle_y &lt; 0) left_paddle_y = 0; // Left paddle shouldn't be allowed to below the screen else if (left_paddle_y + PADDLE_HEIGHT &gt; SCREEN_HEIGHT) left_paddle_y = SCREEN_HEIGHT - PADDLE_HEIGHT; // We're done updating values if the ball hasn't been launched yet if (!launch_ball) return; // Three hits =&gt; increment ball speed and reset hit counter if (hit_count == 3) { speed++; hit_count = 0; } // Smooth collision between ball and left paddle if (checkLeftCollision()) { if (bounce) { // y coordinate of the ball in relation to the left paddle (from 0 to 70) int left_relative_y = (y_ball - left_paddle_y + BALL_HEIGHT); // Angle formed between ball direction and left paddle after collision angle = (2.14f * left_relative_y - 75.0f); ball_dx = speed*cos(angle*M_PI/180.0f); // convert angle to radian, find its cos() and multiply by the speed ball_dy = speed*sin(angle*M_PI/180.0f); // convert angle to radina, find its sin() and multiply by the speed bounce = false; // finished bouncing } x_ball = left_paddle_x + PADDLE_WIDTH; // deposit ball on left paddle surface (smooth collision) bounce = true; // bounce ball on next frame Mix_PlayChannel(-1, paddle_sound, 0); // Play collision sound } // Smooth collision between ball and right paddle else if (checkRightCollision()) { if (bounce) { // y coordinate of the ball in relation to the right paddle (from 0 to 70) int right_relative_y = (y_ball - right_paddle_y + BALL_HEIGHT); // Angle formed between ball direction and right paddle after collision angle = (2.14 * right_relative_y - 75.0f); ball_dx = -speed*cos(angle*M_PI/180.0f);// convert angle to radian, find its cos() and multiply by the negative of speed ball_dy = speed*sin(angle*M_PI/180.0f); // convert angle to radian, find its sin() and multiply by the speed bounce = false; // finished bouncing } x_ball = right_paddle_x - BALL_WIDTH; // deposit ball on surface right paddle surface (smooth collision) hit_count++; // increment hit counter bounce = true; // bounce ball on next frame Mix_PlayChannel(-1, paddle_sound, 0); // play collision sound final_predicted_y = predict(); // predict ball position for AI to intercept } // Upper and bottom walls collision else if ( (y_ball + ball_dy &lt; 0) || (y_ball + BALL_HEIGHT + ball_dy &gt;= SCREEN_HEIGHT) ) { ball_dy *= -1; // reverse ball direction on y-axis Mix_PlayChannel(-1, wall_sound, 0); // play collision sound } // No collision occurs, update ball coordinates else { x_ball += ball_dx; y_ball += ball_dy; } // If ball goes out... if (x_ball &gt; SCREEN_WIDTH || x_ball &lt; 0) { // Change score if (x_ball &gt; SCREEN_WIDTH) { score1++; left_score_changed = true; } else { score2++; right_score_changed = true; } // Play score sound Mix_PlayChannel(-1, score_sound, 0); // Reset ball position as before launch x_ball = SCREEN_WIDTH / 2; y_ball = SCREEN_HEIGHT / 2; // Ball is fixed ball_dx = 0; ball_dy = 0; launch_ball = false; // Speed and hit counter are reset to their initial positions speed = 8; hit_count = 0; } } // Render objects on screen void render() { // Clear screen (background color) SDL_SetRenderDrawColor( renderer, 67, 68, 69, 255 ); // dark grey SDL_RenderClear(renderer); // Color left background with light grey SDL_Rect left_background = { SCREEN_WIDTH / 2, 0, SCREEN_WIDTH / 2, SCREEN_HEIGHT }; SDL_SetRenderDrawColor( renderer, 187, 191, 194, 255 ); SDL_RenderFillRect( renderer, &amp;left_background ); // Paddle color SDL_SetRenderDrawColor( renderer, 212, 120, 102, 255 ); // Render filled paddle SDL_Rect paddle1 = { left_paddle_x, left_paddle_y, PADDLE_WIDTH, PADDLE_HEIGHT }; SDL_RenderFillRect( renderer, &amp;paddle1 ); // Render filled paddle SDL_Rect paddle2 = { right_paddle_x, right_paddle_y, PADDLE_WIDTH, PADDLE_HEIGHT }; SDL_RenderFillRect( renderer, &amp;paddle2 ); // Render ball SDL_Rect ball = { x_ball - BALL_WIDTH / 2, y_ball, BALL_WIDTH, BALL_HEIGHT }; SDL_RenderFillRect(renderer, &amp;ball); // Render scores if (left_score_changed) { font_image_score1 = renderText(to_string(score1), "Lato-Reg.TTF", light_font, 24, renderer); left_score_changed = false; } renderTexture(font_image_score1, renderer, SCREEN_WIDTH * 4 / 10, SCREEN_HEIGHT / 12); int score_font_size = 24; if (right_score_changed) { font_image_score2 = renderText(to_string(score2), "Lato-Reg.TTF", dark_font, score_font_size, renderer); right_score_changed = false; } renderTexture(font_image_score2, renderer, SCREEN_WIDTH * 6 / 10 - score_font_size/2, SCREEN_HEIGHT/ 12); // Render text indicating the winner if (score1 == 5) { font_image_winner = renderText("Player 1 won!", fonts[0], light_font, 24, renderer); renderTexture(font_image_winner, renderer, SCREEN_WIDTH * 1 / 10 + 3, SCREEN_HEIGHT / 4); // align with score font_image_restart = renderText("Press SPACE to restart", fonts[0], light_font, 18, renderer); renderTexture(font_image_restart, renderer, SCREEN_WIDTH * 1 / 10 + 3, SCREEN_HEIGHT / 3); if (launch_ball) { score1 = 0; score2 = 0; left_score_changed = true; right_score_changed = true; } } else if (score2 == 5) { font_image_winner = renderText("Player 2 won!", fonts[0], dark_font, 24, renderer); renderTexture(font_image_winner, renderer, SCREEN_WIDTH * 6 / 10 - score_font_size/2, SCREEN_HEIGHT / 4); // align with score font_image_restart = renderText("Press SPACE to restart", fonts[0], dark_font, 18, renderer); renderTexture(font_image_restart, renderer, SCREEN_WIDTH * 6 / 10 - score_font_size/2, SCREEN_HEIGHT / 3); if (launch_ball) { score1 = 0; score2 = 0; left_score_changed = true; right_score_changed = true; } } // Draw "Press SPACE to start" else if (!launch_ball) { renderTexture(font_image_launch1, renderer, SCREEN_WIDTH / 2 - 80, SCREEN_HEIGHT - 25); renderTexture(font_image_launch2, renderer, SCREEN_WIDTH / 2 + 1, SCREEN_HEIGHT - 25); } // Swap buffers SDL_RenderPresent(renderer); } void cleanUp() { // Destroy textures SDL_DestroyTexture(font_image_score1); SDL_DestroyTexture(font_image_score2); // Free the sound effects Mix_FreeChunk(paddle_sound); Mix_FreeChunk(wall_sound); Mix_FreeChunk(score_sound); // Quit SDL_mixer Mix_CloseAudio(); // Destroy renderer and window SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); // Shuts down SDL SDL_Quit(); } void gameLoop() { while(!done) { input(); update(); render(); } cleanUp(); } void initialize() { // Initialize SDL SDL_Init(SDL_INIT_EVERYTHING); // Create window in the middle of the screen window = SDL_CreateWindow( "Pong", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN); // Create renderer in order to draw on window renderer = SDL_CreateRenderer( window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC ); // Initialize font TTF_Init(); // Holds text "Press SPACE to start" font_image_launch1 = renderText("Press SPA", fonts[0], light_font, 18, renderer); font_image_launch2 = renderText("CE to start", fonts[0], dark_font, 18, renderer); // Initialize SDL_Mixer Mix_OpenAudio(22050, MIX_DEFAULT_FORMAT, 2, 1024); // Load sounds paddle_sound = Mix_LoadWAV("./sounds/paddle_hit.wav"); wall_sound = Mix_LoadWAV("./sounds/wall_hit.wav"); score_sound = Mix_LoadWAV("./sounds/score_update.wav"); // Don't show cursor SDL_ShowCursor(0); } int main(int argc, char *argv[]) { srand(time(NULL)); initialize(); gameLoop(); return 0; } </code></pre>
[]
[ { "body": "<p><strong>Global variables</strong></p>\n\n<p>You have <em>many</em> global variables, which is very bad. In general, global variables should be avoided as they can be modified anywhere in the program and at any time. This especially makes debugging difficult as you won't be able to keep track of where these variables could have been modified, as it can happen anywhere in the program.</p>\n\n<p>I also cannot tell which of these should be constants (minus the two that are already constants). If any of them should be a constant, add <code>const</code>. Those can then stay there as they'll no longer be mutable.</p>\n\n<p>For the rest, you should be passing them to functions as needed, or just keep them in one function if they're only used in one. They can be passed separately, or encapsulated in a container class, depending on the situation. This will give you a much better idea of how each variable is used, making debugging and maintainability easier.</p>\n\n<p><strong>Classes</strong></p>\n\n<p>Yes, you should consider using OOP or at least just classes. I'm not too familiar with OOP, so I won't go more into that. But I can say that you should at least consider having a <code>Game</code> class and probably additional classes if needed.</p>\n\n<p>With this, yes, you'll need to have multiple files. The driver file will just have <code>main()</code> and will include any needed headers. A separate header and implementation file will be for <code>Game</code>. In the driver, you create a <code>Game</code> object, which will essentially run the game.</p>\n\n<p>You could also have, say, a <code>Ball</code> class and a <code>Paddle</code> class. Basically, if you have some \"object\" that holds data and has functions to modify that data, it could have its own class. This will help encapsulate your program even more, allowing you to manage these separate classes instead of just straight functions and variables that can correspond with anything.</p>\n\n<p><strong>Misc.</strong></p>\n\n<ul>\n<li><p><a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">I'd recommend against using <code>using namespace std</code></a>.</p></li>\n<li><p>I see that you use <code>nullptr</code>, yet your <code>std::srand()</code> call uses <code>NULL</code>. If you have access to <code>nullptr</code>, you should use it everywhere as needed and replace <code>NULL</code>.</p></li>\n<li><p>As you are using C++11, you should no longer use <code>std::srand()</code> and <code>std::rand()</code>. You should instead consider any of the new functionality found in <a href=\"http://en.cppreference.com/w/cpp/header/random\" rel=\"nofollow noreferrer\"><code>&lt;random&gt;</code></a>.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-25T23:46:10.263", "Id": "42826", "ParentId": "42823", "Score": "13" } }, { "body": "<blockquote>\n <p>Would it be better to use OOP?</p>\n</blockquote>\n\n<p>I'd prefer it if you did: I find it easier to read.</p>\n\n<p>Your variables are already well-commented and grouped into ... groups.</p>\n\n<pre><code>// Screen resolution\n// Controllers\n// Mouse coordinates;\n// Paddle lengths\n// Paddle position\n// Launch ball\n// Ball dimensions\n// Ball position\n// Ball movement\n// Match score\n// Prediction\n// Font names\n</code></pre>\n\n<p>To start with you can refactor that into structs:</p>\n\n<pre><code>// Ball position\nint x_ball = SCREEN_WIDTH / 2;\nint y_ball = SCREEN_HEIGHT / 2;\n\n// Ball movement\nint ball_dx = 0; // movement in pixels (speed) over the x-axis\nint ball_dy = 0; // movement in pixels (speed) over the y-axis\n\nint speed = 8; // ball speed = √(dx²+dy²)\n</code></pre>\n\n<p>... becomes ...</p>\n\n<pre><code>struct Ball\n{\n int x;\n int y;\n int dx;\n int dy;\n int speed;\n};\n</code></pre>\n\n<p>That alone is a win:</p>\n\n<ul>\n<li>Assuming there's an instance of <code>Ball</code> named <code>ball</code>, and assuming you name the parameter <code>ball</code> whenever you pass it by parameter, I can search the code for 'ball' to see all lines of code which affect the ball</li>\n<li>You can more easily change the game to contain more than one ball instance</li>\n<li><p>You can refactor some details, for example make speed a method instead of an independent variable:</p>\n\n<pre><code>int speed() const { return (int)sqrt(dx*dx + dy*dy); }\n</code></pre></li>\n<li><p>If you make the data private and accessed via accessor method like <code>void setX(int x) { this.x = x; }</code> and <code>int getX() const { return x; }</code> then I can find the places where <code>x</code> is being written and where it's being read</p></li>\n<li>You can move more functionality into the class; for example you don't change <code>x</code> and <code>y</code> independently, you change them both at the same time, so there should probably be one <code>Ball</code> method which changes both of them</li>\n<li>After you've moved most of the functionality into helper methods of the various classes, then the remaining logic of the game is clearer: the game code will say what happens in each turn but doesn't need to say how (the 'how' is implemented inside helper methods like <code>bool ball.CollidesWith(const Paddle&amp;) const { ... }</code>).</li>\n</ul>\n\n<p>This looks like good C code. It isn't really \"C++\" code (no classes, not OOP).</p>\n\n<p>On a minor note I'm not sure that your checkColission functions are completely accurate: for example because they're ignoring ball_dy. You need a little trignometry there: add a little bit of dy, depending on what percentage of dx is required to reach the paddle line.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-23T14:02:53.590", "Id": "179049", "Score": "0", "body": "*It isn't really \"C++\" code (no classes, not OOP)* Classes and OOP are not what makes code \"C++\". What makes (this) code \"C\" is reliance on legacy C mechanisms (manual resource lifetime management) where C++ offers less error-prone solutions (RAII in general, `std::unique_ptr` in particular)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-23T14:09:29.023", "Id": "179054", "Score": "0", "body": "The code in the OP literally looks like C (not C++) code, which would compile with a C compiler." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-23T14:27:03.203", "Id": "179062", "Score": "0", "body": "Anyway, the code works and right API functions are called in the right order. It would need the restructuring you suggest, whether \"C\" or \"C++\". I mean that to deem it \"C++\", I would not require usage of classes and OOP as you mention, but of RAII, `<math>` and `<random>` instead of resp. manual resource management, `<cmath>` and `<ctime>`." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T00:22:32.493", "Id": "42829", "ParentId": "42823", "Score": "12" } }, { "body": "<p>Here are my two cents:</p>\n\n<ul>\n<li>The call to <code>cleanUp</code> is misplaced with regards to <code>initialize</code>, since the former undoes what the latter does. It should be taken out of <code>gameLoop</code> and called right after it.</li>\n</ul>\n\n<p>In C++, there is something called RAII (Resource Acquisition Is Initialization). A resource is something external to your program, that your program has to borrow AND give back. (file handles <code>fopen</code>/<code>fclose</code>, chunks of heap memory <code>malloc</code>/<code>free</code>, free-store objects <code>new</code>/<code>delete</code>, textures <code>SDL_CreateTextureFromSurface</code>/<code>SDL_DestroyTexture</code>, ...)</p>\n\n<p>Since you're using <code>nullptr</code>, I bet you are using C++11. C++11 provides smart pointers to automatically manage resources. Since you're owning resources like textures, surfaces and the like, here is an example to use <code>unique_ptr</code>to manage your resources.</p>\n\n<pre><code>#include &lt;memory&gt;\n\nnamespace internal {\n struct TextureDeleter {\n void operator()(SDL_Texture* resource) {\n if(resource != nullptr) {\n SDL_DestroyTexture(resource);\n }\n }\n }\n}\n\nusing Texture = std::unique_ptr&lt;SDL_Texture, internal::TextureDeleter&gt;;\n</code></pre>\n\n<p>Now, you have a type name <code>Texture</code> which represents a smart pointer on <code>SDL_Texture</code>. When an object of this type is destroyed, <code>SDL_DestroyTexture</code> will be called on the owned <code>SDL_Texture*</code>.</p>\n\n<p>Use this type for textures you have to free at some point. (<code>font_image_score1</code>,...) The lifetime of your <code>SDL_Texture</code> will then match the lifetime of your objects, which is why they have to be as local as possible. (instead of global variables, as suggested by another answer) In particular, their lifetime have to be strictly contained between <code>SDL_Init</code> and <code>SDL_Quit</code>.</p>\n\n<p>Make your resources more local, and use RAII, and you'll see your resource-freeing code disintegrate like a start-up.</p>\n\n<p>There are other idioms usable for system initialization (involving <code>weak_ptr</code>s) but that's a bit out of scope.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-18T08:20:11.337", "Id": "54605", "ParentId": "42823", "Score": "5" } }, { "body": "<p>That's pretty code, for your first game. I like that you commented each variable at the top.</p>\n\n<p>I would recommend against using OOP or multiple files. It takes time away from what should be a fluid iterative process of tweaking the game as you play it.</p>\n\n<p>In fact, for something this simple, I wouldn't even use C++, C would have worked just as well.</p>\n\n<p>But, more importantly, that's not how Pong works! The paddle is divided into a small amount of regions, each of which reflects the ball in a different way. See Diagram \\$6(b)\\$ <a href=\"http://web.mit.edu/6.111/www/s2007/LABS/LAB4/lab4.pdf\" rel=\"nofollow\">here</a> for more information.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-07T04:38:09.383", "Id": "96046", "ParentId": "42823", "Score": "2" } } ]
{ "AcceptedAnswerId": "42826", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-25T23:08:54.317", "Id": "42823", "Score": "22", "Tags": [ "c++", "game", "c++11", "sdl" ], "Title": "Pong game using SDL 2.0" }
42823
<p>So I've got a jquery project where I'm using an external class that has callback style events. Meaning, it has an "onSave" property that takes one function. However, I need to more than one other component to hook into it.</p> <p>What I've settled on for now, goes like this:</p> <pre><code>var saveCallbacks = $.Callbacks(); saveCallbacks.fire.callbacks = saveCallbacks; globalDoodad.onSave = saveCallbacks.fire; </code></pre> <p>which allows me to do this in my other components:</p> <pre><code>globalDoodad.onSave.callbacks.add( myMethod ); </code></pre> <p>Is there a better, or at least more standard, way to handle this? It seems to be working ok, just has a bit of a smell to it.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T04:16:43.723", "Id": "73822", "Score": "0", "body": "Is confusing how you add a reference of an object to itself. What is the external class you are using? I created a gist once of a JS class that facilitates the creation of jQuery plugins with a jQuery UI style interface, no longer use but you might find it useful https://gist.github.com/ptejada/2269151" } ]
[ { "body": "<p>I think what you need is a global <a href=\"http://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern\" rel=\"nofollow\">pub-sub facility</a>. Modules you have subscribe to certain events. These subscriptions (functions) get executed when that event is published, usually with data. </p>\n\n<p>This allows different modules, from different parts of your program, to interact even without direct visibility with each other. The only dependency visible to your modules is the pub-sub module.</p>\n\n<p>For instance this:</p>\n\n<pre><code>// ModuleA.js\nPubSub.module('moduleA',function(tower){\n tower.subscribe('foo',function(data){\n // executes when somewhere else publishes a foo\n alert('foo executed in A with ' + data.join(' '));\n });\n});\n\n// ModuleB.js\nPubSub.module('moduleB',function(tower){\n tower.subscribe('foo',function(data){\n // executes when somewhere else publishes a foo\n alert('foo executed in B with ' + data.join(' '));\n });\n});\n\n// ModuleC.js\nPubSub.module('moduleC',function(tower){\n $(document).on('click',function(){\n // publish a foo event, passing 1 and 2, which arrives as \"data\" in each handler\n tower.publish('foo','1','2');\n });\n});\n</code></pre>\n\n<hr>\n\n<p>jQuery has built-in event-handling capabilities, which also allow custom events. You can use this ability as your pub-sub facility.</p>\n\n<pre><code>var test = $(document); // You can bind it to any object. document is handy.\ntest.on('sampleevent',function(){ // Add a handler\n alert('executed');\n});\n\ntest.trigger('sampleevent'); // Execute\n</code></pre>\n\n<p>You can also implement your own, which doubles as a good programming practice. <a href=\"https://github.com/fskreuz/MiniEvent\" rel=\"nofollow\">Here's my version of it</a>, which I based on <a href=\"http://nodejs.org/api/events.html\" rel=\"nofollow\">Node.js's EventEmitter.</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T12:01:57.387", "Id": "42861", "ParentId": "42833", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T02:03:58.337", "Id": "42833", "Score": "3", "Tags": [ "javascript", "jquery", "callback" ], "Title": "Using jquery Callbacks.fire method as a event handler" }
42833
<pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; struct Stack { int value; int is_empty; struct Stack *next; }; int pop(struct Stack **stack) { if ((*stack)-&gt;is_empty == 1) { printf("Stack is empty!\n"); abort(); // not sure what this does } else { int value = (*stack)-&gt;value; // outer pointer (static) points to new stack now *stack = (*stack)-&gt;next; return value; } } void push(struct Stack **stack, int value) { // malloc is used so this memory can be accessed outside of scope struct Stack *head = malloc(sizeof(struct Stack*)); if (head != NULL) { head-&gt;value = value; // head's next is pointer to stack head-&gt;next = *stack; head-&gt;is_empty = 0; // stack now holds pointer to head *stack = head; } else { printf("push memory no alloc"); } } struct Stack *empty() { struct Stack *head = malloc(sizeof(struct Stack *)); if (head != NULL) { head-&gt;value = 0; head-&gt;is_empty = 1; head-&gt;next = NULL; return head; } else { return NULL; } } int main() { struct Stack *init = empty(); struct Stack **stack = &amp;init; push(stack, 3); push(stack, 2); push(stack, 1); int one = pop(stack); printf("one: %d\n", one); int two = pop(stack); printf("two: %d\n", two); int three = pop(stack); printf("three: %d\n", three); //int hmm = pop(stack); } </code></pre> <p>I'm not sure pointers to pointers is the best way to do this. I also feel like I'm writing code in a Java-y way, and would like to know how to improve my C style.</p> <p>Also, are there any edge cases I am missing?</p>
[]
[ { "body": "<h1>Things you did well:</h1>\n\n<ul>\n<li><p>Overall the code looks very nice and well organized.</p></li>\n<li><p>You used comments well.</p></li>\n</ul>\n\n<h1>Things you could improve:</h1>\n\n<h3>Syntax:</h3>\n\n<ul>\n<li><p><code>typedef</code> your <code>struct</code>s.</p>\n\n<blockquote>\n<pre><code>struct Stack {\n int value;\n int is_empty;\n struct Stack *next;\n};\n</code></pre>\n</blockquote>\n\n<p>The <code>typedef</code> means you no longer have to write <code>struct</code> all over the place. That not only saves some space, it also can make the code cleaner since it provides a bit more abstraction.</p>\n\n<pre><code>typedef struct\n{\n int value;\n int is_empty;\n struct Stack *next;\n} Stack;\n</code></pre></li>\n<li><p>You can simplify your <code>NULL</code> checks.</p>\n\n<blockquote>\n<pre><code>if (head != NULL)\n</code></pre>\n</blockquote>\n\n<p>Since <code>NULL</code> is defined as <code>(void *)0</code>, we can treat is as a comparison to <code>0</code>, making the <code>!= NULL</code> a redundant check.</p>\n\n<pre><code>if (head)\n</code></pre></li>\n<li><p>If you don't take in any variables as parameters, you should declare them as <code>void</code>.</p>\n\n<pre><code>int main(void)\n</code></pre></li>\n</ul>\n\n<h3>Error handling:</h3>\n\n<ul>\n<li><p>Don't use <a href=\"http://www.cplusplus.com/reference/cstdlib/abort/\"><code>abort()</code></a>. The function raises the <code>SIGABRT</code> signal. This, if uncaught, causes the program to terminate returning a platform-dependent unsuccessful termination error code to the host environment. The program is terminated without destroying any object and without calling any of the functions passed to <code>atexit</code> or <code>at_quick_exit</code>. It would be much better to return an error indicator and have the calling function handle it.</p>\n\n<pre><code>return -1; // we have an error\n</code></pre></li>\n</ul>\n\n<h3>Memory usage:</h3>\n\n<ul>\n<li><p>You never <code>free()</code> your <code>init</code> value.</p>\n\n<blockquote>\n<pre><code>struct Stack *init = empty();\n\n// within empty()\nstruct Stack *head = malloc(sizeof(struct Stack *));\nreturn *head;\n</code></pre>\n</blockquote>\n\n<p>You should probably <code>free()</code> it before your program terminates. Failure to deallocate memory using <code>free()</code> leads to buildup of non-reusable memory, which is no longer used by the program. This wastes memory resources and can lead to allocation failures when these resources are exhausted.</p>\n\n<pre><code>free(init);\n</code></pre></li>\n</ul>\n\n<h3>Returning:</h3>\n\n<ul>\n<li><p>You don't <code>return</code> a value from <code>main()</code>, even though you state you do.</p>\n\n<blockquote>\n<pre><code>int main() {\n // no return value... no indication of successful exit\n}\n</code></pre>\n</blockquote>\n\n<p><code>Return</code>ing <code>0</code> is usually a typical indication of a successful exit.</p>\n\n<pre><code>return 0;\n</code></pre></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T04:27:21.857", "Id": "73823", "Score": "0", "body": "I also never free `head`, in `push`. Should I do that, and if so, where? EDIT: That may be a stupid question. Rather, should I be freeing memory in pop somewhere?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T04:29:52.847", "Id": "73824", "Score": "0", "body": "@dysruption You `return` the allocated memory (`head`) and assign it to `init`, so `init` is the only variable you have to `free()`. See [this answer](http://stackoverflow.com/a/1305785/1937270) for more clarification." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T04:31:03.840", "Id": "73825", "Score": "0", "body": "how about in pop? is there dead memory there?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T04:39:46.810", "Id": "73826", "Score": "0", "body": "@dysruption When you `typedef` your `struct`, and get rid of all the superfluous `struct` text, you will get a warning: \"Incompatible pointer types assigning to `struct Stack *` from `Stack *`\". I'll leave that up to you to fix though." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T04:50:19.760", "Id": "73827", "Score": "0", "body": "I did not receive that warning. Which line would have triggered it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T04:57:37.103", "Id": "73828", "Score": "1", "body": "@dysruption Lines 18 and 29. If compiling with GCC, enable compiler warnings with `-Wall`." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T02:58:20.710", "Id": "42835", "ParentId": "42834", "Score": "12" } }, { "body": "<p>Your calls to <code>malloc(sizeof(struct Stack *))</code> are wrong. That does <em>not</em> allocate enough memory to hold one stack element. Rather, it allocates enough memory to contain one pointer. You want <code>malloc(sizeof(struct Stack))</code>.</p>\n\n<p>You provide <code>push()</code> and <code>pop()</code>, but those two operations aren't enough to make a useful stack. At the minimum, you should also provide an <code>is_empty()</code> function. Otherwise, it wouldn't be fair to expect users to know when it is safe to pop an element. (They would have to keep track of the stack size themselves, which means that your data structure isn't doing its job.) Also consider adding a <code>peek()</code> function.</p>\n\n<p>I find that <code>empty()</code> is an odd name for a constructor. Something like <code>new_stack()</code> would be clearer.</p>\n\n<p>The stack, being a data structure, acts as a \"library\". To remain generic and reusable, library code should avoid having side effects. In particular,</p>\n\n<ul>\n<li>Calling <code>abort()</code> is antisocial. If you detect an error, then you should return an error code. As an alternative, an assertion might be acceptable. Another crappier alternative would be to not check at all, and just declare that popping an empty stack has undefined behaviour (i.e., it probably crashes). Calling <code>abort()</code> is odd in that you are expending effort to detect the error, but deliberately taking an action that violates expectations of how a library should behave.</li>\n<li>Don't print error messages. If you <em>must</em> print something, print to <code>stderr</code> to avoid contaminating the output.</li>\n</ul>\n\n<p>In this case, I think that returning an error code would make the interface too much of a pain to use. Using an assertion would be the way to go, in my opinion.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T01:18:15.250", "Id": "74006", "Score": "0", "body": "I appreciate it. In my pop function - do I need to free the memory of the initial Stack? Or does it get deallocated after there is no longer a reference to it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T02:36:21.617", "Id": "74010", "Score": "0", "body": "Nothing in C is automatic. Every pointer returned by `malloc()` must eventually be `free()`d. Otherwise, it's a memory leak. So yes, you have a memory leak in `pop()`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T04:43:37.270", "Id": "74016", "Score": "0", "body": "How does [this](http://pastebin.com/1tbz5kUL) look?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T07:14:08.660", "Id": "74027", "Score": "0", "body": "Better! I suggest that you pose it as a second question on Code Review. Mention that it is a follow-up to this question." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T11:53:21.443", "Id": "42859", "ParentId": "42834", "Score": "5" } } ]
{ "AcceptedAnswerId": "42835", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T02:43:07.830", "Id": "42834", "Score": "7", "Tags": [ "c", "stack", "integer" ], "Title": "Int stack implementation" }
42834
<p>Single app which listen to multiple RabbitMQ queue and process the message. This is working fine but not sure this implementation is right one or I am missing something.</p> <p>Implementation is inspired from this answer <a href="https://stackoverflow.com/a/21847234/37571">https://stackoverflow.com/a/21847234/37571</a></p> <pre><code>//Message subscriber implementation public class AuditSubscriber : IMessageSubscriber { public IList&lt;string&gt; SubscribedRouteKeys { get { return new List&lt;string&gt;() { "*.inceitive.attested.*" }; } } public async Task&lt;bool&gt; Process(Core.MessageInfo MessageItem) { //Start new task to process the message bool _ProcessedResult = await Task&lt;bool&gt;.Factory.StartNew(() =&gt; MessageProcesser(MessageItem), CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); return _ProcessedResult; } protected bool MessageProcesser(MessageInfo MessageItem) { Thread.Sleep(1000); //Acthual work return true; } } public class RabbitMQMessageConsumer : AbstractRabbitMQClient, IMessageConsumer { //Message consumer method, which will initiate number of tasks based upon the available subscriber. public void Consume(CancellationToken token) { //Start Rabbit MQ connection StartConnection(_ConnectionFactory.Get()); List&lt;Task&gt; tasks = new List&lt;Task&gt;(); foreach (SubscriberType subscriberType in (SubscriberType[])Enum.GetValues(typeof(SubscriberType))) { //Start listeing to all queues based upon the number of subscriber type availbale in the system Task task = Task.Factory.StartNew(() =&gt; ConsumeMessage(subscriberType, token), CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); tasks.Add(task); } Task.WhenAll(tasks); } //Listen to queue async Task ConsumeMessage(SubscriberType subscriberType, CancellationToken token) { try { //Get message subscriber which will process the message IMessageSubscriber _MessageSubscriber = _MessageSubscriberFactory.GetMessageSubscriber(subscriberType); using (IModel _ConsumerChannel = _Connection.CreateModel()) { _ConsumerChannel.ExchangeDeclare(_ExchangeProperties.Name, _ExchangeProperties.Type, _ExchangeProperties.Durable); string _QueueName = Enum.GetName(typeof(SubscriberType), subscriberType); _ConsumerChannel.QueueDeclare(_QueueName, _QueueProperties.Durable, _QueueProperties.Exclusive, _QueueProperties.AutoDelete, _QueueProperties.Arguments); foreach (string routeKey in _MessageSubscriber.SubscribedRouteKeys) { _ConsumerChannel.QueueBind(_QueueName, _ExchangeProperties.Name, routeKey); } var consumer = new QueueingBasicConsumer(_ConsumerChannel); _ConsumerChannel.BasicConsume(_QueueName, false, consumer); //Infinite loop to listen the queueu while (true) { if (token.IsCancellationRequested) { break; } try { BasicDeliverEventArgs eventArgs; //Get meesage or time out if (consumer.Queue.Dequeue(1000, out eventArgs)) { if (eventArgs != null) { MessageInfo _MessageItem = ByteArrayToMessageInfo(eventArgs.Body); //Message process by async method var messageProcesser = _MessageSubscriber.Process(_MessageItem); //Wait for result bool _MessageProcessed = await messageProcesser; if (_MessageProcessed) { _ConsumerChannel.BasicAck(eventArgs.DeliveryTag, false); } else { _ConsumerChannel.BasicNack(eventArgs.DeliveryTag, false, true); } } else { //connnection is dead } } } catch (EndOfStreamException ex) { Console.WriteLine(ex.Message); throw; } } } } catch (Exception ex) { Console.WriteLine(ex.Message); //TODO: Restart the task again throw; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T13:20:00.330", "Id": "73879", "Score": "0", "body": "Does it work? Why do you think it might not be right?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T14:21:51.753", "Id": "73889", "Score": "0", "body": "@svick Yes its work." } ]
[ { "body": "<pre><code>public async Task&lt;bool&gt; Process(Core.MessageInfo MessageItem)\n{\n //Start new task to process the message\n bool _ProcessedResult = await Task&lt;bool&gt;.Factory.StartNew(() =&gt; MessageProcesser(MessageItem), CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);\n\n return _ProcessedResult;\n}\n</code></pre>\n\n<ul>\n<li><p>That's a weird name for a local variable. The common naming is camelCase (e.g. <code>processedResult</code>). Underscores are sometimes used for fields, but certainly not for locals.</p></li>\n<li><p>The variable is actually unnecessary, you can just directly <code>return</code> the expression.</p></li>\n<li><p>If all <code>await</code>s in a method are <code>return await</code>s, then you don't need <code>await</code> at all, just return the <code>Task</code> directly, after removing <code>async</code> from the signature.</p></li>\n<li><p>Are you sure <code>TaskCreationOptions.LongRunning</code> is appropriate here? Its practical (and undocumented) effect is that it creates a new <code>Thread</code> to execute the <code>Task</code>. If you don't need that, just use <code>Task.Run()</code></p></li>\n</ul>\n\n<p>With all those changes the method would look like this:</p>\n\n<pre><code>public Task&lt;bool&gt; Process(Core.MessageInfo MessageItem)\n{\n return Task.Run(() =&gt; MessageProcesser(MessageItem));\n}\n</code></pre>\n\n<hr>\n\n<p>There are many empty lines in your code that I think are unnecessary. Empty lines are useful, but I think the way you're using them (after <code>{</code> or between two <code>}</code>) is just wasting space. And multiple empty lines are usually not useful either.</p>\n\n<hr>\n\n<pre><code>Task.WhenAll(tasks);\n</code></pre>\n\n<p><code>WhenAll()</code> <em>returns a <code>Task</code></em> that represents waiting for all the passed-in <code>Task</code>s, so ignoring its return value like this doesn't make any sense. Ideally, you should <code>await</code> the returned <code>Task</code>, but for that you need <code>async</code>. And <code>async void</code> methods shouldn't be used. So, if you need to wait for all the <code>Task</code>s here and you can't use <code>await</code>, you will have to block the thread by using <code>Task.WaitAll(tasks)</code>.</p>\n\n<hr>\n\n<pre><code>consumer.Queue.Dequeue(1000, out eventArgs)\n</code></pre>\n\n<p>This looks like a blocking method. Isn't there an asynchronous version available? If there is, you should probably use that instead.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-11T12:06:44.940", "Id": "76244", "Score": "0", "body": "Unfortunately \"consumer.Queue.Dequeue(1000, out eventArgs)\" do not have any async version." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-10T21:03:58.357", "Id": "43990", "ParentId": "42836", "Score": "6" } }, { "body": "<p>Very new to all the async await stuff so I could be completely off the mark here but I don't really follow why you are running the MessageProcessor in another new task.</p>\n\n<pre><code>//Wait for result \nbool _MessageProcessed = await messageProcesser;\n</code></pre>\n\n<p>You are already consuming messages in an asynchronous task. So it seems to me that your call to await on the messageProcessor is just going to block an existing asynchronous task. So you might as well just do that work in the current asynchronous task rather than submitting a new task? There is no caller of ConsumeMessage that benefits from this additional await.</p>\n\n<p>Like I said - very new to async await, so please 'school' me if I'm missing the point!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T22:52:18.943", "Id": "49024", "ParentId": "42836", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T03:05:31.157", "Id": "42836", "Score": "8", "Tags": [ "c#", "task-parallel-library", "async-await" ], "Title": "Listen to multiple RabbitMQ queue by task and process the message" }
42836
<p>If this is my class:</p> <pre><code>class Something { UUID id; // Other members } </code></pre> <p>Given a <code>List&lt;Something&gt; things</code> and I want to get a <code>List&lt;UUID&gt; ids</code>, this is what I usually do:</p> <pre><code>List&lt;UUID&gt; ids = new ArrayList&lt;UUID&gt; for(Something thing : things) { ids.add(thing.getId()); } return ids; </code></pre> <p>Is there a more elegant way of doing this in <strong>Java 6</strong>?</p> <p>[I googled for this pattern, however, didn't find much as I think I lacked the right keywords]</p>
[]
[ { "body": "<p>When I have encountered this type of problem, it typically involves creating some ugly code in your method to do that iteration. In essense, there is no way to do things any differently, you <em>have</em> to iterate, and collect the UUID's (but, you could wait for Java8 and do lambdas ..).</p>\n\n<p>But, there is no reason why you have to do it outside of the <code>Something</code> class. A trick you can do which keeps like-code together, is to put a static method on <code>Something</code>, which does:</p>\n\n<pre><code>public static final List&lt;UUID&gt; getUUIDs(Iterable&lt;Something&gt; somethings) {\n List&lt;UUID&gt; ids = new ArrayList&lt;UUID&gt;();\n for(Something thing : somethings) {\n ids.add(thing.getId());\n }\n return ids;\n}\n</code></pre>\n\n<p>Now that code is stashed away somewhere useful, and when you need it you can:</p>\n\n<pre><code>for (UUID uuid : Something.getUUIDs(things) {\n ... do something ....\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T08:01:17.860", "Id": "73838", "Score": "0", "body": "Yes, once the world (Read : my org) is ready to adopt Java 8, better code will be seen." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T06:53:36.403", "Id": "42844", "ParentId": "42842", "Score": "1" } }, { "body": "<p>You can do it with Guava's <code>Function</code> and <code>Lists</code> (<a href=\"https://code.google.com/p/guava-libraries/wiki/FunctionalExplained\" rel=\"nofollow\">Functional idioms in Guava, explained</a>):</p>\n\n<pre><code>Function&lt;Something, UUID&gt; getIdFunction = new Function&lt;Something, UUID&gt;() {\n public UUID apply(Something input) {\n return input.getId();\n }\n};\n\nList&lt;UUID&gt; ids2 = Lists.transform(things, getIdFunction);\n</code></pre>\n\n<p>(If you're unable to include a 3rd party library to your project for any reason you still can copy the code of relevant classes or create your own implementation with the same pattern.)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T07:23:06.330", "Id": "42845", "ParentId": "42842", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T06:33:27.567", "Id": "42842", "Score": "3", "Tags": [ "java", "lambda" ], "Title": "Elegant way of making a List of an attribute from a list of objects containing that attribute" }
42842
<p>I wrote a simple cython script to optimize the collections.Counter of a dictionary counter and the python zip implementation (the main input is a list of tuples). Is there a way to speed it up?</p> <pre><code>%%cython --annotate cimport cython import numpy as np cimport numpy as np from collections import defaultdict @cython.boundscheck(False) @cython.wraparound(False) def uniqueCounterListCython(list x not None): cdef: Py_ssize_t i,n n = len(x) dx = defaultdict(int) for i from 0 &lt;= i &lt; n: dx[x[i]] += 1 return dx @cython.boundscheck(False) @cython.wraparound(False) def zipCython(np.ndarray[long,ndim=1] x1 not None, np.ndarray[long,ndim=1] x2 not None): cdef: Py_ssize_t i,n n = x1.shape[0] l=[] for i from 0 &lt;= i &lt; n: l.append(((x1[i],x2[i]))) return l </code></pre> <p>Sample input - </p> <pre><code>uniqueCounterListCython(zipCython(np.random.randint(0,3,200000),np.random.randint(0,3,200000))) </code></pre> <p><img src="https://i.stack.imgur.com/fLDLo.png" alt="pic1"> <img src="https://i.stack.imgur.com/MSskz.png" alt="pic2"></p> <p>EDIT: Found a kind of trivial way to speed things up - just merge the two functions:</p> <pre><code>@cython.boundscheck(False) @cython.wraparound(False) def uniqueCounterListCythonWithZip(np.ndarray[long,ndim=1] x1 not None, np.ndarray[long,ndim=1] x2 not None): cdef: Py_ssize_t i,n n = x1.shape[0] dx = defaultdict(int) for i from 0 &lt;= i &lt; n: dx[((x1[i],x2[i]))] += 1 return dx </code></pre> <p>Any more suggestions? </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T08:25:57.217", "Id": "73841", "Score": "0", "body": "Welcome to Code Review! Could you please run a profiler on your code to see what's slow? See the [Cython profiling tutorial](http://docs.cython.org/src/tutorial/profiling_tutorial.html). Thanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T11:51:19.190", "Id": "73866", "Score": "0", "body": "I've added a profiling snapshot" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T13:21:39.993", "Id": "73881", "Score": "0", "body": "this is not really useful, you forgot `# cython: profile=True` as explained in the tutorial. We want to know how much time is spent in functions called by Cython code. Thanks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T14:09:40.197", "Id": "73887", "Score": "0", "body": "I've followed the tutorial and inserted # cython: profile=True . What am I missing?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T14:23:26.240", "Id": "73890", "Score": "0", "body": "Not sure. It's no longer \"magic\" so maybe you can't get much better results than that. Is it still too slow for your needs?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T14:26:32.180", "Id": "73891", "Score": "0", "body": "Yes - it is still too slow.." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T21:27:38.607", "Id": "73952", "Score": "0", "body": "Can you explain what you are trying to do here?" } ]
[ { "body": "<p>You don't give us much context for this problem, so it's unclear to me exactly what you are trying to achieve. But in your example, you have a pair of NumPy arrays containing integers in the range 0–2, and you seem to want to count the number of occurrences of each pair of values.</p>\n\n<p>So I suggest encoding pairs of integers in the range 0–2 into a single integer in the range 0–8, using <a href=\"http://docs.scipy.org/doc/numpy/reference/generated/numpy.bincount.html\" rel=\"nofollow\"><code>numpy.bincount</code></a> to do the counting, and then using <a href=\"http://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html\" rel=\"nofollow\"><code>numpy.reshape</code></a> to decode the result, like this:</p>\n\n<pre><code>&gt;&gt;&gt; import numpy as np\n&gt;&gt;&gt; x, y = np.random.randint(0,3,200000), np.random.randint(0,3,200000)\n&gt;&gt;&gt; counts = np.bincount(x * 3 + y).reshape((3, 3))\n&gt;&gt;&gt; counts\narray([[22282, 22093, 22247],\n [22084, 22295, 22396],\n [22012, 22243, 22348]])\n</code></pre>\n\n<p>A quick check that I got the encoding/decoding right:</p>\n\n<pre><code>&gt;&gt;&gt; counts[0,2] == np.count_nonzero((x == 0) &amp; (y == 2))\nTrue\n</code></pre>\n\n<p>This runs much faster than the code in your question (assuming I have interpreted your profile screenshots correctly):</p>\n\n<pre><code>&gt;&gt;&gt; from timeit import timeit\n&gt;&gt;&gt; timeit(lambda:np.bincount(x * 3 + y).reshape((3, 3)), number=1000)\n2.7519797360000666\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T23:09:46.190", "Id": "73973", "Score": "0", "body": "Sorry for not properly defining the problem. This was the exact intention. Thank you!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T21:23:38.490", "Id": "42901", "ParentId": "42846", "Score": "4" } } ]
{ "AcceptedAnswerId": "42901", "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T07:26:47.283", "Id": "42846", "Score": "3", "Tags": [ "python", "optimization", "numpy", "cython" ], "Title": "Speedup cython dictionary counter" }
42846
<p><a href="http://oj.leetcode.com/problems/binary-tree-level-order-traversal/" rel="nofollow">Level traverse binary tree question</a>:</p> <blockquote> <p>Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).</p> <p>For example:</p> <p>Given binary tree <code>{3,9,20,#,#,15,7}</code>,</p> <pre class="lang-none prettyprint-override"><code> 3 / \ 9 20 / \ 15 7 </code></pre> <p>return its level order traversal as:</p> <pre class="lang-none prettyprint-override"><code>[ [3], [9,20], [15,7] ] </code></pre> </blockquote> <p>The problem is pretty common level order traverse a binary tree but break each level into single array.</p> <p>I implemented mine: I've designed a few test cases, but when I submit it to the OJ, it just complains about a runtime error. I don't quite understand where the problem is.</p> <p><a href="http://ideone.com/heL0Jj" rel="nofollow">Full Sample</a></p> <pre class="lang-c++ prettyprint-override"><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;cstdio&gt; #include &lt;algorithm&gt; using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { vector&lt;TreeNode*&gt; headlist; public: vector&lt;vector&lt;int&gt; &gt; levelOrder(TreeNode *root) { vector&lt;vector&lt;int&gt; &gt; result; if( root ) { DFSVisit(root,0); size_t n=headlist.size(); result.resize(n); for( size_t i=0; i&lt;n; i++ ){ TreeNode* h = headlist[i]; while( (h ) ){ result[i].push_back( h-&gt;val ); h = h-&gt;left; } reverse( result[i].begin(), result[i].end() ); } } return result; } void DFSVisit( TreeNode* n, size_t level ){ //cerr &lt;&lt; "DFSVISIT" &lt;&lt; endl; TreeNode* l = n-&gt;left; TreeNode* r = n-&gt;right; AppendNodeToHeadlist( n, level ); if( l ) DFSVisit( l, level+1); if( r ) DFSVisit( r, level+1); } void AppendNodeToHeadlist( TreeNode* n, size_t l ){ //cerr &lt;&lt; "DFSVISIT" &lt;&lt; endl; //printf( "healist size %lu \n", headlist.size() ); //printf( "node to append %d \n", n-&gt;val ); if( headlist.size() &lt; l+1 ){ headlist.push_back(NULL); headlist[l] = n; n-&gt;left = NULL; } else{ TreeNode* h = headlist[l]; h-&gt;right = n; n-&gt;left = h; headlist[l]=n; //printf( "chain[%lu]: %d-&gt;%d\n",l, h-&gt;val, n-&gt;val ); } } }; void print_result( vector&lt;vector&lt;int&gt; &gt;&amp; r ){ //cerr &lt;&lt; "DFSVISIT" &lt;&lt; endl; for( size_t i=0; i&lt;r.size(); i++ ){ for( size_t j=0; j&lt;r[i].size(); j++ ){ printf( "%d ", r[i][j] ); } printf( "\n" ); } printf( "\n" ); } void test_solution0(){ Solution s; auto r = s.levelOrder(NULL); vector&lt;vector&lt;int&gt; &gt; e; if ( r == e ){ printf( "CASE0 PASSED!\n" ); } else{ printf( "CASE0 FAILED!\n" ); printf( "===Actual Result ===\n"); print_result( r ); printf( "===Expected Result ===\n"); print_result( e ); } } void test_solution1(){ TreeNode n1(1),n2(2),n3(3),n4(4),n5(5); n1.left = &amp;n2; n1.right = &amp;n3; n3.left = &amp;n4; n3.right = &amp;n5; Solution s; auto r = s.levelOrder(&amp;n1); vector&lt;vector&lt;int&gt; &gt; e = { {1}, {2,3}, {4,5} }; if ( r == e ){ printf( "CASE1 PASSED!\n" ); } else{ printf( "CASE1 FAILED!\n" ); printf( "===Actual Result ===\n"); print_result( r ); printf( "===Expected Result ===\n"); print_result( e ); } } void test_solution2(){ TreeNode n1(1),n2(2),n3(3),n4(4),n5(5), n6(6); n1.left = &amp;n2; n1.right = &amp;n3; n3.left = &amp;n4; n3.right = &amp;n5; n2.left = &amp;n6; Solution s; auto r = s.levelOrder(&amp;n1); vector&lt;vector&lt;int&gt; &gt; e = { {1}, {2,3}, {6,4,5} }; if ( r == e ){ printf( "CASE2 PASSED!\n" ); } else{ printf( "CASE2 FAILED!\n" ); printf( "===Actual Result ===\n"); print_result( r ); printf( "===Expected Result ===\n"); print_result( e ); } } int main(){ test_solution0(); test_solution1(); test_solution2(); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-27T06:04:48.547", "Id": "89557", "Score": "0", "body": "first of all it is not broken, it just didn't deal with boundary condition correctly. secondly this code is already written, you can run through the `full sample` link." } ]
[ { "body": "<p>I don't see why \"DFS\" should appear in your code. The challenge is to perform a breadth-first traversal. The typical way to implement a breadth-first traversal is to use a queue.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-27T06:06:52.130", "Id": "89559", "Score": "0", "body": "you are correct, but I don't see issue implementing this way as well." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-27T03:35:23.400", "Id": "51801", "ParentId": "42848", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T08:31:07.437", "Id": "42848", "Score": "2", "Tags": [ "c++", "algorithm", "c++11", "tree", "programming-challenge" ], "Title": "Level-traverse a binary tree" }
42848
<p>I have this portion of code and I would like to know if I did it right, what changes could be done to optimize and make it better, and if I used the all the tags the right way. For the moment, the CSS part is not really done since I have few bugs on the height of each column.</p> <pre><code>&lt;div class="shop-grid"&gt; &lt;div class="container"&gt; &lt;section class="col-group"&gt; &lt;article class="col-3"&gt; &lt;div class="item-container"&gt; &lt;figure&gt; &lt;div class="container-thumb-screen"&gt;&lt;span class="thumb-screen"&gt;&lt;/span&gt;&lt;/div&gt; &lt;img src="../public/uploads/productPictures/thumbnails/" alt=""&gt; &lt;figcaption class="product-name"&gt; &lt;h2&gt;&lt;a href=""&gt;Hartie Copiator A4 Artist &lt;/a&gt;&lt;/h2&gt; &lt;/figcaption&gt; &lt;/figure&gt; &lt;div class="item-actions"&gt; &lt;a href="" class="button"&gt;&lt;i class="icon-heart"&gt;&lt;/i&gt;&lt;/a&gt; &lt;a href="" class="button"&gt;&lt;i class="icon-shopping-cart"&gt;&lt;/i&gt;&lt;/a&gt; &lt;a href="" class="button"&gt;&lt;i class="icon-double-angle-right"&gt;&lt;/i&gt;&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/article&gt; &lt;article class="col-3"&gt; &lt;div class="item-container"&gt; &lt;figure&gt; &lt;div class="container-thumb-screen"&gt;&lt;span class="thumb-screen"&gt;&lt;/span&gt;&lt;/div&gt; &lt;img src="../public/uploads/productPictures/thumbnails/" alt=""&gt; &lt;figcaption class="product-name"&gt; &lt;h2&gt;&lt;a href=""&gt;Hartie Copiator A4 Xerox Bussines&lt;/a&gt;&lt;/h2&gt; &lt;/figcaption&gt; &lt;/figure&gt; &lt;div class="item-actions"&gt; &lt;a href="" class="button"&gt;&lt;i class="icon-heart"&gt;&lt;/i&gt;&lt;/a&gt; &lt;a href="" class="button"&gt;&lt;i class="icon-shopping-cart"&gt;&lt;/i&gt;&lt;/a&gt; &lt;a href="" class="button"&gt;&lt;i class="icon-double-angle-right"&gt;&lt;/i&gt;&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/article&gt; &lt;article class="col-3"&gt; &lt;div class="item-container"&gt; &lt;figure&gt; &lt;div class="container-thumb-screen"&gt;&lt;span class="thumb-screen"&gt;&lt;/span&gt;&lt;/div&gt; &lt;img src="../public/uploads/productPictures/thumbnails/" alt=""&gt; &lt;figcaption class="product-name"&gt; &lt;h2&gt;&lt;a href=""&gt;Hartie Copiator A3 Xerox Bussines&lt;/a&gt;&lt;/h2&gt; &lt;/figcaption&gt; &lt;/figure&gt; &lt;div class="item-actions"&gt; &lt;a href="" class="button"&gt;&lt;i class="icon-heart"&gt;&lt;/i&gt;&lt;/a&gt; &lt;a href="" class="button"&gt;&lt;i class="icon-shopping-cart"&gt;&lt;/i&gt;&lt;/a&gt; &lt;a href="" class="button"&gt;&lt;i class="icon-double-angle-right"&gt;&lt;/i&gt;&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/article&gt; &lt;article class="col-3"&gt; &lt;div class="item-container"&gt; &lt;figure&gt; &lt;div class="container-thumb-screen"&gt;&lt;span class="thumb-screen"&gt;&lt;/span&gt;&lt;/div&gt; &lt;img src="../public/uploads/productPictures/thumbnails/" alt=""&gt; &lt;figcaption class="product-name"&gt; &lt;h2&gt;&lt;a href=""&gt;Hartie Copiator A3 Maestro&lt;/a&gt;&lt;/h2&gt; &lt;/figcaption&gt; &lt;/figure&gt; &lt;div class="item-actions"&gt; &lt;a href="" class="button"&gt;&lt;i class="icon-heart"&gt;&lt;/i&gt;&lt;/a&gt; &lt;a href="" class="button"&gt;&lt;i class="icon-shopping-cart"&gt;&lt;/i&gt;&lt;/a&gt; &lt;a href="" class="button"&gt;&lt;i class="icon-double-angle-right"&gt;&lt;/i&gt;&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/article&gt; &lt;/section&gt; &lt;/div&gt; &lt;/div&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T15:23:58.293", "Id": "73903", "Score": "0", "body": "Having empty `alt`s is a code smell." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T06:47:55.480", "Id": "74021", "Score": "1", "body": "well i have an empty alt because i posted the html version didn't include the template vars that will populate with data in places where is needed." } ]
[ { "body": "<p>Don’t use <code>i</code> for font icons. Use <code>span</code> instead (like you did with <code>.thumb-screen</code>). The <a href=\"https://codereview.stackexchange.com/a/41124/16414\"><code>i</code> element is not appropriate</a> for such purposes.</p>\n\n<p>In any case, you should offer alternative content for user-agents that have no CSS support. I.e., your links in <code>.item-actions</code> couldn’t be accessed by, for example, screen reader users. So add content and optionally hide it visually.</p>\n\n<p>Then you might also consider using an <code>ul</code> for the three link actions.</p>\n\n<p>The <code>alt</code> attribute for <code>img</code> should have content, unless the image is only decorative (but then you should better use CSS instead).</p>\n\n<p>No need for <code>h2</code> in <code>figcaption</code>. It’s already defined to be the caption (or \"title\" if you will) for this <code>figure</code>. It also doesn’t play a role in the document outline, because <code>figure</code> is a sectioning root. So if you want to provide a heading for the <code>article</code>, you need to place it outside of <code>figure</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T09:18:31.793", "Id": "74031", "Score": "0", "body": "i will do the changes and come back with a new version :-)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T07:19:03.940", "Id": "42936", "ParentId": "42849", "Score": "3" } } ]
{ "AcceptedAnswerId": "42936", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T08:46:09.550", "Id": "42849", "Score": "4", "Tags": [ "html", "html5" ], "Title": "Product grid for a online catalog" }
42849
<p>In my code I have a base type which is OnlinePaymentTransaction:</p> <pre><code>public abstract class OnlinePaymentTransaction { public abstract void Complete( PaymentGatewayCallbackArgs args ); } </code></pre> <p>The problem I am having is that each class that inherits from this base class require different dependency's in the complete method. Currently I have just added the dependency's as extra parameters to the complete method which doesn't seem right. For example my base class is now like this. </p> <pre><code>public abstract class OnlinePaymentTransaction { public abstract void Complete( Dependency1 dep1, Dependency2 dep2, PaymentGatewayCallbackArgs args ); } </code></pre> <p>I cannot inject the dependency's in the constructor as the OnlinePaymentTransactions are retrieved from using nhibernate.</p> <p>What would you recommend because I don't like using ServiceLocator as it hides the dependency and also makes it harder to test. An suggestions would be greatly appreciated.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T11:52:25.187", "Id": "73867", "Score": "1", "body": "What does complete do that means its a method on the model? ie. Why isn't there a separate logic object that makes the decision/s on how the model has changed?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T20:20:57.097", "Id": "73928", "Score": "0", "body": "I am trying to follow the TellDontAsk coding practice and the OnlinePaymentTransaction is the only object that knows how to complete the transaction." } ]
[ { "body": "<p>Darn, at first glance this looked like a simple solution but you ruled out constructor injection.</p>\n\n<p>The only suggestion I can come up with is to have a class that inherits from the same interface, DOES have the constructor injection is built up and added to the main object as a composite object fed in through a set only Property, maybe some kind of flagged function call like </p>\n\n<pre><code>Init(TheThingWithThePropertiesInAConstructorInitializer);\n</code></pre>\n\n<p>Then in your Complete function you could throw an exception if <code>HasBeenInitialized</code> is false. </p>\n\n<p>You would then have access to your composite different parameters in your complete method while keeping your abstraction, </p>\n\n<p>albeit with the caveat that your initialization is now a two stage process, that requires an initialization call;</p>\n\n<p>*<strong>ps</strong>, <em>no I do not propose that to be an actual argument name!</em></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T20:14:17.517", "Id": "73925", "Score": "0", "body": "Do you think there is any other way than this?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T11:14:41.643", "Id": "74040", "Score": "1", "body": "@JakeRote can't think of any. MAt's Mug is right up above.The problem stems from the overall design. your dependency injector should be injecting implementations of your creators and factories not your direct objects. That would leave your object free to use their constructor params and be initialized correctly. The above method is the only one I can think of that will keep your base design but yeah, it really should be more IOC with TransactionFactories being what is injected IMO." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T10:47:10.603", "Id": "42853", "ParentId": "42851", "Score": "3" } }, { "body": "<blockquote>\n <p><em>I cannot inject the dependency's in the constructor as the OnlinePaymentTransactions are retrieved from using nhibernate.</em></p>\n</blockquote>\n\n<p>There's your problem. Your <code>OnlinePaymentTransaction</code> class is/should-be a POCO whose job is to convey data. The <code>Complete()</code> method doesn't belong on that type, it's breaking SRP and making your life much harder than it needs to be.</p>\n\n<p>I'd suggest to introduce another type, call it <code>OnlinePaymentTransactionProcessor</code> or whatever - <em>that type</em> will take the dependencies in its constructor, and have a <code>Complete</code> method that takes an <code>OnlinePaymentTransaction</code> instance.</p>\n\n<p>Kudos for striving to avoid a <em>Service Locator</em> :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T20:27:23.280", "Id": "73932", "Score": "0", "body": "I wad thinking of creating a processor but was just thinking that would need some kind of OnlinePaymentTransactionProcessorProvider. If i didnt have a provider how would I get a processor?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T20:31:02.057", "Id": "73933", "Score": "0", "body": "Where *Provider* is an abstract factory? There's not a lot of code in your post, to see how the pieces would fit together. My answer essentially boils down to GraemeBradbury's comment: you're turning your *model* into something more than just a *model* - taking that functionality out into its own type should make it easier to figure out :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T10:04:27.000", "Id": "74035", "Score": "0", "body": "Does this not break the TellDontAsk code practice as you have to ask the OnlinePaymentTransaction how to get the information to complete the online payment transaction." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T13:51:12.300", "Id": "74058", "Score": "0", "body": "@JakeRote the reason it doesn't break the practice is that you're not asking anything. You tell the repo to get data X. You then tell the factory to create a transaction Y from data X. You then tell the transaction Y to complete using CallbackArgs Z." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T20:22:17.890", "Id": "42892", "ParentId": "42851", "Score": "5" } } ]
{ "AcceptedAnswerId": "42892", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T09:38:42.067", "Id": "42851", "Score": "3", "Tags": [ "c#", "dependency-injection" ], "Title": "Dependency on overridden method" }
42851
<p>I am trying to cache the entirety of streams from Twitch.TV public API with the following code. It is successful but takes almost a full minute to execute so I am wondering if it's my code or just the speed of the API delivery. In any case, because it is my first PHP script (and really, I'm new in general), I am certain there are logical missteps and performance crushing flows and I would appreciate some review! </p> <p>The function <code>buildPages()</code> is mainly what is in question for this post. </p> <p>The data is always returned as json and I dump it all to disk for local testing. Suggestions on how to implement an accelerator for this collection are welcomed since I've never played with one before. APC or Memcache(d)? I have a lot of reading to do.. </p> <p>Also, I am not certain why the lines</p> <pre><code>$length = count($page-&gt;streams); $length = count($page['streams']); </code></pre> <p>had to be written as such. <code>stdClass</code> Object versus <code>ArrayAccess</code>? I don't really understand why I would get errors when trying to use the same accessor in the case of my code. Is <code>$page</code> not always an associative array created from the JSON data?</p> <pre><code>&lt;?php $base = 'https://api.twitch.tv/kraken/'; $thatlist = array( 'games'=&gt; array( 'url'=&gt;'games/top', 'params'=&gt; array( 'limit'=&gt;100, 'offset'=&gt;0 ) ), 'featured'=&gt;array( 'url'=&gt;'streams/featured', 'params'=&gt;array( 'limit'=&gt;100, 'offset'=&gt;0 ) ), 'summary'=&gt;array( 'url'=&gt;'streams/summary', 'params'=&gt;array( 'limit'=&gt;100, 'offset'=&gt;0 ) ), 'teams'=&gt;array( 'url'=&gt;'teams', 'params'=&gt;array( 'limit'=&gt;100, 'offset'=&gt;0 ) ) ); foreach($thatlist as $key =&gt; $val) { $fullurl = $base . $val['url']; foreach($val['params'] as $foo =&gt; $bar){ $fullurl .= '?' . $foo . '=' . $bar; } $quicklist[$key] = json_decode(file_get_contents($fullurl), true); } function buildPages() { $streams = array(); $offset = 0; $page = json_decode(file_get_contents("https://api.twitch.tv/kraken/streams?offset=".$offset."&amp;limit=100", true)); $length = count($page-&gt;streams); array_push($streams, $page); // request always returns 100 items unless at the end of live data while($length = 100) { $index = count($streams); $offset = $index * 100; $page = json_decode(file_get_contents("https://api.twitch.tv/kraken/streams?offset=".$offset.'&amp;limit=100'), true); $length = count($page['streams']); echo "Index: ".$index."&lt;br/&gt;"; echo "Length: ".$length."&lt;br/&gt;"; array_push($streams, $page); } var_dump($streams); $sd = fopen('streams-dump.json', 'w'); fwrite($sd, json_encode($streams)); fclose($sd); } $qld= fopen('quicklist-dump.json', 'w'); fwrite($qld, json_encode($quicklist)); fclose($qld); buildPages(); ?&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T10:19:00.963", "Id": "73856", "Score": "0", "body": "I believe I also need to consider the fact that, while my script is collecting data, the live data might update and my universe of discord might become fragmented with duplicates or missing entries. If `$offset = 2500` and a few streams back from `$offset = 300` drop, won't it screw up everything?" } ]
[ { "body": "<p>At a glance I'd be almost certain that the network requests are your bottleneck here.</p>\n\n<p>If you think of the difference between some code interpreted and run locally vs instantiating a network connection, sending the request, waiting for their servers to run <em>their</em> code and the network latency to respond I think it's safe to say the network time is going to be the bottleneck. Particularly when you consider you're doing hundreds of network connections.</p>\n\n<p>To speed this up I'd say Memcached is your best option. APC is also pretty useful, but not specifically for this. The general idea would be to check if you have cached results and if not generate the data you need and stick it in memcached and return the data. Then, in separate code, take that data and format it as required.</p>\n\n<p>Roughly speaking:</p>\n\n<pre><code>if (Cache-&gt;check('key-to-your-data'))\n{\n $twitchTvData = Cache-&gt;get('key-to-your-data');\n}\nelse\n{\n $twitchTvScraper = new TwitchTvScraper();\n $twitchTvData = $twitchTvScraper-&gt;scrape();\n Cache-&gt;set('key-to-your-data', $twitchTvData);\n}\n\necho PageBuilder-&gt;buildFoo($twitchTvData);\n</code></pre>\n\n<p>In this example I've split out the caching, scraping of content and building of pages into separate classes. Having these all in the one place is a recipe for disaster/embarrassingly silly bugs.</p>\n\n<p>Also, it's worth noting that hitting someone's API repeatedly like this is usually considered bad form and if they're monitoring for such activity you could get blocked. It might be worth looking into a package that can scrape pages with a rate limit. I'm sure there are a few out there. If you don't need the data refreshed often you could just use <code>wget</code> and read the files from a directory locally.</p>\n\n<p>Finally; it's fine to stick some html together when you're learning a new language but in practice it isn't the way to go. Typically you use an off the shelf framework that can build HTML from templates. Something like, Zend, Laravel etc. (<a href=\"http://www.phpframeworks.com/\" rel=\"nofollow\">http://www.phpframeworks.com/</a> for more).</p>\n\n<p>Having said all that, if you're just learning to code, <em>don't</em> take this all on at once! Take it piece by piece and <a href=\"http://git-scm.com/\" rel=\"nofollow\">save early, save often</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T14:12:47.540", "Id": "73888", "Score": "0", "body": "I like where your `save early, save often` links to :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T22:59:23.597", "Id": "73968", "Score": "0", "body": "Thank you for the tips on caching behaviors. I'm familiar with the basic concept of checking for the cache before requesting updates but I appreciate the coded example for logical purposes. The links and other tips (Git!) are solid as well. \n\nA friend was able to help rewrite my function and I've learned a lot in the process. I'll be putting your information to use soon. :]" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T12:54:41.200", "Id": "42866", "ParentId": "42852", "Score": "1" } }, { "body": "<p>I got in touch with a friend who helped me smash out some of the bad parts (read: all of it). Here is the modified function which is much cleaner and more logical. Works like a charm:</p>\n\n<pre><code>function buildPages() {\n\n $streams = array();\n $offset = 0;\n $url = 'https://api.twitch.tv/kraken/streams?limit=100&amp;offset=';\n\n do {\n $page = file_get_contents($url . $offset);\n\n if(empty($page))\n throw new Exception('Error loading URL: ' . $url . $offset);\n\n $pageData = json_decode($page, true);\n $numStreams = count($pageData['streams']);\n $offset += $numStreams;\n $streams[] = $pageData;\n\n } while($numStreams &gt;= 100);\n\n var_dump($streams);\n\n $sd = fopen('streams-dump.json', 'w');\n fwrite($sd, json_encode($streams));\n fclose($sd);\n\n}\n</code></pre>\n\n<p>Now I have to think of a way to compare the contents of the current page and previous page to eliminate any duplicate entries being caused by the behavior of the API delivery regarding <code>offset</code> shifting as I crawl the pages. </p>\n\n<p>Then I'm ready for memcache and live testing, I think. :D</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T22:57:58.150", "Id": "42907", "ParentId": "42852", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T10:16:54.313", "Id": "42852", "Score": "0", "Tags": [ "php" ], "Title": "Build a local cache of all streams from Twitch.TV API" }
42852
<p>I have about 11 singleton-esque classes divided over a dozen files:</p> <p>the first file is one that gathers all singleton definitions and makes them callable on a request scope:</p> <pre><code>public sealed partial class ExpertiseverslagEngine { readonly IOrganizationService _oService; readonly XrmServiceContext _oServiceContext; static readonly object Padlock = new object(); ExpertiseverslagEngine() { _oService = CrmConnector.GetOrganization(); _oServiceContext = new XrmServiceContext(_oService); } public static ExpertiseverslagEngine Instance { get { lock (Padlock) { if (UnitOfWorkHelper.CurrentDataStore["ExpertiseverslagEngine"] == null) { UnitOfWorkHelper.CurrentDataStore["ExpertiseverslagEngine"] = new ExpertiseverslagEngine(); } return (ExpertiseverslagEngine)UnitOfWorkHelper.CurrentDataStore["ExpertiseverslagEngine"]; } } } } public sealed partial class OnderhoudEngine { readonly IOrganizationService _oService; readonly XrmServiceContext _oServiceContext; static readonly object Padlock = new object(); OnderhoudEngine() { _oService = CrmConnector.GetOrganization(); _oServiceContext = new XrmServiceContext(_oService); } public static OnderhoudEngine Instance { get { lock (Padlock) { if (UnitOfWorkHelper.CurrentDataStore["OnderhoudEngine"] == null) { UnitOfWorkHelper.CurrentDataStore["OnderhoudEngine"] = new OnderhoudEngine(); } return (OnderhoudEngine)UnitOfWorkHelper.CurrentDataStore["OnderhoudEngine"]; } } } } </code></pre> <p>The other 11 files are all but 1 built in this manner:</p> <pre><code>public partial class ExpertiseverslagEngine { public List&lt;slfn_expertiseverslag&gt; Retrieve_Active() { return (from exp in _oServiceContext.slfn_expertiseverslagSet select exp).ToList(); } public slfn_expertiseverslag Retrieve(Guid expertiseverslagId) { slfn_expertiseverslag expertiseverslag = (from exp in _oServiceContext.slfn_expertiseverslagSet where exp.Id == expertiseverslagId select exp).First(); return expertiseverslag; } public List&lt;slfn_schadebeschrijvingwagen&gt; Retrieve_Schade(Guid expertiseverslagGuid) { List&lt;slfn_schadebeschrijvingwagen&gt; beschrijvingen = (from sbw in _oServiceContext.slfn_schadebeschrijvingwagenSet where sbw.slfn_Expertiseverslag.Id == expertiseverslagGuid select sbw).ToList(); return beschrijvingen; } public String Update(slfn_expertiseverslag oexpertiseverslag) { string status; try { _oServiceContext.UpdateObject(oexpertiseverslag); _oServiceContext.SaveChanges(); status = "Update gelukt"; } catch (Exception e) { status = String.Format("Update mislukt, foutboodschap: {0}", e.Message); } return status; } public string Create(slfn_expertiseverslag expertiseverslag) { string status; try { _oServiceContext.AddObject(expertiseverslag); _oServiceContext.SaveChanges(); status = "Aanmaken gelukt"; } catch (Exception e) { status = String.Format("Update mislukt, foutboodschap: {0}", e.Message); } return status; } } </code></pre> <p>Another example of one of these classes:</p> <pre><code>public partial class AssetEngine { public List&lt;slfn_asset&gt; Retrieve_Active() { return (from asset in _oServiceContext.slfn_assetSet select asset).ToList(); } public slfn_asset Retrieve(Guid assetId) { slfn_asset oAsset = (from asset in _oServiceContext.slfn_assetSet where asset.Id == assetId select asset).First(); return oAsset; } internal List&lt;slfn_gebruikershistoriekasset&gt; Retrieve_Geschiedenis(Guid assetId) { return (from gha in _oServiceContext.slfn_gebruikershistoriekassetSet where gha.slfn_Asset.Id == assetId select gha).ToList(); } public string Update(slfn_asset oAsset) { string status; try { _oServiceContext.UpdateObject(oAsset); _oServiceContext.SaveChanges(); status = "Update gelukt."; } catch (Exception e) { status = String.Format("Update mislukt, Foutmelding: {0}", e.Message); } return status; } public string Create(slfn_asset asset) { string status; try { _oServiceContext.AddObject(asset); _oServiceContext.SaveChanges(); status = "Aanmaken gelukt."; } catch (Exception e) { status = String.Format("Aanmaken mislukt, Foutmelding: {0}.", e.Message); } return status; } } </code></pre> <p>The final one is for a different purpose and looks like this:</p> <pre><code>public sealed partial class OptionsetEngine { public List&lt;OptionMetadata&gt; GetGlobalOptionSet(string optionsetName) { // Use the RetrieveOptionSetRequest message to retrieve // a global option set by it's name. RetrieveOptionSetRequest retrieveOptionSetRequest = new RetrieveOptionSetRequest { Name = optionsetName }; // Execute the request. RetrieveOptionSetResponse retrieveOptionSetResponse = (RetrieveOptionSetResponse)_oService.Execute( retrieveOptionSetRequest); // Access the retrieved OptionSetMetadata. OptionSetMetadata retrievedOptionSetMetadata = (OptionSetMetadata)retrieveOptionSetResponse.OptionSetMetadata; // Get the current options list for the retrieved attribute. return retrievedOptionSetMetadata.Options.ToList(); } public List&lt;OptionMetadata&gt; GetLocalOptionset(string entityName, string attributeName) { RetrieveAttributeRequest retrieveAttributeRequest = new RetrieveAttributeRequest { EntityLogicalName = entityName, LogicalName = attributeName, RetrieveAsIfPublished = true }; // Execute the request. RetrieveAttributeResponse retrieveAttributeResponse = (RetrieveAttributeResponse)_oService.Execute(retrieveAttributeRequest); // Access the retrieved attribute. // Get the current options list for the retrieved attribute. List&lt;OptionMetadata&gt; optionlist = new List&lt;OptionMetadata&gt;(); if (retrieveAttributeResponse.AttributeMetadata.GetType().FullName.Contains("PicklistAttributeMetadata")) { PicklistAttributeMetadata retrievedPicklistAttributeMetadata = (PicklistAttributeMetadata)retrieveAttributeResponse.AttributeMetadata; optionlist = retrievedPicklistAttributeMetadata.OptionSet.Options.ToList(); }else if (retrieveAttributeResponse.AttributeMetadata.GetType().FullName.Contains("StatusAttributeMetadata")) { StatusAttributeMetadata statusMetadata = (StatusAttributeMetadata)retrieveAttributeResponse.AttributeMetadata; // Get the current options list for the retrieved attribute. optionlist = statusMetadata.OptionSet.Options.ToList(); }else if (retrieveAttributeResponse.AttributeMetadata.GetType().FullName.Contains("StateAttributeMetadata")) { StateAttributeMetadata stateMetaData = (StateAttributeMetadata)retrieveAttributeResponse.AttributeMetadata; optionlist = stateMetaData.OptionSet.Options.ToList(); } return optionlist; } public IEnumerable&lt;Entity&gt; Retrieve_Assist_Entities(string entityName) { return _oServiceContext.CreateQuery(entityName).ToList(); } } </code></pre> <p>As you can tell, this is for development of a Dynamics CRM 2011 extension outside the website platform. I have 11 of these engines, and apart from the final one mentioned above, they all have the same methods and variables in them.</p> <p>i'm wondering if it's worth it to extract an interface (something like an <code>IEntityEngine</code>) so additional engines can be added more easily, and how to go ahead with that. I see 2 difficulties:</p> <ol> <li>The clases are split over 2 files, so that might cause some difficulties extracting an interface;</li> <li>each engine is intended for a different entity type, and has to return a different early bound entity;</li> </ol>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T18:18:06.910", "Id": "73918", "Score": "0", "body": "Got [ReSharper](http://www.jetbrains.com/resharper/)?" } ]
[ { "body": "<p><em>Extracting an interface</em> essentially boils down to taking the signatures for all public members, making them part of the interface you're extracting, and then making the type implement the interface you've extracted.</p>\n\n<p>Tools like <a href=\"http://www.jetbrains.com/resharper/\" rel=\"nofollow noreferrer\">ReSharper</a> work amazingly well for this (the <code>partial</code> class is handled, no sweat - in fact, the interface only needs to be specified in one place, if it's in both files one of them is redundant):</p>\n\n<p><img src=\"https://i.stack.imgur.com/n905b.png\" alt=\"R# Extract Interface\"></p>\n\n<p>But before you start extracting interfaces, you should ask yourself <em>why</em> you have 11 classes that are essentially identical. Wouldn't a generic class make your life easier? It could implement a generic interface, which could look like this:</p>\n\n<pre><code>public interface IEngine&lt;T, U&gt;\n{\n IEnumerable&lt;T&gt; RetrieveActive();\n T Retrieve(Guid id);\n IEnumerable&lt;U&gt; RetrieveSchade(Guid id);\n string Update(T value);\n string Create(T value);\n}\n</code></pre>\n\n<p>Where <code>T</code> would be <code>slfn_expertiseverslag</code> and <code>U</code> would be <code>slfn_schadebeschrijvingwagen</code>, but then the type parameters would need perhaps better names.</p>\n\n<p>Note that I'm exposing <code>IEnumerable&lt;T&gt;</code>, not <code>List&lt;T&gt;</code> - if the goal of the method is to expose data that's meant to be <em>consumed</em> you should expose <code>IEnumerable&lt;T&gt;</code>. Expose a <code>List&lt;T&gt;</code> when the client code needs to be able to <code>Add()</code> and <code>Remove()</code> items.</p>\n\n<p>There's a problem with your naming. <code>slfn_expertiseverslag</code> and <code>slfn_schadebeschrijvingwagen</code> don't follow naming conventions for types. Should be <code>PascalCase</code>, no underscores (save <code>snake_case</code> for <a href=\"/questions/tagged/python\" class=\"post-tag\" title=\"show questions tagged &#39;python&#39;\" rel=\"tag\">python</a> ;).</p>\n\n<p>As to address whether it's worth it to extract an interface, I can't really tell (it could very well be just additional complexity). I think making your class generic would definitely be helpful though.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T07:34:52.053", "Id": "74028", "Score": "0", "body": "The reason the naming is all lowercase is because this is a Dynamics CRM 2011 custom entity. that slfn_ is a prefix which is automatically added when you make the entity, I cannot change that. I'm also going to give an example of another class to show that 1 generic class won't work without a redesign of the code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T18:57:03.630", "Id": "74100", "Score": "0", "body": "If you mean *entity* as in *database table*, and you're using Entity Framework, mapping POCO class ABC to database table XYZ is fairly easy; an *entity* doesn't *have* to be named exactly as the db table it's mapped to. I'll take a look at your updated code later today ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T07:41:36.740", "Id": "74229", "Score": "0", "body": "I mean Entity as in a Dynamics CRM% 2011 Entity, from Microsoft.Xrm.Sdk.Entity. I don't think that's related to the Entity Framework." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T18:43:45.287", "Id": "42887", "ParentId": "42854", "Score": "10" } } ]
{ "AcceptedAnswerId": "42887", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T10:48:01.193", "Id": "42854", "Score": "6", "Tags": [ "c#", "interface" ], "Title": "How do I extract interfaces from existing similar classes?" }
42854
<p>After reading a lot of documents, I wrote this object pooling code. Can anyone help me to improve this code? I am lagging in validating the object, confirming whether I can reuse it or not.</p> <pre><code>/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package iaccount.ui; import java.util.Enumeration; import java.util.Hashtable; /** * * @author system016 */ public class ObjectPool&lt;T&gt; { private long expirationTime; private Hashtable locked, unlocked; ObjectPool() { expirationTime = 30000; // 30 seconds locked = new Hashtable(); unlocked = new Hashtable(); } // abstract public Object create(Class&lt;T&gt; clazz) throws InstantiationException, IllegalAccessException { Object obj = clazz.newInstance(); unlocked.put(clazz.newInstance(), expirationTime); return obj; } ; // abstract boolean validate( Object o ); // abstract void expire( Object o ); synchronized Object checkOut(Class&lt;T&gt; clazz) { long now = System.currentTimeMillis(); Object o = null; if (unlocked.size() &gt; 0) { Enumeration e = unlocked.keys(); while (e.hasMoreElements()) { o = e.nextElement(); if ((clazz.isAssignableFrom(o.getClass()))) { // } if ((now - ((Long) unlocked.get(o)).longValue()) &gt; expirationTime) { // object has expired unlocked.remove(o); // expire(o); o = null; } else { // if (validate(o)) { unlocked.remove(o); locked.put(o, new Long(now)); return (o); // } else { // // object failed validation // unlocked.remove(o); //// expire(o); // o = null; // } } } } } return o; } // public boolean validate(Object o){return true;}; } // synchronized void checkIn( Object o ){...} </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T12:52:27.280", "Id": "73874", "Score": "0", "body": "`ObjectPool<MyObject> pool = new ObjectPool<MyObject>(); pool.create(MyObject.class); Object obj = pool.checkOut(MyObject.class);` returns `null`. Does it work? How? Could you provide an usage example?" } ]
[ { "body": "<p>The choices of classes and other design patterns that you have made indicate to me that the books/tutorials you have been reading are pretty old. There are a number of things in your code which are almost ten years out of date in the Java 'world'.</p>\n\n<p>Also, you are only showing us half of your implementation, you have not included the <code>checkIn()</code> code.</p>\n\n<p>While I can't review the whole system without the <code>checkIn()</code> code, there is a lot to comment on without that still.</p>\n\n<h2>General</h2>\n\n<p>It is obvious that you are using an IDE to help you write your code because you have some code-template things like:</p>\n\n<blockquote>\n<pre><code>/*\n * To change this template, choose Tools | Templates\n * and open the template in the editor.\n */\n</code></pre>\n</blockquote>\n\n<p>Why is that still there? Why have you not fixed it, or removed it?</p>\n\n<p>Now, your tool should also then be pointing out other a bunch of other issues that you are obviously ignoring.... why?</p>\n\n<ul>\n<li><p>You have a semicolon out of place:</p>\n\n<blockquote>\n<pre><code> ;\n// abstract boolean validate( Object o );\n// abstract void expire( Object o );\n</code></pre>\n</blockquote></li>\n</ul>\n\n<h2>Generics</h2>\n\n<p>Your class is defined as: <code>public class ObjectPool&lt;T&gt; {</code> but you do not take full advantage of generics.</p>\n\n<p>Your constructor should take the variable <code>Class&lt;T&gt; clazz</code> instead of the <code>create(Class&lt;T&gt; clazz)</code> method, which should take nothing.</p>\n\n<p>The constructor should save away the <code>clazz</code> as a <code>private final Class&lt;T&gt; clazz;</code>;</p>\n\n<p>Then, your <code>create()</code> method should be fixed in 2 ways:</p>\n\n<ol>\n<li>it should return generic type <code>T</code></li>\n<li>it should do some validation.</li>\n<li>it should not have any input parameters.</li>\n</ol>\n\n<p>To save having the complicated exceptions on the <code>create</code> method I recommend adding the first value to the pool in the constructor, and making the constructor throw the complicated exceptions.... then the <code>create()</code> method will be simpler to use ....</p>\n\n<p>Note the following in these examples:</p>\n\n<ol>\n<li>the instance variables should be <code>private final</code> (note the final).</li>\n<li>Use the clazz instance to cast the value.</li>\n</ol>\n\n<p>Example code:</p>\n\n<pre><code> private final long expirationTime;\n private final Hashtable locked, unlocked;\n private final Class&lt;T&gt; clazz;\n\n ObjectPool(Class&lt;T&gt; clazz) throws InstantiationException, IllegalAccessException {\n expirationTime = 30000; // 30 seconds\n locked = new Hashtable();\n unlocked = new Hashtable();\n this.clazz = clazz;\n // complicated constructors with thrown exceptions....\n T o = clazz.cast(clazz.newInstance());\n locked.put(o, new Long(now));\n }\n\n public T create() {\n try {\n T obj = clazz.cast(clazz.newInstance());\n unlocked.put(clazz.newInstance(), expirationTime);\n\n return obj;\n } catch (InstantiationException ie) {\n throw new IllegalStateException(\"Even though were were able to do it in the constructor, \" \n + \"we were not able to create a new instance of \" + clazz.getName(), ie);\n } catch (IllegalAccessException iae) {\n throw new IllegalStateException(\"Even though were were able to do it in the constructor, \" \n + \"we were not able to access the newInstance() \" + clazz.getName(), ie);\n }\n\n }\n</code></pre>\n\n<p>Your <code>checkOut()</code> method should have the same generic patterns as above.</p>\n\n<p>Now, the two Hashtables... they should be Generified (your IDE is giving a lot of warnings, right?)</p>\n\n<pre><code> private Hashtable&lt;T, Long&gt; locked, unlocked;\n</code></pre>\n\n<h2>Locking and Synchronization</h2>\n\n<p>Your two methods are synchronized differently. The 'checkOut()<code>method is synchronized, but the</code>create` method is not.</p>\n\n<p>Also, you are using the (old, by the way) class <code>Hashtable</code> which is internally synchronized.</p>\n\n<p>You should, for simplicity at the moment, just use synchronized methods:</p>\n\n<pre><code>public synchronized T create() {\n ...\n}\n\npublic synchronized T checkOut() {\n ...\n}\n</code></pre>\n\n<p>and your Hashtable instances should both just be the newer, faster, and better:</p>\n\n<pre><code>private final Map&lt;T, Long&gt; locked, unlocked;\n</code></pre>\n\n<p><em>Note, I would normally recommend the Map should be a HashMap, but, read the next section...</em></p>\n\n<h2>Class Choices and bugs</h2>\n\n<p>Your class choice of Hashtable is wrong, it should be HashMap. This will lead to Iterator instead of Enumeration as well.</p>\n\n<p>Also, you are making big assumptions about <code>Class&lt;T&gt;</code> since you use it as the key to the table/map. This is a problem because the keys need to be <em>immutable</em>. I would recommend using an <code>java.util.IdentityHashMap</code> instead.</p>\n\n<h2>Conclusion...</h2>\n\n<p>There are a lot of things which can be done differently. The code has a lot of work to do still</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-05-09T14:37:58.457", "Id": "309632", "Score": "0", "body": "can you help https://codereview.stackexchange.com/questions/162914/did-this-generic-object-pool-consider-successful" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T13:00:51.947", "Id": "42867", "ParentId": "42862", "Score": "6" } }, { "body": "<p>@rolfl made a good and complete review. I would add only one thing that I think is very important.</p>\n\n<p>Don't leave commented code. </p>\n\n<pre><code>// } else {\n// // object failed validation\n// unlocked.remove(o);\n//// expire(o);\n// o = null;\n// }\n</code></pre>\n\n<p>Why is it commented ? Is it still good, is there a bug ? Can I safely remove it ? Commented code tend to stick in place forever, because no one want to remove it. Normally, your code will be under the control of a versioning software. If you need a previous version of the code, you will update a previous version of the file. This will help having only the code needed and remove noise when people read the code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T20:38:42.920", "Id": "42896", "ParentId": "42862", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T12:19:16.443", "Id": "42862", "Score": "2", "Tags": [ "java", "beginner", "synchronization" ], "Title": "Reusing objects using a generic object pool" }
42862
<p>I have implemented a customized UTF-8 encoding mechanism. The code works fine, but I have a lot of concerns regarding the code.</p> <pre><code>public class Utf8Encoding { public static void main(String[] args) { byte [] arr = new byte[1000]; int iStr = 95000; // or &gt; 65535, as till 65535 all chars are unicode and above are surrogates. String str = new String(Character.toChars(iStr)); encode(arr,0,str); System.out.println(decode(arr,utf8Length(str))); System.out.println(decode(arr,utf8Length(str)).equals(str)); } public static byte[] encode(byte[] aByteArray , int offset ,String str) { int len = str.length(); int j = offset; try { for (int k = 0; k &lt; len; ++k) { int l = str.charAt(k) &amp; 0xFFFF; if ((l &gt;= 1) &amp;&amp; (l &lt;= 127)) { aByteArray[(j++)] = (byte) l; } else if ((l == 0) || ((l &gt;= 128) &amp;&amp; (l &lt;= 2047))) { aByteArray[(j++)] = (byte) (192 + (l &gt;&gt; 6)); aByteArray[(j++)] = (byte) (128 + (l &amp; 0x3F)); } else { aByteArray[(j++)] = (byte) (224 + (l &gt;&gt; 12)); aByteArray[(j++)] = (byte) (128 + (l &gt;&gt; 6 &amp; 0x3F)); aByteArray[(j++)] = (byte) (128 + (l &amp; 0x3F)); } } } catch (ArrayIndexOutOfBoundsException localArrayIndexOutOfBoundsException) { throw new InternalError( "Cannot encode the chracter "+str); } return aByteArray; } public static String decode(byte[] aByteArray ,int len) { int j = 0; int aOffset = 0; int i = len; char[] charArray = new char[len]; while ((j &lt; len) &amp;&amp; (aByteArray[aOffset] &gt;= 0)) { charArray[(j++)] = (char) aByteArray[(aOffset++)]; } while (aOffset &lt; i) { int l = aByteArray[(aOffset++)]; if (l &gt;= 0) { charArray[(j++)] = (char) l; } else { int i1; if (l &gt;&gt; 5 == -2) { if (aOffset &lt; i) { i1 = aByteArray[(aOffset++)]; charArray[(j++)] = (char) (l &lt;&lt; 6 ^ i1 ^ 0xF80); } } int i2; if (l &gt;&gt; 4 == -2) { if (aOffset + 1 &lt; i) { i1 = aByteArray[(aOffset++)]; i2 = aByteArray[(aOffset++)]; charArray[(j++)] = (char) (l &lt;&lt; 12 ^ i1 &lt;&lt; 6 ^ i2 ^ 0xFFFE1F80); } } if (l &gt;&gt; 3 == -2) { if (aOffset + 2 &lt; i) { i1 = aByteArray[(aOffset++)]; i2 = aByteArray[(aOffset++)]; int i3 = aByteArray[(aOffset++)]; int i4 = l &lt;&lt; 18 ^ i1 &lt;&lt; 12 ^ i2 &lt;&lt; 6 ^ i3 ^ 0x381F80; charArray[(j++)] = (char) getHighSurrogate(i4); charArray[(j++)] = (char) getLowSurrogate(i4); } } } } return new String(charArray,0,j); } public static int utf8Length(String str) { int i = str.length(); int j = 0; for (int k = 0; k &lt; i; ++k) { int l = str.charAt(k) &amp; 0xFFFF; if ((l &gt;= 1) &amp;&amp; (l &lt;= 127)) ++j; else if ((l == 0) || ((l &gt;= 128) &amp;&amp; (l &lt;= 2047))) { j += 2; } else j += 3; } return j; } public static int getLowSurrogate(int number) { return (number &amp; 0x3ff) + '\uDC00'; } public static int getHighSurrogate(int number) { return (65989 &gt;&gt;&gt; 10)+ ('\uD800' - (0x010000 &gt;&gt;&gt; 10)); } } </code></pre> <p><strong>Few points of concern :</strong></p> <ol> <li><p>If I encode the above supplementary character, it is taking 6 bytes. But when I perform <code>str.getBytes("utf8")</code> it returns only 4 bytes. How many bytes does a surrogate character occupies in UTF-8 ? is it 4 or 6 ?</p></li> <li><p>Can we use UTF-8 where we have lots of Non-ASCII / native language characters ? The characters whose code point > 3000 land up occupying 3 bytes ?</p></li> </ol>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T13:49:14.670", "Id": "73885", "Score": "1", "body": "Is there a particular reason why you're reinventing the wheel instead of using the UTF-8 encoder and decoder in the standard API?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T16:05:10.940", "Id": "73907", "Score": "0", "body": "Arrays are bad. Use Collections." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T21:01:45.200", "Id": "73941", "Score": "1", "body": "All code points are \"unicode\". Even surrogates. \"utf8\" in utf8 only takes 4 bytes. Surrogates are not part of UTF-8, they are entirely a UTF-16 thing (Java strings use UTF-16). UTF-8 is _designed_ for non-ASCII/native language characters. It originally could handle even more codepoints than Java's UTF-16, but then they officially disallowed those extra codepoints. If you don't know this stuff, maybe you shouldn't be trying to write an encoder." } ]
[ { "body": "<h3>Handling of supplementary characters</h3>\n\n<p>No, your code does not handle supplementary characters correctly. A string encoded in UTF-8 <a href=\"http://en.wikipedia.org/wiki/UTF-8#Invalid_code_points\" rel=\"nofollow noreferrer\">must not contain high and low surrogate halves</a>. Instead, supplementary characters (in the range U+10000 to U+10FFFF) should be encoded as 4-byte UTF-8 sequences. Your <code>encode()</code> function only has three cases, covering 1-, 2-, and 3-byte sequences.</p>\n\n<p>As mentioned in a <a href=\"https://codereview.stackexchange.com/a/42658/9357\">previous answer</a>, Java stores its strings internally using UTF-16. Characters that don't fit into a 16-bit <code>char</code> are split into a high surrogate and a low surrogate <code>char</code>. You'll need to detect such surrogates pairs in the string and merge them before encoding.</p>\n\n<h3>Overlong encoding of <kbd>NUL</kbd></h3>\n\n<p>You encode the <kbd>NUL</kbd> byte as <code>11000000 10000000</code>. According to the specification, that's an <a href=\"http://en.wikipedia.org/wiki/UTF-8#Overlong_encodings\" rel=\"nofollow noreferrer\">overlong encoding</a>, and it's illegal.</p>\n\n<p>In short, what you have implemented is <a href=\"http://en.wikipedia.org/wiki/UTF-8#Modified_UTF-8\" rel=\"nofollow noreferrer\">Modified UTF-8</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T13:25:15.223", "Id": "73883", "Score": "0", "body": "But this code encodes and decodes supplementary characters correctly . Just try to encode and decode any supplementary character :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T13:32:15.000", "Id": "73884", "Score": "4", "body": "As I said, you've implemented Modified UTF-8. You _could_ consider it \"correct\", but you shouldn't claim that it is proper UTF-8. At the least, you should declare that it is _Modified_ UTF-8 in the JavaDoc, and possibly rename the class as well." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T13:19:24.730", "Id": "42870", "ParentId": "42863", "Score": "16" } }, { "body": "<p>Proceeding with a \"regular\" code review…</p>\n\n<p>Many of my <a href=\"https://codereview.stackexchange.com/a/42664/9357\">previous remarks about your UTF-16 encoder</a> also apply here.</p>\n\n<ul>\n<li>The parameters to <code>encode()</code> feel backwards to me.</li>\n<li>Your <code>encode()</code> lets the caller specify an offset; your <code>decode()</code> lets the caller specify a length. Design consistency would be appreciated.</li>\n<li>Does the <code>len</code> parameter to <code>decode()</code> specify the number of <code>byte</code>s to interpret or the number of <code>char</code>s to accept?</li>\n<li>In <code>encode()</code>, <code>int l = str.charAt(k) &amp; 0xFFFF</code> could just be <code>int l = str.charAt(k)</code>.</li>\n<li>The spacing around your commas ,which is inconsistent , is awkward ,though harmless.</li>\n</ul>\n\n<p>The exception handling in <code>encode()</code> is perplexing. An <code>ArrayIndexOutOfBoundsException</code> would not be an <a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/InternalError.html\" rel=\"nofollow noreferrer\"><code>InternalError</code></a>. You should never throw an <code>InternalError</code>, which indicates that the JVM has detected something seriously wrong with itself. Rather, if an <code>ArrayIndexOutOfBoundsException</code> does arise, it means that the caller passed in an array that is too small. The best course of action, in my opinion, is ignore the exception and let it propagate.</p>\n\n<p>As I read it, <code>decode()</code> seems to have a serious problem. Your first while-loop would likely copy the entire <code>byte</code> array into the <code>char</code> array (with type promotion), probably terminating when <code>j == len</code>. Since <code>aOffset</code> is synonymous with <code>j</code> (they both get incremented the same number of times in the loop), and <code>i</code> is synonymous with <code>len</code>, you'll enter the next while-loop with <code>aOffset == i</code>, thus skipping the entire second while-loop.</p>\n\n<p>There are already a lot of variables to keep track of. I don't think you need to add more variables by defining <code>int j = offset</code> in <code>encode()</code> and <code>i = len</code> in <code>decode()</code>.</p>\n\n<p>Since you are doing a lot of bit-twiddling, I would find the code easier to understand if you wrote hexadecimal (or <a href=\"http://docs.oracle.com/javase/7/docs/technotes/guides/language/binary-literals.html\" rel=\"nofollow noreferrer\">binary</a>) numeric literals instead of base-10 values. I had to break out my decimal-to-hex converter just to understand your code.</p>\n\n<p>The <code>getLowSurrogate()</code> and <code>getHighSurrogate()</code> methods have no business being part of the interface of a <code>Utf8Encoding</code>. Such helper methods should be private.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T13:43:27.163", "Id": "42872", "ParentId": "42863", "Score": "8" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T12:23:43.483", "Id": "42863", "Score": "10", "Tags": [ "java", "reinventing-the-wheel", "utf-8" ], "Title": "Customised Java UTF-8" }
42863
<p>I am working on a project in which I have three box (as of now) and each box will have some color of balls, so I am storing the input in a <code>Map</code> of <code>String</code> and <code>List</code> of <code>String</code> as shown below:</p> <pre><code>Map&lt;String, List&lt;String&gt;&gt; boxBallMap = new LinkedHashMap&lt;String, List&lt;String&gt;&gt;(); </code></pre> <p>Data in the above map can be like this. Below is one possible input combination and each box won't have same color balls, so two blues is not possible in <code>box1</code> as an input:</p> <pre><code>{box1=[blue, red, orange]} {box2=[blue, red, orange]} {box3=[blue, red, orange]} </code></pre> <p>Basis on the above input, I need to return a mapping which will be <code>List&lt;Map&lt;String, String&gt;&gt;</code>, so for above input below mapping would be returned as an output (this is one possible output combination which follows the below rules):</p> <pre><code>[{box1=blue, box2=red, box3=orange}, {box1=red, box2=orange, box3=blue}, {box1=orange, box2=blue, box3=red}] </code></pre> <p>Some rules:</p> <ol> <li><p>In each row, boxes should have an alternate colors of ball. If you see above, each row has an alternate color of balls for each box - meaning <code>blue</code> for <code>box1</code>, <code>red</code> for <code>box2</code>, <code>orange</code> for <code>box3</code> in the first row.</p></li> <li><p>I cannot have same color of balls in each row, so the below combination is not possible as it has same color of balls for two boxes in one row:</p> <pre><code>{box1=blue, box2=blue, box3=orange} </code></pre></li> <li><p>In the next row, I won't use those balls for the box which have been used in the earlier rows, so the second row cannot have <code>blue</code> for <code>box1</code> as it was already used in the first row by <code>box1</code>.</p></li> </ol> <p>Below is the code I have so far which works fine on some input combinations but somehow doesn't work on some of the input combinations:</p> <pre><code>public static List&lt;Map&lt;String, String&gt;&gt; generateMappings(Map&lt;String, List&lt;String&gt;&gt; input) { List&lt;Map&lt;String, String&gt;&gt; output = new ArrayList&lt;Map&lt;String, String&gt;&gt;(); // find all boxes List&lt;String&gt; boxes = new ArrayList&lt;String&gt;(input.keySet()); // find all colors Set&lt;String&gt; distinctColors = new LinkedHashSet&lt;String&gt;(); for(List&lt;String&gt; e : input.values()) { for(String color : e) { if(! distinctColors.contains(color)) { distinctColors.add(color); } } } List&lt;String&gt; colors = new ArrayList&lt;String&gt;(distinctColors); int colorIndex = 0; for(int i = 0; i &lt; colors.size(); i++) { Map&lt;String, String&gt; row = new LinkedHashMap&lt;String, String&gt;(); output.add(row); colorIndex = i; for(int j = 0; j &lt; colors.size(); j++) { int boxIndex = j; if(boxIndex &gt;= boxes.size()) { boxIndex = 0; } String box = boxes.get(boxIndex); List&lt;String&gt; boxColors = input.get(box); if(colorIndex &gt;= colors.size()) { colorIndex = 0; } String color = colors.get(colorIndex++); // a combination is generated only if the actual // colors does exist in the actual box if(boxColors.contains(color)) { row.put(box, color); } } } return output; } </code></pre> <p>Sample Unit Test</p> <pre><code>Map&lt;String, List&lt;String&gt;&gt; input = new LinkedHashMap&lt;&gt;(); input.put("box1", Arrays.asList("blue", "red", "orange")); input.put("box2", Arrays.asList("blue", "red", "orange")); input.put("box3", Arrays.asList("blue", "red", "orange")); List&lt;Map&lt;String, String&gt;&gt; output = create(input); for(Map&lt;String, String&gt; e : output) { System.out.println(e); } </code></pre> <p>And</p> <pre><code>Map&lt;String, List&lt;String&gt;&gt; input = new LinkedHashMap&lt;&gt;(); input.put("box1", Arrays.asList("blue", "red", "orange")); input.put("box2", Arrays.asList("blue", "red", "orange")); input.put("box3", Collections.&lt;String&gt;emptyList()); List&lt;Map&lt;String, String&gt;&gt; output = create(input); for(Map&lt;String, String&gt; e : output) { System.out.println(e); } </code></pre> <p>And </p> <pre><code>Map&lt;String, List&lt;String&gt;&gt; input = new LinkedHashMap&lt;&gt;(); input.put("box1", Arrays.asList("blue", "red", "orange")); input.put("box2", Arrays.asList("blue", "red")); input.put("box3", Arrays.asList("blue", "red", "orange")); List&lt;Map&lt;String, String&gt;&gt; output = create(input); for(Map&lt;String, String&gt; e : output) { System.out.println(e); } </code></pre> <p>Is there any better way of solving this algorithm?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T14:39:36.443", "Id": "73893", "Score": "0", "body": "I'm not sure I understand the requirements, say on top of your sample input I have `{box4=[blue,blue]}` what would the expected output be? It would be nice if you also added some unit tests." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T15:21:37.580", "Id": "73901", "Score": "0", "body": "Sample input won't be like that.. It will always be different colors balls for same box in each row. Just updated the question.." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T16:24:30.843", "Id": "73910", "Score": "0", "body": "These are not [unit tests](http://en.wikipedia.org/wiki/Unit_testing)... these are samples... at least give the expected output... is the requirement that the color order will always be \"blue\", \"red\", \"orange\"? Are more colors allowed?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T16:39:46.403", "Id": "73912", "Score": "0", "body": "There might be more colors allowed as well.. I thought those code will be sufficient.. Expected output is based on those rules I have.. let me try to grab the outputs if possible.." } ]
[ { "body": "<p>First of all, save some manual checking work and make your <a href=\"http://xunitpatterns.com/Goals%20of%20Test%20Automation.html\" rel=\"nofollow\">test self-checking</a> with JUnit and Google Guava:</p>\n\n<pre><code>import static com.google.common.collect.Lists.newArrayList;\nimport static org.junit.Assert.assertEquals;\nimport org.junit.Test;\nimport com.google.common.collect.ImmutableMap;\n\n...\n\n@Test\npublic void test1() {\n final Map&lt;String, List&lt;String&gt;&gt; input = new LinkedHashMap&lt;&gt;();\n input.put(\"box1\", Arrays.asList(\"blue\", \"red\", \"orange\"));\n input.put(\"box2\", Arrays.asList(\"blue\", \"red\", \"orange\"));\n input.put(\"box3\", Arrays.asList(\"blue\", \"red\", \"orange\"));\n\n final List&lt;Map&lt;String, String&gt;&gt; output = Generator.generateMappings(input);\n\n final List&lt;Map&lt;String, String&gt;&gt; expected = newArrayList();\n expected.add(ImmutableMap.of(\"box1\", \"blue\", \"box2\", \"red\", \"box3\", \"orange\"));\n expected.add(ImmutableMap.of(\"box1\", \"red\", \"box2\", \"orange\", \"box3\", \"blue\"));\n expected.add(ImmutableMap.of(\"box1\", \"orange\", \"box2\", \"blue\", \"box3\", \"red\"));\n\n assertEquals(expected, output);\n}\n\n@Test\npublic void test2() throws Exception {\n final Map&lt;String, List&lt;String&gt;&gt; input = new LinkedHashMap&lt;&gt;();\n input.put(\"box1\", Arrays.asList(\"blue\", \"red\", \"orange\"));\n input.put(\"box2\", Arrays.asList(\"blue\", \"red\", \"orange\"));\n input.put(\"box3\", Collections.&lt;String&gt; emptyList());\n\n final List&lt;Map&lt;String, String&gt;&gt; output = Generator.generateMappings(input);\n\n final List&lt;Map&lt;String, String&gt;&gt; expected = newArrayList();\n expected.add(ImmutableMap.of(\"box1\", \"blue\", \"box2\", \"red\"));\n expected.add(ImmutableMap.of(\"box1\", \"red\", \"box2\", \"orange\"));\n expected.add(ImmutableMap.of(\"box1\", \"orange\", \"box2\", \"blue\"));\n\n assertEquals(expected, output);\n}\n\n@Test\npublic void test3() throws Exception {\n final Map&lt;String, List&lt;String&gt;&gt; input = new LinkedHashMap&lt;&gt;();\n input.put(\"box1\", Arrays.asList(\"blue\", \"red\", \"orange\"));\n input.put(\"box2\", Arrays.asList(\"blue\", \"red\"));\n input.put(\"box3\", Arrays.asList(\"blue\", \"red\", \"orange\"));\n\n final List&lt;Map&lt;String, String&gt;&gt; output = Generator.generateMappings(input);\n\n final List&lt;Map&lt;String, String&gt;&gt; expected = newArrayList();\n expected.add(ImmutableMap.of(\"box1\", \"blue\", \"box2\", \"red\", \"box3\", \"orange\"));\n expected.add(ImmutableMap.of(\"box1\", \"red\", \"box3\", \"blue\"));\n expected.add(ImmutableMap.of(\"box1\", \"orange\", \"box2\", \"blue\", \"box3\", \"red\"));\n\n assertEquals(expected, output);\n}\n</code></pre>\n\n<p>Then make it a little bit more readable with extracted out methods and <code>new*</code> factory methods:</p>\n\n<pre><code>import static com.google.common.collect.Lists.newArrayList;\nimport static com.google.common.collect.Maps.newLinkedHashMap;\n\n...\n\npublic static List&lt;Map&lt;String, String&gt;&gt; generateMappings(\n Map&lt;String, List&lt;String&gt;&gt; input) {\n final List&lt;Map&lt;String, String&gt;&gt; output = newArrayList();\n final List&lt;String&gt; boxes = getAllBoxes(input);\n final List&lt;String&gt; colors = getAllColors(input);\n\n int colorIndex = 0;\n for (int i = 0; i &lt; colors.size(); i++) {\n ...\n }\n return output;\n}\n\nprivate static List&lt;String&gt; getAllBoxes(\n Map&lt;String, List&lt;String&gt;&gt; input) {\n return newArrayList(input.keySet());\n}\n\nprivate static List&lt;String&gt; getAllColors(\n Map&lt;String, List&lt;String&gt;&gt; input) {\n final Set&lt;String&gt; distinctColors = new LinkedHashSet&lt;String&gt;();\n for (final List&lt;String&gt; e: input.values()) {\n for (final String color: e) {\n if (!distinctColors.contains(color)) {\n distinctColors.add(color);\n }\n }\n }\n final List&lt;String&gt; colors = newArrayList(distinctColors);\n return colors;\n}\n</code></pre>\n\n<p>Note that it made the comments superfluous so I removed them.</p>\n\n<p>I don't completely understand the requirements nor the code but maybe I'm just too tired. Anyway, I'd suggest you another approach: Generate every possible row (invalid ones too) and decide with one or more <code>Rule</code> classes whether a row is valid or not.</p>\n\n<p>Pseudocode:</p>\n\n<pre><code>public interface Rule {\n boolean isValidRow(row, acceptedRows);\n}\n\npublic class AndRule implements Rule {\n List&lt;Rule&gt; rules;\n\n public AndRule(Rule rules...) {\n this.rules = newArrayList(rules);\n }\n\n public boolean isValidRow(row, acceptedRows) {\n for (Rule rule: rules) {\n if (!rule.isValidRow(row, acceptedRows)) {\n return false;\n }\n }\n return true;\n }\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>Rule mainRule = new AndRule(rule1, rule2, rule3);\n\nList&lt;Map&lt;String, String&gt;&gt; output = newArrayList();\n// maybe you need nested loops here, but an Iterator would be better\nfor (...) { \n Map&lt;String, String&gt; row = createNextRow(...);\n if (mainRule.isValidRow(row, output)) {\n output.add(row);\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T21:52:54.380", "Id": "74138", "Score": "1", "body": "Thanks for your suggestion.. I was able to find a solution for this from your suggestion.. Appreciated your help.. I also have similar question [here](http://codereview.stackexchange.com/questions/42982/find-an-element-from-multiple-sorted-lists-efficiently). Can you take a look if possible?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T19:01:54.737", "Id": "42888", "ParentId": "42871", "Score": "2" } } ]
{ "AcceptedAnswerId": "42888", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T13:36:49.500", "Id": "42871", "Score": "2", "Tags": [ "java", "optimization", "algorithm" ], "Title": "Generating balls and box combinations depending on set rules" }
42871
<p>In the below code I should highlight countries on the map based on the category of the country in which there are 2 different type of countries (issuing office and selected countries). Based on the country type I have to highlight that country on the map. Let us not worry about map code.</p> <p>There is a checkbox which contains names of all the countries once user choose checkbox against countries (i.e selects a country I should add it as issuing office and if user unchecks the checkgox then I should deselect the issuing office).</p> <p>There are update details button <code>onClicking</code>. With this button I get some information which I will not show on the map (we can ignore action taken on clicking update details button for now).</p> <p>Now after clicking update details button, if user selects a country by clicking checkbox, then I should add that country as selected country. If user unchecks the newly selected country I should deselect it from the map. If user unchecks the issuing office then we should deselect that country.</p> <p>The idea here is first time user choose io after clicking update details buttons I get some information now which ever chooses newly they are selected countries which I highlight in different color after clicking on update details button I will convert all newly selected countries into issuing office.</p> <p>Now that I have explained the functionality below few point:</p> <p>Whenever a country I chosen or deselected I don't get the name of country that was choose/unchoosen. I get names of all the countries that currently selected.</p> <p>Let's say I choose:</p> <pre><code> Australia my method gets Australia now user chooses Italy I get Australia,Italy now user chooses Russia I get Australia,Italy,Russia Now user unchecks Australia I get Italy,Russia </code></pre> <p>Below is the code. Please validate:</p> <pre><code>var issuingOffice,selectedCountries,issuingOfficeSymbol,mapDefaultSymbol,selectedOfficeSymbol; require(["dojox/collections/ArrayList","esri/symbols/SimpleFillSymbol", "esri/symbols/SimpleLineSymbol", "dojo/_base/Color", "esri/graphic" ], function(arrayList){ issuingOffice = new arrayList(); selectedCountries = new arrayList(); issuingOfficeSymbol = new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID, new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color("#AED8EC"), 1), new Color("#FDB913")); mapDefaultSymbol = new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID, new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color("#C2C2C2"), 1), new Color("#A0A0A0")); selectedOfficeSymbol = new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID, new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color("#C2C2C2"), 1), new Color("#8440E3")); }); function setIssuingOffice(countryName){ console.log("function : setIssuingOffice"); /* * semicolon sepearated list of countryName will be avaialabe via program selecton module * we have to replace ; with , so that we iterate over the list */ countryName = replaceAll(";", ",", countryName); /* * once we replace ; with , then we split the string with , to get * list of string */ var countryList = countryName.split(","); if(getDetailsClicked == true){ var tempCountry; var removedCoutries; var countriesTobeRemoved; require(["dojox/collections/ArrayList"], function(arrayList){ tempCountry = new arrayList(); removedCoutries = new arrayList(); countriesTobeRemoved = new arrayList(); }); // below code is to check if any country has been deselected var it = selectedCountries.getIterator(); while (!it.atEnd()) { var country = it.get(); var isSelected = false; dojoArray.some(countryList, function(selectedCountry){ return isSelected=(country == selectedCountry); }) if (!isSelected) { tempCountry.add(country); // this is list of countris that has to be deleted on click on GEt Details } } // iterate over deselected countries and remove them // DO this when GET DETAILS is clicked. var tempCountryIt = tempCountry.getIterator(); while (!tempCountryIt.atEnd()) { var country = tempCountryIt.get(); bottomBar.remove(country); selectedCountries.remove(country); if (country != producingOffice) { removeCountry(country); } } var issuingIt = issuingOffice.getIterator(); while (!issuingIt.atEnd()) { var country = issuingIt.get(); var isSelected = false; dojoArray.some(countryList, function(selectedCountry){ return isSelected = (country == selectedCountry); }) if (!isSelected) { countriesTobeRemoved.add(country); } } var countriesTobeRemovedIt = countriesTobeRemoved.getIterator(); while (!countriesTobeRemovedIt.atEnd()) { var country = countriesTobeRemovedIt.get(); issuingOffice.remove(country); bottomBar.remove(country); if (country != producingOffice) { removeCountry(country); } } dojo.forEach(countryList, function(country){ if (country != '' &amp;&amp; country != undefined) { if (!tempCountry.contains(country) &amp;&amp; !selectedCountries.contains(country) &amp;&amp; !countriesTobeRemoved.contains(country) &amp;&amp; !issuingOffice.contains(country)) { if (producingOffice != country) { selectedCountries.add(country); // TODO: check if country exists only then add if (!bottomBar.contains(country)) { bottomBar.add(country); } // below is logic to highligt based on page if lannding page and if country has alert then highlight as alert. if (hashMap.containsKey(country)) { var graphic = hashMap.item(country); graphic.setSymbol(selectedOfficeSymbol); //map.graphics.add(graphic); } }else if(producingOffice == country){ selectedCountries.add(country); } } } }); }else{ var tempCountry; var removedCoutries; require(["dojox/collections/ArrayList"], function(arrayList){ tempCountry = new arrayList(); removedCoutries = new arrayList(); }); // check for con-current modification ? var isIt = issuingOffice.getIterator(); while (!isIt.atEnd()) { var country = isIt.get(); var isSelected = false; /*dojo.forEach(countryList, function(selectedCountry){ if (country == selectedCountry) { isSelected = true; } });*/ dojoArray.some(countryList, function(selectedCountry){ return isSelected=(country == selectedCountry); }) if (!isSelected) { removedCoutries.add(country); } } var tempCountryIt = removedCoutries.getIterator(); while (!tempCountryIt.atEnd()) { var country = tempCountryIt.get(); bottomBar.remove(country); issuingOffice.remove(country); if (country != producingOffice) { removeCountry(country); } } // below code is to check if any country has been deselected dojo.forEach(countryList, function(country){ if (country != '' &amp;&amp; country != undefined) { if (!issuingOffice.contains(country) &amp;&amp; !removedCoutries.contains(country)) { if(producingOffice != country){ issuingOffice.add(country); // TODO: check if country exists only then add if (!bottomBar.contains(country)) { bottomBar.add(country); } if (hashMap.containsKey(country)) { var graphic = hashMap.item(country); graphic.setSymbol(issuingOfficeSymbol); //map.graphics.add(graphic); } }else if(producingOffice == country){ issuingOffice.add(country); if (!bottomBar.contains(country)) { bottomBar.add(country); } }else{ } } } }); } } </code></pre>
[]
[ { "body": "<p>From a once over:</p>\n\n<ul>\n<li><p>This:<br></p>\n\n<pre><code> /*\n * semicolon sepearated list of countryName will be avaialabe via selection module\n * we have to replace ; with , so that we iterate over the list\n */\n countryName = replaceAll(\";\", \",\", countryName); \n\n /*\n * once we replace ; with , then we split the string with , to get\n * list of string\n */\n var countryList = countryName.split(\",\");\n</code></pre>\n\n<p>should be this:</p>\n\n<pre><code>//CountryNames contains a semicolon separated list of country names\nvar countryList = countryNames.split(';');\n</code></pre>\n\n<p>Note that <code>countryName</code> -> <code>countryNames</code> since you are passing more often than not multiple country names.</p></li>\n<li><p>This:<br></p>\n\n<pre><code> // below code is to check if any country has been deselected\n var it = selectedCountries.getIterator();\n while (!it.atEnd()) { \n var country = it.get(); \n var isSelected = false; \n dojoArray.some(countryList, function(selectedCountry){\n return isSelected=(country == selectedCountry);\n }) \n if (!isSelected) {\n tempCountry.add(country); // this is list of countris that has to be deleted on click on GEt Details\n }\n }\n</code></pre>\n\n<p>could be ( by using <code>filter</code> which is both in standard JS and in Dojo ):</p>\n\n<pre><code> tempCountry = dojoArray.filter( countryList, function( country ){\n return dojoArray.indexOf( selectedCountries, country ) == -1; \n });\n</code></pre>\n\n<p>Since you are talking about loop optimization, you might even consider to change <code>selectedCountries</code> to act like a hashMap (an object with each selected country as a property set to to <code>true</code>), this way you could <code>return</code> even faster like this:</p>\n\n<pre><code> tempCountry = dojoArray.filter( countryList, function( country ){\n return !selectedCountries[country]; \n });\n</code></pre></li>\n<li>Iterators just seem wrong in JavaScript, I would suggest to just use <code>forEach</code></li>\n<li><code>if (country != '' &amp;&amp; country != undefined) {</code> -> <code>if(country){</code></li>\n<li>Where do you declare <code>var hashMap</code> ?</li>\n<li>Avoid <code>console.log</code> in production code</li>\n<li>Avoid commented out code in production code</li>\n<li><p>If <code>bottomBar</code> was a hashMap, then this:</p>\n\n<pre><code>if (!bottomBar.contains(country)) {\n bottomBar.add(country);\n}\n</code></pre>\n\n<p>would be <code>bottomBar[country] = true;</code></p></li>\n<li>There is a ton of copy pasted code in there, with the <code>filter</code> trick, you might not need to address it, but in general, you should be more diligent in factoring copy pasted code into functions.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T14:00:08.287", "Id": "74443", "Score": "0", "body": "Thanks a lot , i was not able to reply early since i was busy .Can there be anyother way i can skip the loop itself ." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T14:54:21.477", "Id": "42875", "ParentId": "42873", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T14:18:19.180", "Id": "42873", "Score": "6", "Tags": [ "javascript", "optimization", "algorithm", "dojo" ], "Title": "Highlight countries based on category" }
42873
<p>I need to improve the performance of a function that calculates the integral of a two-dimensional <a href="https://en.wikipedia.org/wiki/Kernel_density_estimation" rel="nofollow noreferrer">kernel density estimate</a> (obtained using the function <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.gaussian_kde.html" rel="nofollow noreferrer">stats.gaussian_kde</a>) where the domain of integration is all points that evaluate below a given value.</p> <p>I've found that a <strong>single line</strong> takes up pretty much 100% of the time used by the code:</p> <pre><code>insample = kernel(sample) &lt; iso </code></pre> <p>(see the code below). This line stores in the list <code>insample</code> all the values in <code>sample</code> that evaluate in <code>kernel</code> to less than the float <code>iso</code>.</p> <p>I made this question (slightly modified) 6 months ago over at <a href="https://stackoverflow.com/questions/18538790/speed-up-sampling-of-kernel-estimate">Stack Overflow</a> and the best answer involved parallelization. I'm hoping to avoid parallelization (gives way too much trouble as can be seen in the question linked above), but I'm open to any improvement in performance achieved by means of virtually any other way (including Cython and any package available).</p> <p>Here's the minimum working example (MWE):</p> <pre><code>import numpy as np from scipy import stats # Define KDE integration function. def kde_integration(m1, m2): # Perform a kernel density estimate (KDE) on the data. values = np.vstack([m1, m2]) kernel = stats.gaussian_kde(values, bw_method=None) # This list will be returned at the end of this function. out_list = [] # Iterate through all floats in m1, m2 lists and calculate for each one the # integral of the KDE for the domain of points located *below* the KDE # value of said float eveluated in the KDE. for indx, m1_p in enumerate(m1): # Compute the point below which to integrate. iso = kernel((m1_p, m2[indx])) # Sample KDE distribution sample = kernel.resample(size=100) # THIS TAKES ALMOST 100% OF THE COMPUTATION TIME. # Filter the sample. insample = kernel(sample) &lt; iso # Monte Carlo Integral. integral = insample.sum() / float(insample.shape[0]) # Avoid 'nan' and/or 'infinite' values down the line. integral = integral if integral &gt; 0. else 0.000001 # Append integral value for this point to list that will return. out_list.append(round(integral, 2)) return out_list # Generate some random two-dimensional data: def measure(n): "Return two coupled measurements." m1 = np.random.normal(size=n) m2 = np.random.normal(scale=0.5, size=n) return m1+m2, m1-m2 # Random data. m1, m2 = measure(100) # Call KDE integration function. kde_integration(m1, m2) </code></pre> <p>Any help/suggestions/ideas will be very much appreciated.</p>
[]
[ { "body": "<blockquote>\n<p>I am never forget the day I first meet the great Lobachevsky.\nIn one word he told me secret of success in NumPy:\nVectorize!</p>\n<p>Vectorize!<br>\nIn every loop inspect your <code>i</code>'s<br>\nRemember why the good Lord made your eyes!<br>\nSo don't shade your eyes,<br>\nBut vectorize, vectorize, vectorize—<br>\nOnly be sure always to call it please 'refactoring'.</p>\n</blockquote>\n<pre><code>def kde_integration(m1, m2, sample_size=100, epsilon=0.000001):\n values = np.vstack((m1, m2))\n kernel = stats.gaussian_kde(values, bw_method=None)\n iso = kernel(values)\n sample = kernel.resample(size=sample_size * len(m1))\n insample = kernel(sample).reshape(sample_size, -1) &lt; iso.reshape(1, -1)\n return np.maximum(insample.mean(axis=0), epsilon)\n</code></pre>\n<h3>Update</h3>\n<p>I find that my <code>kde_integration</code> is about ten times as fast as yours with <code>sample_size=100</code>:</p>\n<pre class=\"lang-none prettyprint-override\"><code>&gt;&gt;&gt; m1, m2 = measure(100)\n&gt;&gt;&gt; from timeit import timeit\n&gt;&gt;&gt; timeit(lambda:kde_integration1(m1, m2), number=1) # yours\n0.7005664870084729\n&gt;&gt;&gt; timeit(lambda:kde_integration2(m1, m2), number=1) # mine (above)\n0.07272820601065177\n</code></pre>\n<p>But the advantage disappears with larger sample sizes:</p>\n<pre class=\"lang-none prettyprint-override\"><code>&gt;&gt;&gt; timeit(lambda:kde_integration1(m1, m2, sample_size=1024), number=1)\n1.1872510590037564\n&gt;&gt;&gt; timeit(lambda:kde_integration2(m1, m2, sample_size=1024), number=1)\n1.2788789629994426\n</code></pre>\n<p>What this suggests is that there is a &quot;sweet spot&quot; for <code>sample_size * len(m1)</code> (perhaps related to the computer's cache size) and so you'll get the best results by processing the samples in chunks of that length.</p>\n<p>You don't say exactly how you're testing it, but different results are surely to be expected, since <a href=\"http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.gaussian_kde.html\" rel=\"nofollow noreferrer\"><code>scipy.stats.gaussian_kde.resample</code></a> &quot;Randomly samples a dataset from the estimated pdf&quot;.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T11:59:12.003", "Id": "74043", "Score": "0", "body": "Thank you @Gareth! I checked and this function seems slightly faster than the original for small `sample_size` but quite slower for larger values (try `sample_size=1000`) Can you confirm this?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T12:10:14.873", "Id": "74045", "Score": "0", "body": "Also this function returns slightly different values and I can't figure out why." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T12:36:30.397", "Id": "74048", "Score": "0", "body": "See revised answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T13:05:38.393", "Id": "74050", "Score": "0", "body": "In my case `sample_size=100` and `len(m1)=100` give a ~x3 speed improvement and this appears to be the maximum I can get. If I fix `sample_size=1000` I could not find a `len(m1)` size where the new function performed significantly better. (You are right, the results are not exactly the same because of the resampling done by `kernel.resample`)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T13:11:54.260", "Id": "74052", "Score": "0", "body": "Add: I can only get a minimal improvement with `sample_size=1000` if `len(m1)<50`, but it's a really minor difference." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T02:44:47.033", "Id": "42919", "ParentId": "42876", "Score": "6" } } ]
{ "AcceptedAnswerId": "42919", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T15:16:35.413", "Id": "42876", "Score": "6", "Tags": [ "python", "performance", "numpy", "statistics" ], "Title": "Improve performance of Gaussian kernel function evaluation" }
42876
<p>When an API has a 'next' feature, I use the following pattern to obtain all the results:</p> <pre><code>/** Obtains a list of channels followed by a user */ function get_follows(username, callback) { var channels = []; function handler(data) { if (!data || data.follows.length == 0) { callback(channels); return; } for (var i = 0; i &lt; data.follows.length; i++) channels.push(data.follows[i].channel); JSON.load(data._links.next, handler); } var url = "https://api.twitch.tv/kraken/users/"+username+"/follows/channels?limit=75&amp;offset=0&amp;on_site=1"; JSON.load(url, handler); } </code></pre> <p>Is there a better way to go about this?</p>
[]
[ { "body": "<p>I like your code, and would use it myself, some thoughts:</p>\n\n<ul>\n<li><p>I assume you declare <code>url</code> next to <code>JSON.load</code> because you want to declare it close to where you use it. I would still recommend using 1 comma separated list of variables on the top.</p></li>\n<li><p>lowerCamelCase is good for you, <code>get_follows</code> -> <code>getFollows</code> -> <code>getFollowedChannels</code> ?</p></li>\n<li><p>Comparing to <code>0</code> should be done with <code>===</code>, if you do it for the length of an array I would go with a falsey comparison: <code>if (!data || !data.follows.length) {</code></p></li>\n</ul>\n\n<p>From a design perspective, you are circumventing the paging system, are you sure you always need every single channel? I hope you at least cache the retrieved information.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T17:05:43.557", "Id": "42881", "ParentId": "42878", "Score": "5" } } ]
{ "AcceptedAnswerId": "42881", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T15:47:31.957", "Id": "42878", "Score": "7", "Tags": [ "javascript", "ajax", "json", "callback", "http" ], "Title": "Requesting Resources Until Exhaustion" }
42878
<p>I got a piece of Java code using Hadoop to calculate min, max, average and variance on a large dataset made of (index value) couples separated by a newline:</p> <pre><code>0 11839923.64831265 1 5710431.90800272 </code></pre> <p>It's compiled locally and run on a remote distributed HDFS instance by a sh script.</p> <p>My main concerns are:</p> <ul> <li><p>if the output is collected in a different order, the thing just stops working, and instead of returning one result for each key, it prints the same key over and over, filling the terminal</p></li> <li><p>it creates a new <code>Text</code> instance every time, which looks really inefficient, but when I tired to use a single shared constant, it stopped working. Maybe using an <code>Enum</code> would do fine, but I don't feel like changing it until I fixed the previous point.</p></li> <li><p>it's using a <code>Scanner</code> inside the mapper to treat multi-line inputs properly, but only single-line input is showing up. Does Hadoop guarantee each mapper only receives one-line inputs, or is the remote setup that makes it so?</p></li> <li><p>it uses the "old" approach of extending the <code>MapReduceBase</code> class and implementing the <code>Mapper</code>/<code>Reducer</code> interface. I've read that, with the new 2.0 APIs it's sufficient to extend one <code>Mapper</code> or <code>Reducer</code> class. Yet, I can't find any migration doc with simple migration doc, and the official WordCount example tutorial <a href="https://hadoop.apache.org/docs/r1.2.1/mapred_tutorial.html#Example:+WordCount+v1.0" rel="nofollow noreferrer">is stuck at r1.2.1</a>. EDIT: found <a href="https://stackoverflow.com/questions/7626077/mapreducebase-and-mapper-deprecated">a reference</a> for this. And <a href="https://stackoverflow.com/questions/7598422/is-it-better-to-use-the-mapred-or-the-mapreduce-package-to-create-a-hadoop-job">another one here</a>. </p></li> </ul> <p>Here's the code:</p> <pre><code>package org.myorg; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.BufferedWriter; import java.io.OutputStreamWriter; import java.util.*; import org.apache.hadoop.fs.*; import org.apache.hadoop.conf.*; import org.apache.hadoop.io.*; import org.apache.hadoop.mapred.*; import org.apache.hadoop.util.*; public class calcAll { public static class Map extends MapReduceBase implements Mapper&lt;LongWritable, Text, Text, DoubleWritable&gt; { public void map(LongWritable key, Text value, OutputCollector&lt;Text, DoubleWritable&gt; output, Reporter reporter) throws IOException { // this will work even if we receive more than 1 line Scanner scanner = new Scanner(value.toString()); String line; String[] tokens; double observation; while (scanner.hasNext()) { line = scanner.nextLine(); tokens = line.split("\\s+"); observation = Double.parseDouble(tokens[1]); output.collect(new Text("values"), new DoubleWritable(observation)); } } } public static class Combine extends MapReduceBase implements Reducer&lt;Text, DoubleWritable, Text, DoubleWritable&gt; { public void reduce(Text key, Iterator&lt;DoubleWritable&gt; values, OutputCollector&lt;Text, DoubleWritable&gt; output, Reporter reporter) throws IOException { double count = 0d; // should be an int, but anyway... double min = Double.MAX_VALUE; double max = Double.MIN_VALUE; double sum = 0d; double sumSquared = 0d; double value; while (values.hasNext()) { ++count; value = values.next().get(); min = Math.min(min, value); max = Math.max(max, value); sum += value; sumSquared += value * value; } // keep in alphabetical order or KABOOM! output.collect(new Text("count"), new DoubleWritable(count)); output.collect(new Text("max"), new DoubleWritable(max)); output.collect(new Text("min"), new DoubleWritable(min)); output.collect(new Text("sum"), new DoubleWritable(sum)); output.collect(new Text("sumSquared"), new DoubleWritable(sumSquared)); } } public static class Reduce extends MapReduceBase implements Reducer&lt;Text, DoubleWritable, Text, DoubleWritable&gt; { public void reduce(Text key, Iterator&lt;DoubleWritable&gt; values, OutputCollector&lt;Text, DoubleWritable&gt; output, Reporter reporter) throws IOException { if (key.equals(new Text("count"))) { double count = 0d; double value; while (values.hasNext()) { value = values.next().get(); count += value; } output.collect(new Text("count"), new DoubleWritable(count)); } if (key.equals(new Text("max"))) { double max = Double.MIN_VALUE; double value; while (values.hasNext()) { value = values.next().get(); max = Math.max(max, value); } output.collect(new Text("max"), new DoubleWritable(max)); } if (key.equals(new Text("min"))) { double min = Double.MAX_VALUE; double value; while (values.hasNext()) { value = values.next().get(); min = Math.min(min, value); } output.collect(new Text("min"), new DoubleWritable(min)); } if (key.equals(new Text("sum"))) { double sum = 0d; double value; while (values.hasNext()) { value = values.next().get(); sum += value; } output.collect(new Text("sum"), new DoubleWritable(sum)); } if (key.equals(new Text("sumSquared"))) { double sumSquared = 0d; double value; while (values.hasNext()) { value = values.next().get(); sumSquared += value; } output.collect(new Text("sumSquared"), new DoubleWritable(sumSquared)); } } } public static boolean applySecondPass(Path in, Path out) { double count = 0d, max = 0d, min = 0d, sum = 0d, sumSquared = 0d; try (FileSystem fs = FileSystem.get(new Configuration()); BufferedReader br = new BufferedReader(new InputStreamReader(fs.open(in)));) { String line; String[] words; line = br.readLine(); while (line != null) { words = line.split("\\s+"); switch (words[0]) { case "count": count = Double.parseDouble(words[1]); break; case "max": max = Double.parseDouble(words[1]); break; case "min": min = Double.parseDouble(words[1]); break; case "sum": sum = Double.parseDouble(words[1]); break; case "sumSquared": sumSquared = Double.parseDouble(words[1]); break; } line = br.readLine(); } } catch (Exception e) { e.printStackTrace(); return false; } double avg = sum / count; // (Sum_sqr - (Sum*Sum)/n)/(n - 1) double variance = (sumSquared - (sum * sum) / count) / (count - 1); try (FileSystem fs = FileSystem.get(new Configuration()); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fs.create(out, true)));) { String line; line = "avg\t" + String.valueOf(avg) + System.lineSeparator(); bw.write(line); line = "variance\t" + String.valueOf(variance) + System.lineSeparator(); bw.write(line); } catch (Exception e) { e.printStackTrace(); return false; } return true; } public static void main(String[] args) throws Exception { JobConf conf = new JobConf(calcAll.class); conf.setJobName("calcAll"); conf.setOutputKeyClass(Text.class); conf.setOutputValueClass(DoubleWritable.class); conf.setMapperClass(Map.class); conf.setCombinerClass(Combine.class); conf.setReducerClass(Reduce.class); conf.setInputFormat(TextInputFormat.class); conf.setOutputFormat(TextOutputFormat.class); FileInputFormat.setInputPaths(conf, new Path(args[0])); Path out1 = new Path(args[1]); FileOutputFormat.setOutputPath(conf, out1); JobClient.runJob(conf); // blocking call // the output is a set of files, merge them before continuing Path out1Merged = new Path(args[2]); Configuration config = new Configuration(); try { FileSystem hdfs = FileSystem.get(config); FileUtil.copyMerge(hdfs, out1, hdfs, out1Merged, false, config, null); } catch (IOException e) { e.printStackTrace(); System.exit(1); } // calculate on job output boolean success = applySecondPass(out1Merged, new Path(args[3])); System.out.println("Second pass successful? " + success); System.exit(success ? 1 : 0); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-02T00:10:50.460", "Id": "74510", "Score": "0", "body": "How large is your dataset? Unless it can't fit on a typical hard-drive, I would re-examine whether you even need to MR." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-03T13:16:42.380", "Id": "74721", "Score": "0", "body": "Several GBs. These are just base calculations that could be done with multi-threading, but, I'll need to do more complex stuff later, so I'd better learn MR now." } ]
[ { "body": "<p>I'm not familiar with Hadoop, take my advice with care.</p>\n\n<ol>\n<li><p>Are you sure that the following is precise enough?</p>\n\n<pre><code>double count = 0d; // should be an int, but anyway...\n</code></pre>\n\n<p>Consider the following:</p>\n\n<pre><code>final double original = 123456789123456789.0;\ndouble d = original;\nd++;\nSystem.out.println(d == original); // true\nSystem.out.printf(\"%f%n\", original); // 123456789123456784,000000\nSystem.out.printf(\"%f%n\", d); // 123456789123456784,000000\n</code></pre>\n\n<p>I'd use a <code>long</code> there. I guess it's not a problem here but if I'm right the reducer could suffer from this.</p>\n\n<p>See also: </p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/q/3730019/843804\">Why not use Double or Float to represent currency?</a></li>\n<li><em>Effective Java, 2nd Edition, Item 48: Avoid float and double if exact answers are required</em></li>\n</ul></li>\n<li><blockquote>\n<pre><code>tokens = line.split(\"\\\\s+\");\n</code></pre>\n</blockquote>\n\n<p>The <a href=\"http://hg.openjdk.java.net/jdk6/jdk6-gate/jdk/file/tip/src/share/classes/java/lang/String.java\" rel=\"nofollow noreferrer\">implementation of <code>split</code> was simply this in Java 6</a>:</p>\n\n<pre><code>public String[] split(String regex, int limit) {\n return Pattern.compile(regex).split(this, limit);\n}\n</code></pre>\n\n<p><a href=\"http://hg.openjdk.java.net/jdk7/jdk7/jdk/file/tip/src/share/classes/java/lang/String.java\" rel=\"nofollow noreferrer\">Java 7 contains some fast-paths</a>, but at the end it still calls:</p>\n\n<pre><code>return Pattern.compile(regex).split(this, limit);\n</code></pre>\n\n<p>In your case (with the <code>\\\\s+</code> pattern) it does not use any fast-path, so it might be worth to store the compiled <code>Pattern</code> instance and call <code>split</code> on that. (I guess it would be faster but the JVM might cache that for you.)</p></li>\n<li><blockquote>\n<pre><code> double count = 0d, max = 0d, min = 0d, sum = 0d, sumSquared = 0d;\n</code></pre>\n</blockquote>\n\n<p>I'd put the variable declarations to separate lines. From <em>Code Complete 2nd Edition</em>, p759:</p>\n\n<blockquote>\n <p>With statements on their own lines, the code reads from top to bottom, instead\n of top to bottom and left to right. When you’re looking for a specific line of code,\n your eye should be able to follow the left margin of the code. It shouldn’t have to\n dip into each and every line just because a single line might contain two statements.</p>\n</blockquote>\n\n<p>Additionally, <code>max</code> and <code>min</code> is not used (they are only written), you could safely remove them (or might want to print them to the output).</p></li>\n<li><pre><code>@Override\npublic void reduce(Text key, Iterator&lt;DoubleWritable&gt; values,\n OutputCollector&lt;Text, DoubleWritable&gt; output, Reporter reporter) throws IOException {\n if (key.equals(new Text(\"count\"))) {\n</code></pre>\n\n<p>If <code>Text</code> is thread-safe/immutable you could store <code>new Text(\"count\")</code> (and the other ones) in fields instead of constructing them on every call for equals as well as for <code>output.collect()</code>:</p>\n\n<blockquote>\n<pre><code> output.collect(new Text(\"sumSquared\"), new DoubleWritable(sumSquared));\n</code></pre>\n</blockquote></li>\n<li><p>It looks like that <code>sum</code> and <code>sumSquared</code> have the same implementation in the reducer. Is that a bug? If not you could create a method to eliminate the duplicated logic.</p></li>\n<li><p><code>sum</code>, <code>sumSquared</code>, <code>min</code>, <code>max</code> should be constants instead of magic numbers. There are used multiple times.</p></li>\n<li><p>Declaring variables before their usage with a bigger scope looks microoptimization:</p>\n\n<blockquote>\n<pre><code>String line;\nString[] tokens;\ndouble observation;\nwhile (scanner.hasNext()) {\n line = scanner.nextLine();\n tokens = line.split(\"\\\\s+\");\n observation = Double.parseDouble(tokens[1]);\n</code></pre>\n</blockquote>\n\n<p>It would be readable declaring them inside the loop. (<em>Effective Java, Second Edition, Item 45: Minimize the scope of local variables</em>)</p>\n\n<blockquote>\n<pre><code>String line;\nString[] words;\n\nline = br.readLine();\nwhile (line != null) {\n words = line.split(\"\\\\s+\");\n</code></pre>\n</blockquote>\n\n<p>also could be </p>\n\n<pre><code>String line = br.readLine();\nwhile (line != null) {\n final String[] words = line.split(\"\\\\s+\");\n</code></pre></li>\n<li><p>The reduce method contains a lot of similar structures. I'd consider using a function interface with some implementations:</p>\n\n<pre><code>public interface AggregateFunction {\n void addValue(double value);\n double getResult();\n}\n\npublic class MaxFunction implements AggregateFunction {\n private double max = Double.MAX_VALUE;\n\n @Override\n public void addValue(final double value) {\n max = Math.max(value, max);\n }\n\n @Override\n public double getResult() {\n return max;\n }\n}\n\npublic class SumFunction implements AggregateFunction {\n private double sum = 0.0;\n\n @Override\n public void addValue(final double value) {\n sum += value;\n }\n\n @Override\n public double getResult() {\n return sum;\n }\n}\n</code></pre>\n\n<p>The will reduce the <code>Reducer</code>: </p>\n\n<pre><code>public class Reduce extends MapReduceBase \n implements Reducer&lt;Text, DoubleWritable, Text, DoubleWritable&gt; {\n\n // assuming that Text is thread-safe/immutable\n private final Text countKey = new Text(\"count\");\n private final Text maxKey = new Text(\"max\");\n private final Text minKey = new Text(\"min\");\n private final Text sumKey = new Text(\"sum\");\n private final Text sumSquaredKey = new Text(\"sumSquared\");\n\n @Override\n public void reduce(Text key, Iterator&lt;DoubleWritable&gt; values,\n OutputCollector&lt;Text, DoubleWritable&gt; output, \n Reporter reporter) throws IOException {\n aggregate(\"count\", countKey, values, output, new SumFunction());\n aggregate(\"max\", maxKey, values, output, new MaxFunction());\n aggregate(\"min\", minKey, values, output, new MinFunction());\n aggregate(\"sum\", sumKey, values, output, new SumFunction());\n aggregate(\"sumSquared\", sumSquaredKey, values, output, \n new SumSquaredFunction());\n }\n}\n</code></pre></li>\n<li><blockquote>\n<pre><code>line = br.readLine();\nwhile (line != null) {\n words = line.split(\"\\\\s+\");\n\n switch (words[0]) {\n ...\n }\n line = br.readLine();\n}\n</code></pre>\n</blockquote>\n\n<p>I'd restructure the loop for better readability:</p>\n\n<pre><code>while (true) {\n final String line = br.readLine();\n if (line == null) {\n break;\n }\n final String[] words = line.split(\"\\\\s+\");\n ...\n}\n</code></pre></li>\n<li><blockquote>\n<pre><code>String line;\nline = \"avg\\t\" + String.valueOf(avg) + System.lineSeparator();\nbw.write(line);\nline = \"variance\\t\" + String.valueOf(variance) + System.lineSeparator();\nbw.write(line);\n</code></pre>\n</blockquote>\n\n<p>The <code>line</code> variable is used for multiple purposes. Using separate variable would make the code easier to read.</p>\n\n<pre><code>final String averageLine = \"avg\\t\" + String.valueOf(avg) + System.lineSeparator();\nbw.write(averageLine);\nfinal String varianceLine = \"variance\\t\" + String.valueOf(variance) + System.lineSeparator();\nbw.write(varianceLine);\n</code></pre>\n\n<p>Anyway, using a <code>PrintWriter</code> would be the best:</p>\n\n<pre><code>bw.printf(\"avg\\t%d%n\", avg);\nbw.printf(\"variance\\t%d%n\", variance);\n</code></pre></li>\n<li><p>Instead of commenting write a unit test for it:</p>\n\n<pre><code>// keep in alphabetical order or KABOOM!\n</code></pre>\n\n<p>It is much safer, especially if you use continuous integration or run unit test automatically on every build.</p></li>\n<li><p>There are unused imports:</p>\n\n<blockquote>\n<pre><code>import org.apache.hadoop.util.*;\n</code></pre>\n</blockquote>\n\n<p>It's cleaner omit them. Eclipse could do that for you with a keypress (Ctrl+Shift+O).</p></li>\n<li><blockquote>\n<pre><code>public class calcAll {\n</code></pre>\n</blockquote>\n\n<p>According to the <a href=\"http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-135099.html#367\" rel=\"nofollow noreferrer\">Code Conventions for the Java Programming Language</a> class names should start with uppercase letters. </p>\n\n<p>I'd try to give a more descriptive name, <code>SomethingStatistics</code> or something similar.</p>\n\n<ul>\n<li><a href=\"http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-135099.html#367\" rel=\"nofollow noreferrer\">Code Conventions for the Java Programming Language, 9 - Naming Conventions</a></li>\n<li><em>Effective Java, 2nd edition</em>, <em>Item 56: Adhere to generally accepted naming conventions</em></li>\n</ul></li>\n<li><p>Calling the mapper <code>Map</code> is confusing (since there is a <code>java.util.Map</code> too). I'd choose something more descriptive. The same is true for <code>Reduce</code>. </p>\n\n<p><a href=\"http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-135099.html#367\" rel=\"nofollow noreferrer\">Class names should be nouns</a>, not verbs, like <code>Map</code> or <code>Reduce</code>.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-03T18:59:26.200", "Id": "74794", "Score": "0", "body": "Your answer has lots of good points, I'll upvote it, but I cannot accept it until. I truly need to figure out the points I have expressed in the question. My main concern is the first point, the collection of the output is extremely fragile now.\nI'll comment on your points, though\n1. this can be taken care of when everything else works. It requires changing all DoubleWritable types to a more generic ObjectWritable, and then casting to either DoubleWritable or IntWritable\n2. I'll probably drop the splitting altogether if I can be sure I always receive one-liners as input" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-03T18:59:51.280", "Id": "74795", "Score": "0", "body": "3. Already tried that, but it breaks, it's probably related to how Hadoop stores the keys\n4. It's fine, min and max are used by an external sh file\n5. It's fine, I could put them in the same if\n6. OK\n7. I got the habit in my C++ days, I prefer not to trust the Java compiler for optimizations\n8. I don't get it, especially the \"aggregate\" call, I see no \"aggregate\" function in the reducer\n9. I prefer not to use break statements and instead make the exit condition clear\n10. OK, good one\n11. this is my biggest problem, I need to solve it, not just better advertise it\n12. OK\n13. OK\n14. OK, MyMapper" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-03T06:08:32.747", "Id": "43280", "ParentId": "42885", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T18:10:12.157", "Id": "42885", "Score": "8", "Tags": [ "java", "performance", "statistics", "hadoop", "mapreduce" ], "Title": "Calculate min, max, average, and variance on a large dataset" }
42885
<p>I have a <code>Queue</code> that needs to try to process when anything updates in it (add, remove or update).</p> <p>However, I don't want any of the callers to wait while the processing is happening (either for the processing to happen or while the processing is happening).</p> <p>This is what I came up with:</p> <pre><code>private static readonly SemaphoreSlim asyncLock = new SemaphoreSlim(1); private async void ProcessQueue() { // Lock this up so that one thread at a time can get through here. // Others will do an async await until it is their turn. await asyncLock.WaitAsync(); try { // Offload this to a background thread (so that the UI is not affected) var queueProcessingTask = Task.Run( () =&gt; { var processingStuck = false; while (myQueue.Count &gt;= 1 &amp;&amp; !processingStuck) { // Get the next item var queueItem = myQueue.Peek(); // Try to process this one. (ie DoStuff) processingStuck = ProcessQueueItem(queueItem); // If we processed successfully, then we can dequeue the item if (!processingStuck) myQueue.Dequeue(); } }); Task.WaitAll(queueProcessingTask); } finally { asyncLock.Release(); } } </code></pre> <p>Is my Thread and async handling going to ensure that only 1 queueItem at a time can ever be "in the works"?</p> <p>And will this avoid using resources from the UI thread?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T20:58:24.397", "Id": "73938", "Score": "3", "body": "Welcome to CR! Quick question: to the best of your knowledge, does the code work as expected? (just to make sure)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T21:02:45.857", "Id": "73942", "Score": "0", "body": "@Mat'sMug - I have not put it through all the paces. Should I delete it an re-post it when I am more confident of how well it works?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T21:07:00.457", "Id": "73945", "Score": "3", "body": "Peer reviews can find hidden bugs, that's not a problem. However *if there's a known problem with your code*, CR isn't the right place to get it fixed (that's SO's grounds ;) - if the code doesn't blow up and works as you'd expect it to work (to the best of your knowledge), then I wouldn't delete it. I've favorited this post, will come back to it later for sure ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T22:11:36.017", "Id": "73960", "Score": "1", "body": "What is the type/class of your myQueue item? Which thread (is it the UI thread) that's calling your ProcessQueue method? When behaviour do you want if ProcessQueueItem returns true?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T23:31:23.257", "Id": "73977", "Score": "0", "body": "@ChrisW - It is a custom type of mine. Has a few native types and a dictionary. The thread that calls it will likely be the UI Thread. (Though that is not guaranteed.) If ProcessQueueItems returns true then everything should stop. (The idea is that we would get user interaction that would update the item and cause another call of this method (that would succeed)).\nThe problem is that there are a lot of threads going on, and so this method could be called many times and I need to make sure that only one item is being worked on at once." } ]
[ { "body": "<blockquote>\n<p>The thread that calls it will likely be the UI Thread.</p>\n</blockquote>\n<p>You're invoking <code>Task.WaitAll</code> which waits for the processing to finish.</p>\n<p>However you said, &quot;... I don't want any of the callers to wait while the processing is happening (either for the processing to happen or while the processing is happening).&quot;</p>\n<p>Is this a contradiction?</p>\n<p>Instead of creating short-lived tasks as a local variable inside a semaphore, perhaps it would be better to:</p>\n<ul>\n<li>Create a single long-lived task (e.g. as a data member of your class)</li>\n<li>Wake up the task when you enqueue something or fix a ProcessQueueItems problem (perhaps by setting a event which the task is waiting on)</li>\n<li>Don't invoke Task.WaitAll until your program is shutting down</li>\n<li>Put an exception handler inside the task so that the (single, supposedly long-lived) task can't permanently fail if one ProcessQueueItem call throws an exception</li>\n</ul>\n<blockquote>\n<p>It is a custom type of mine. Has a few native types and a dictionary.</p>\n</blockquote>\n<p>It needs to be a type like <a href=\"http://msdn.microsoft.com/en-us/library/dd267265(v=vs.110).aspx\" rel=\"nofollow noreferrer\"><code>ConcurrentQueue&lt;T&gt;</code></a> because you have one thread (the task) dequeueing from it while (presumably) other threads are enqueueing on it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T23:56:17.287", "Id": "73982", "Score": "0", "body": "I am doing the WaitAll because I need my call to finish before I allow another caller to run the method. But, I see your point, I should be waiting async. That way the task can wait to release the `asyncLock` until the task finishes, but not block. About the `myQueue`, it is of Type `Queue`. I mistakenly thought you were asking about `queueItem`. I am not using ConcurrentQueue because the goal of my code is to ensure that more than one thread does not ever access the queue at once. Not for the safety of the queue, but because I end up printing things from the queue that MUST be in order." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T23:59:48.737", "Id": "73984", "Score": "0", "body": "If you want to use `Queue` instead of `ConcurrentQueue` then you need to use e.g. `lock` to make it thread-safe: acquire a lock before you dequeue from it, and acquire the same lock before you enqueue on it (to ensure that two different threads don't simultaneously enqueue and dequeue)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T00:02:43.850", "Id": "73986", "Score": "0", "body": "doesn't my `SemaphoreSlim asyncLock` do that? I put that in so that I could have a non-blocking lock." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T00:04:38.580", "Id": "73988", "Score": "0", "body": "What is the problem with two different threads doing an enqueue and a dequeue? (ie why would I need the same lock for enqueue and dequeue?)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T00:05:03.053", "Id": "73989", "Score": "0", "body": "Do you acquire the same semaphore before/while you call myQueue.Enqueue?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T00:07:04.923", "Id": "73990", "Score": "1", "body": "@Vaccano The problem is that Queue (unlike ConcurrentQueue) is not documented/guaranteed to be thread-safe: see the 'Thread Safety' section at the end of http://msdn.microsoft.com/en-us/library/7977ey2c(v=vs.110).aspx" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T00:09:01.070", "Id": "73991", "Score": "0", "body": "OK, seems like I should use ConcurrentQueue then. Thanks!" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2014-02-26T23:46:29.913", "Id": "42911", "ParentId": "42893", "Score": "5" } } ]
{ "AcceptedAnswerId": "42911", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T20:30:45.850", "Id": "42893", "Score": "10", "Tags": [ "c#", "task-parallel-library", "async-await" ], "Title": "Async Queue Processing" }
42893
<p>A JavaScript library that could be described as jQuery plus jQuery UI plus some features from Underscore.js</p> <p>Dojo Toolkit is an open source modular JavaScript library designed to ease the rapid development of cross-platform, JavaScript/Ajax-based applications and web sites. It is dual-licensed under the BSD License and the Academic Free License.</p> <p>Useful links:</p> <ul> <li><a href="http://dojotoolkit.org/" rel="nofollow">http://dojotoolkit.org/</a> <ul> <li><a href="http://dojotoolkit.org/documentation/" rel="nofollow">Quick start guide</a></li> <li><a href="http://dojotoolkit.org/reference-guide/" rel="nofollow">Reference guide</a></li> <li><a href="http://dojotoolkit.org/api/" rel="nofollow">API documentation</a></li> <li><a href="http://dojotoolkit.org/community/" rel="nofollow">Mailing list</a></li> <li><a href="http://demos.dojotoolkit.org/demos/" rel="nofollow">Demo</a></li> </ul></li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T20:32:13.753", "Id": "42894", "Score": "0", "Tags": null, "Title": null }
42894
A JavaScript library that could be described as jQuery plus jQuery UI plus some features from Underscore.js
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T20:32:13.753", "Id": "42895", "Score": "0", "Tags": null, "Title": null }
42895
<p>I have implemented a simulation program that runs LRU and another web caching algorithm called Sliding Window LFU. I want to compare them both in terms of the hit rate and their run time. SW-LFU works fine, but it takes FOREVER to run! I really can't figure why, since I used many tricks and ideas to keep the effort low and constant. </p> <p>NOTE: Ignore the <code>for</code> loops in the printing methods, since when I test the performance of the code I comment out the calls to the these methods in <code>main()</code>.</p> <p>Window LFU:</p> <pre><code>/////////////////////////////////////////////// // package declaration package algorithms; /////////////////////////////////////////////// // import of system classes and utilities import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; /////////////////////////////////////////////// // import of user-defined classes import requests.Request; /** * Sliding Window Least Frequently Used (SW-LFU) cache replacement algorithm * There are N items available for caching * These items are objects of type Request distinguished by their numeric ID (int), i.e. the field reqID * Cache is implemented as an array of size M and it is filled with objects of type Request * Sliding window is implemented as an array of size K and it is filled with requests for objects (again objects of type Request) distinguished by their reqID * "Sliding window" means actually a FIFO structure - requests inserted from one end and previous requests shifted by one index at each insertion; when max size is * reached, at every insertion of a request from one end another request is dropped from the other end. * Of course, a trick is used to accomplish this behaviour with a static array, as explained later * The replacement algorithm holds in the cache the items with the highest request count in the sliding window of the last K requests (score) * When a request for an item is inserted into the window, the score of that item is increased by 1 * When a request for an item is dropped from the window, the score of that item is decreased by 1 * The scores are stored in a reqID - score HashMap called scores * The cache is (partially) ordered regarding the score of the cached items, with the "most-valuable" item at the left end and the "least-valuable" item at the right end * Replacement takes place only if the requested item has at least equal score with the "least-valuable" cached item (i.e. right-most item in the cache array) * Otherwise, replacement will not take place (however, the request for that item is inserted into the window, thus the score of the requested item is increased by 1 - * in other words, at the next or after some requests, might be able to replace the cached item that now could not replace it!) * Since no ArrayList, LinkedList, or similar structure is used, which after each insertion would "shift" the previous items by one index, an int position counter is used * for both the cache (counter) and the window (winCounter) in order to achieve the desired behaviour (i.e. a cache ordered w.r.t. the scores of the cached items and a * window acting as a sliding window) * In case of a cache hit, the score of that cached item is increased by 1. Therefore, it might have become greater than or equal to the score of the next item at its * left.If this is the case, the cache is reordered with these two items exchanging position in the cache (and the relevant position counters) in order to maintain an * ordered cache w.r.t. the score of the cached items * Similarly, in case of dropping a request from the window, the score of that item is decreased by 1. Therefore, if that item is in the cache, the score of the next * item at its right might have become greater than its score. If this is the case, the cache is reordered with those two items exchanging position in the cache (and * the relevant position counters) in order to maintain an ordered cache w.r.t. the score of the cached items * In order to perform cache reordering in any of these two cases, we have to know the index (int ind) of the relevant item in the cache - then, the index of the next * item at its left or right is simply ind-1 or ind+1, respectively. In order to know at anytime this index, we store the position counter of the cached objects in a * reqID - counter HashMap called positions. That way, we avoid the use of a "for loop". * Moreover, we use a reqID - Boolean flag HashMap called inCache which puts a value true for the reqID of an object when this object is in the cache. That way, we * avoid using a "for loop" in the cache lookup method (to find whether the requested item is in the cache, i.e. cache hit, or not, i.e. cache miss). * Also we use a boolean flag isMoreThanOne to signify that the current cache size is &gt;1 (it could be avoided). * Finally, since we use simple, static, fixed-size arrays which don't have a size() method to get their current size, we use two int fields - a cacheSize and a * windowSize - which we increase or set appropriately in order to store the current cache or window size. That way, we avoid the use of a "for loop" and the increment * of a counter until the first null object is found. * @author The Higgs Boson * @version 5.0 */ public class WindowLFU { /////////////////////////////////////////////// // member attributes /** Max cache size */ private int M; /** Max window size */ private int K; /** Cache position counter */ private int counter; /** Window position counter */ private int winCounter; /** Current cache size */ private int cacheSize; /** Current window size */ private int windowSize; /** Flag for more than 1 items in cache */ private boolean isMoreThanOne; /** Cache */ private Request[] cache; /** Window */ private Request[] window; /** Map with boolean flags to check whether an item is in cache or not */ private Map&lt;Integer, Boolean&gt; inCache; /** Map of reqID (K) - Score (V) */ private Map&lt;Integer, Integer&gt; scores; /** Map of positions in the cache */ private Map&lt;Integer, Integer&gt; positions; /** Logging Utility */ private Logger logger = Logger.getLogger(WindowLFU.class.getSimpleName()); /////////////////////////////////////////////// // member methods /** * Constructor * @param M Max cache size * @param K Max request size * @param N Number of items */ public WindowLFU(int M, int K, int N) { // initialize max cache size and max window size this.M = M; this.K = K; // initialize counter and window counter counter = 0; winCounter = 0; // initialize current cache size and current window size cacheSize = 0; windowSize = 0; // initialize isMoreThanOne flag isMoreThanOne = false; // Allocate cache and window this.cache = new Request[M]; this.window = new Request[K]; // Allocate inCache, scores, and positions maps inCache = new HashMap&lt;Integer, Boolean&gt;(N); scores = new HashMap&lt;Integer, Integer&gt;(N); positions = new HashMap&lt;Integer, Integer&gt;(N); } /** Clear cache */ public void clearCache() { // fill in the cache with null objects Arrays.fill(cache, null); } /** Clear window */ public void clearWindow() { // clear window Arrays.fill(window, null); } /** Print cache contents */ public void printCache() { // set logging level logger.setLevel(Level.OFF); // string variable for holding textual representation of cache contents String str = ""; // scan the cache for(int i = 0; i &lt; this.cache.length; i++) { // if the item is not null if(this.cache[i] != null) { // assign reqID of item to the string variable str += (this.cache[i].reqID + " | "); } } // print cache contents logger.info("PRINT: CACHE: ReqID: " + str); } /** Print window contents */ public void printWindow() { // set logging level logger.setLevel(Level.OFF); // string variable for holding textual representation of window contents String str = ""; // scan the window for(int i = 0; i &lt; this.window.length; i++) { // if the request is not null if(this.window[i] != null) { // assign reqID of items to the string variable str += (this.window[i].reqID + " | "); } } // print window contents logger.info("PRINT: WINDOW: ReqID: " + str); } /** * Getter for current cache size * @return Current cache size */ public int getCacheSize() { // return the current cache size return cacheSize; } /** * Getter for current window size * @return Current window size */ public int getWindowSize() { // return the current window size return windowSize; } /** * Getter for score of item * @param request The item * @return The score of the item */ public int getScore(Request request) { // return score of item return this.scores.get(request.reqID); } /** Print score of cached items */ public void printScores() { // set logging level logger.setLevel(Level.OFF); // scan the cache for(int i = 0; i &lt; this.cache.length; i++) { // if the item is not null if(this.cache[i] != null) { // print reqIDs and scores logger.info("PRINT: SCORES: ReqID: " + this.cache[i].reqID + " | " + "Score: " + getScore(this.cache[i])); } } } /** * Cache insertion operation * @param request The requested item that is inserted into the cache */ public void doCacheInsert(Request request) { // set logging level logger.setLevel(Level.OFF); // logger.info("TEST: CACHE SIZE: " + cacheSize()); // if this is the first item inserted into the cache if(cacheSize == 0) { // set counter counter = M-1; // test // logger.info("TEST: INSERTION: ReqID: " + request.reqID + " | " + "Counter: " + counter); // insert item at index counter this.cache[counter] = request; // increase cache size by 1 cacheSize += 1; // put position index into positions list this.positions.put(request.reqID, counter); } // if this is not the first item inserted into the cache else { //if the cache has not reached its max size if(cacheSize != this.cache.length) { // decrease counter by 1 counter -= 1; // test // logger.info("TEST: INSERTION: ReqID: " + request.reqID + " | " + "Counter: " + counter); // insert item at index counter this.cache[counter] = request; // put position index into positions list this.positions.put(request.reqID, counter); // set isMoreThanOne flag isMoreThanOne = true; // increase cache size by 1 cacheSize += 1; } // if the cache has reached its max size else { // set cache size to cache capacity cacheSize = M; // reset counter to M-1 counter = M-1; // test // logger.info("TEST: INSERTION: ReqID: " + request.reqID + " | " + "Counter: " + counter); // insert item at index counter this.cache[counter] = request; // put position index into positions list this.positions.put(request.reqID, counter); } } // activate flag for item in inCache map this.inCache.put(request.reqID, true); // print message logger.info("CACHE INSERT: The requested item with ID: " + request.reqID + " has been inserted into the cache at index: " + this.positions.get(request.reqID)); } /** * Increase score of item by 1 * @param request The item */ public void incScore(Request request) { // if the item is not in the score map if(!this.scores.containsKey(request.reqID)) { // increase its score to 1 and put the reqID-score pair to the scores map this.scores.put(request.reqID, 1); } // else else { // temp score value int reqCount = this.scores.get(request.reqID); // increase score by 1 reqCount += 1; // put the reqID-score pair to the winFreqs map this.scores.put(request.reqID, reqCount); } } /** * Decrease score of item by 1 * @param request */ public void decWinFreq(Request request) { // temp score value int reqCount = this.scores.get(request.reqID); // decrease score by 1 reqCount -= 1; // put the reqID-score pair to the winFreqs map this.scores.put(request.reqID, reqCount); } /** * Insertion of request in the window * Performs cache reordering due to eviction of a request from the cache, if required * @param request The request */ public void doWindowInsert(Request request) { // set logging level logger.setLevel(Level.OFF); // if this is the first request inserted into the window if(windowSize == 0) { // set window position counter winCounter = K-1; // insert request at index winCounter this.window[winCounter] = request; // increase the score of that item by 1 incScore(request); // increase window size by 1 windowSize += 1; // print message logger.info("WINDOW INSERTION: A request for the item with ID: " + request.reqID + " has been inserted into the window and the score of that item has been updated to: " + getScore(request)); } // if this is not the first request inserted into the window else { // if the window has not reached its capacity if(windowSize != this.window.length) { // decrease winCounter by 1 winCounter -= 1; // insert request at index winCounter this.window[winCounter] = request; // increase the score of that item by 1 incScore(request); // increase window size by 1 windowSize += 1; // print message logger.info("WINDOW INSERTION: A request for the item with ID: " + request.reqID + " has been inserted into the window and the score of that item has been updated to: " + getScore(request)); } // if the window has reached its capacity else { // set windowSize equal to window max size windowSize = K; // request to be removed from the window - right-most request in the window Request reqToBeRemoved = this.window[this.window.length-1]; // decrease the score of that item by 1 decWinFreq(reqToBeRemoved); // if winCounter becomes smaller than 0 if(winCounter &lt; 0) { // reset it to K-1 winCounter = K-1; // i.e. same effect as sliding window } // insert request at index winCounter this.window[winCounter] = request; // increase the score of that item by 1 incScore(request); // decrease winCounter by 1 winCounter -= 1; // print messages logger.info("WINDOW EVICTION: A request for the item with ID: " + reqToBeRemoved.reqID + " has been evicted from the window and the score of that item has been updated to: " + getScore(reqToBeRemoved)); logger.info("WINDOW INSERTION: A request for the item with ID: " + request.reqID + " has been inserted into the window and the score of that item has been updated to: " + getScore(request)); // check for cache reordering due to the eviction of a request from the window // if item reqToBeRemoved is in the cache and it is not the only item in the cache and it is not the right-most item if((this.inCache.get(reqToBeRemoved.reqID) == true) &amp;&amp; (isMoreThanOne == true) &amp;&amp; (!this.cache[this.cache.length-1].equals(reqToBeRemoved))) { // index of reqToBeRemoved in the cache int ind = positions.get(reqToBeRemoved.reqID); // index of item at its right int indRight = ind + 1; // item at its right Request itemRight = this.cache[indRight]; // if the score of itemRight is now greater than the score of reqToBeRemoved if(getScore(itemRight) &gt; getScore(reqToBeRemoved)) { // put reqToBeRemoved at index indRight this.cache[indRight] = reqToBeRemoved; // update its counter this.positions.put(reqToBeRemoved.reqID, indRight); // put itemRight at index ind this.cache[ind] = itemRight; // update its counter this.positions.put(itemRight.reqID, ind); // print messages logger.info("CACHE REORDERING DUE TO EVICTION OF A REQUEST FROM THE WINDOW"); logger.info("The following items with the following scores exchanged position in the cache"); logger.info("ReqID: " + reqToBeRemoved.reqID + " score: " + getScore(reqToBeRemoved)); logger.info("ReqID: " + itemRight.reqID + " score: " + getScore(itemRight)); // print cache printCache(); } } } } } /** * If the item is not in the inCache map, put it and set its value at false * @param request The item */ public void initInCache(Request request) { // if the item is not in the inCache map if(!this.inCache.containsKey(request.reqID)) { // insert it and set its value at false this.inCache.put(request.reqID, false); } } /** * Cache lookup operation - returns true if the requested item is in the cache (cache hit) * @param request The requested item * @return true in case of cache hit */ public boolean doCacheLookup(Request request) { // set logging level logger.setLevel(Level.OFF); // put the item in the inCache map if it is not there and set its value to false initInCache(request); // if the requested item is in the cache (cache hit) if(this.inCache.get(request.reqID) == true) { // print message logger.info("LOOKUP: CACHE HIT: The requested item with ID: " + request.reqID + " is in the cache"); // return true return true; } // else (cache miss) else { // print message logger.info("LOOKUP: CACHE MISS: The requested item with ID: " + request.reqID + " is NOT in the cache"); // return false return false; } } /** * Performs replacement if the score of the requested item is at least equal to the score of the least-valuable cached item * @param request The requested item */ public void doCacheReplace(Request request) { // set logging level logger.setLevel(Level.OFF); // item to be removed from the cache - right-most item in the cache array Request reqToBeRemoved = this.cache[this.cache.length-1]; // if the score of the requested item is at least equal to the score of reqToBeRemoved if(getScore(request) &gt;= getScore(reqToBeRemoved)) { // test // logger.info("TEST: REPLACEMENT: ReqID: " + reqToBeRemoved.reqID + " | " + "Counter: " + positions.get(reqToBeRemoved.reqID)); // replace reqToBeRemoved by the requested item doCacheInsert(request); // set the inCache flag of reqToBeRemoved to false this.inCache.put(reqToBeRemoved.reqID, false); // print messages logger.info("REPLACEMENT: Least-valuable cached item has ID: " + reqToBeRemoved.reqID + " and score: " + getScore(reqToBeRemoved)); logger.info("REPLACEMENT: Requested item has ID: " + request.reqID + " and score: " + getScore(request)); logger.info("REPLACEMENT: Requested item replaced least-valuable cached item"); } // else else { // print messages logger.info("REPLACEMENT: Least-valuable cached item has ID: " + reqToBeRemoved.reqID + " and score: " + getScore(reqToBeRemoved)); logger.info("REPLACEMENT: Requested item has ID: " + request.reqID + " and score: " + getScore(request)); logger.info("REPLACEMENT: No replacement will take place"); } } /** * Performs cache reordering due to cache hit, if required * @param request The requested item */ public void doCacheReorderCacheHit(Request request) { // set logging level logger.setLevel(Level.OFF); // if the cache has more than one items and the requested item is not the left-most cached item if((isMoreThanOne == true) &amp;&amp; (!this.cache[this.cache.length - cacheSize].equals(request))) { // test // logger.info("TEST: REORDER DUE TO CACHE HIT: ReqID: " + request.reqID + " | " + "Counter: " + positions.get(request.reqID)); // index of requested item int ind = this.positions.get(request.reqID); // index of item at its left int indLeft = ind-1; // item at its left Request itemLeft = this.cache[indLeft]; // if the score of the requested item is at least equal to the score of itemLeft if(getScore(request) &gt;= getScore(itemLeft)) { // put requested item at index indLeft this.cache[indLeft] = request; // update its counter this.positions.put(request.reqID, indLeft); // put itemLeft at index ind this.cache[ind] = itemLeft; // update its counter this.positions.put(itemLeft.reqID, ind); // print messages logger.info("CACHE REORDERING DUE TO CACHE HIT"); logger.info("The following items with the following scores exchanged position in the cache"); logger.info("ReqID: " + request.reqID + " score: " + getScore(request)); logger.info("ReqID: " + itemLeft.reqID + " score: " + getScore(itemLeft)); // print cache printCache(); } } } } </code></pre> <p>Code for LRU for comparison:</p> <pre><code>////////////////////////////////////////////////////// // package declaration package algorithms; ////////////////////////////////////////////////////// // import of system classes and utilities import java.util.ArrayDeque; import java.util.Deque; import java.util.HashMap; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; ////////////////////////////////////////////////////// // import of user-defined classes import requests.Request; /** * Least Recently Used (LRU) cache replacement algorithm * Cache is as a doubly-ended queueu implemented as an Array (ArrayDeque) of size M * Insertion of objects from the left of the list, eviction at the right * When the cache has reached its capacity and upon a cache miss, the right-most cached item * (LRU item) is evicted from the cache, i.e. the cache holds the most recently requested items * Upon a cache hit, cache reordering might take place with the relevant item moved at the beginning of * the cache list if it is not already there * @author The Higgs Boson * @version 5.0 */ public class LRU { ////////////////////////////////////////////////////// // member attributes /** Max cache size */ private int M; /** LRU cache */ private Deque&lt;Request&gt; cacheLRU = new ArrayDeque&lt;Request&gt;(M); /** Map inCache */ private Map&lt;Integer, Boolean&gt; inCache; /** Logging utility */ private Logger logger = Logger.getLogger(LRU.class.getSimpleName()); ////////////////////////////////////////////////////// // member methods /** * Constructor * @param M Max cache size */ public LRU(int M, int N) { // initialize max cache size this.M = M; // Allocate inCache map inCache = new HashMap&lt;Integer, Boolean&gt;(N); } /** Clear cacheLRU */ public void clearCacheLRU() { // clear cacheLRU this.cacheLRU.clear(); } /** * Getter for current cacheLRU size * @return cacheLRU.size() Current cacheLRU size */ public int getCacheLRUSize() { // return current cacheLRU size return this.cacheLRU.size(); } /** Print cacheLRU contents */ public void printCacheLRU() { // set logging level logger.setLevel(Level.OFF); // String variable for holding textual representation of cacheLRU contents String str = ""; // scan cacheLRU for(Request r : this.cacheLRU) { // take the reqID of cached items and put them into string variable str str += (r.reqID + " | "); } // print cacheLRU contents logger.info("PRINT: Cache contents: " + str); } /** * If the item is not in inCache map, insert it and put its value at false * @param request The item */ public void initInCache(Request request) { // if the item is not in the inCache map if(!this.inCache.containsKey(request.reqID)) { // insert it and set its value at false this.inCache.put(request.reqID, false); } } /** * Cache lookup operation * @param request The requested item * @return true If the requested item is found in the cache (cache hit) */ public boolean doLookupCacheLRU(Request request) { // set logging level logger.setLevel(Level.OFF); // init inCache initInCache(request); // if the requested item is in cache (cache hit) if(this.inCache.get(request.reqID) == true) { // cache reordering due to cache hit in two steps // 1. remove relevant cached item from the cache cacheLRU.remove(request); // 2. add this item to the end of the cache cacheLRU.add(request); // print message logger.info("LOOKUP: CACHE HIT: The requested item with reqID: " + request.reqID + " is already stored in the cache"); // return true return true; } // else (cache miss) else { // print message logger.info("LOOKUP: CACHE MISS: The requested item with reqID: " + request.reqID + " is not stored in the cache"); // return false return false; } } /** * Cache insertion operation * @param request The requested item */ public void doInsertCacheLRU(Request request) { // set logging level logger.setLevel(Level.OFF); // add the requested item at the end of the cache list this.cacheLRU.add(request); // set its flag to true this.inCache.put(request.reqID, true); // print message logger.info("INSERTION: The requested item with reqID: " + request.reqID + " has been inserted into the cache"); } /** * Cache replacement operation * @param request The requested item */ public void doReplacementCacheLRU(Request request) { // set logging level logger.setLevel(Level.OFF); // print message logger.info("The cache has reached its capacity"); // item to be evicted Request reqToBeRemoved = this.cacheLRU.getFirst(); // evict the left-most cached item from the cache this.cacheLRU.removeFirst(); // set its flag to false this.inCache.put(reqToBeRemoved.reqID, false); // insert new requested item at the end of the cache list this.cacheLRU.add(request); // set its flag to true this.inCache.put(request.reqID, true); // print message logger.info("REPLACEMENT: The requested item with reqID: " + request.reqID + " replaced the LRU item with reqID: " + reqToBeRemoved.reqID); } } </code></pre> <p>Just for the sake of comparison, with this configuration, i.e.:</p> <blockquote> <pre class="lang-none prettyprint-override"><code>Number of items: N = 1,000,000 Number of requests: numR = 2,000,000 Cache size: M = 10,000 </code></pre> </blockquote> <p>LRU takes about 15 seconds.</p> <p>WindowLFU, on the other hand, with the same configuration and a window size K = 2,000,000, after 15 seconds has only processed about 3,000 out of the 2,000,000 requests! This doesn't seem to change when I use a smaller window size (e.g. K = 100,000). </p>
[]
[ { "body": "<p>I appreciate that this is non-trivial code and I can see why you would like to have lots of comments, but code like below is probably taking it a bit too far:</p>\n\n<pre><code>// else\nelse {\n\n// increase score by 1\nreqCount += 1;\n</code></pre>\n\n<p>Especially in the second example, if you need to tell an observer that <code>reqCount</code> is in fact a score, call the variable \"score\".</p>\n\n<p>Instead of your <code>inCache Map</code>, I think a <code>Set&lt;Integer&gt;</code> is a better fit. Doing this will also have the benefit of not being a memory leak. (Currently you can end up adding an arbitrary number of entried into <code>inCache</code>, but you never remove any entries.)</p>\n\n<p>I don't have any complete explanation for why your LFU code is so much slower, but when measuring, you should comment out all your logging statements. Setting log level to \"off\" is a good start, but the argument to the log statement is still evalued, so you concatenate strings and do method calls there.</p>\n\n<p>Also, your LFU code relies on <code>Request.equals(Object)</code>. If this is an expensive operation it will naturally slow thing down. You didn't supply the code for Request, so I can't tell if this is a problem or not.</p>\n\n<p>Edit:\nWhen there are significant performance hits, like the one you've run into, it is fairly uncommon that the problem is that you do a HashMap lookup too much, or instantiate an extra object, or similar things. Instead, keep a look out for excessive concatenation of Strings, IO operations, looping, or the use of the wrong datastructures (such as doing list.get(int) on a LinkedList). To be honest, when looking at your code, my best guess was that the Request.equals method was the culprit, so now I'm a bit at a loss.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T22:33:43.530", "Id": "73964", "Score": "0", "body": "Regarding the `Set<Integer>`, I need a mapping between reqID and inCache flag, therefore I don't understand how I can use a set instead of a map. Regarding commecting out the logging statements, I was not aware of that! Finally, the overriding of the equals method was really simple: public boolean equals(Object obj) { Request req = (Request) obj; if(this.reqID == req.reqID) { return true; } return false; }" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T22:35:01.847", "Id": "73965", "Score": "0", "body": "Sorry about the formatting, I could not find how to add code blocks in comments." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T22:45:40.500", "Id": "73966", "Score": "0", "body": "My idea regarding the Set is that reqId in cache is also in the Set. Then you can use inCache.contains(int) to get information on if the request is in cache or not." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T22:49:54.283", "Id": "73967", "Score": "0", "body": "Oh, I see, yes that makes perfect sense! Thank you!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T23:07:06.510", "Id": "73972", "Score": "0", "body": "I have one idea to get rid of the remaining maps too. If instead of a positions map and a scores map I use somehow a position field and a score field in the Request class, as I use a reqID field, then there will be no need to have these maps with N key-value pairs, right? This might give a significant performance boost. Do you find this idea reasonable? What's your thoughts about it? EDIT: And similarly an inCache boolean field to get rid of the Set too!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T07:09:16.433", "Id": "74025", "Score": "0", "body": "Adding score and position to the Request class might make sense from a performance point of view, but then the Request class has more than one responsibility (representing a request AND managing cache state), so I'd recommend against it. However you could create something like a CachedItemState class, containing position and score, and having a single map, mapping reqId to CachedItemState. That makes sense both for performance and readability. You can use containsKey on the map, instead of using the inCache Set. Also regarding hunting for performance, see my edit." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T22:08:18.753", "Id": "42904", "ParentId": "42898", "Score": "4" } }, { "body": "<p>You didn't provide much information about how you conducted your comparative stress tests wrt. LFU vs. LRU, so I'll assume you simply forced random access requests over the possible set of keys (i.e., your <code>request.reqID</code>, as I understand it).</p>\n\n<p>If so, what I observed with my own implementation is that the LRU eviction and replacement strategy will typically outperforms LFU for such requests that map equiprobable frequencies over the set of accessed keys.</p>\n\n<p>Conversely, LFU starts to perform better when there is more disparity / imbalance in the distribution of the access frequencies of the keys, e.g., say, when some requested keys have high use counts, and other requested keys are accessed less (or much less) frequently. Heuristically, this is for instance the case when your domain model has, e.g., say, keys mapping onto \"very popular vs. little popular\" categories, etc.</p>\n\n<p>As I found out, LFU's bookkeeping of the use counts (or frequencies, or whatever we call it) incurs a significant overhead compared to that of the more straightforward LRU/MRU algorithm and data structure, better suited to cope with equiprobable access scenarios.</p>\n\n<p>Although my implementation of LRU is essentially equivalent to yours, AFAICT, my LFU isn't, however. Instead of SW-LFU, I baked my own, where I keep track of the use counts (or frequencies) in dictionaries indexed by the logarithm base 2 of the use counts.</p>\n\n<p>I did so in order to minimize the use count bookkeeping overhead / fragmentation, in the pathological case for LFU where key1 is accessed once, key2 twice, key3 three times, key4 four times, etc (which would make the evictable frequency collection grow as large as the set of distinct keys, up to the cache capacity M).</p>\n\n<p>Here are the relevant bits, you may find interesting</p>\n\n<p>(just the helper class used internally by the LFU cache implementation for the bookkeeping of the keys use counts)</p>\n\n<pre><code>public class LfuEvictableCollection&lt;TKey&gt; : IUseTrackingCollection&lt;TKey&gt;\n{\n internal sealed class KeyUse\n {\n internal const int None = -1;\n\n private long value;\n\n private int msb = None;\n\n internal int Increment()\n {\n var mask = 1L &lt;&lt; (msb + 1);\n if ((++value &amp; mask) == mask)\n {\n msb++;\n }\n return msb;\n }\n\n internal long Count { get { return value; } }\n\n // Reflects the logarithm base 2 of the use count\n internal int Msb { get { return msb; } }\n }\n\n private IDictionary&lt;TKey, KeyUse&gt; uses;\n\n // We dispatch used keys in use counts partitions, indexed by\n // the logarithm base 2 of the keys' use counts; thus,\n // the single set of keys which have been accessed only once will be in keys[0];\n // the (up to) 2 sets of keys which have been accessed 2 to 3 times, in keys[1];\n // the (up to) 4 sets of keys which have been accessed 4 to 7 times, in keys[2];\n // the (up to) 8 sets of keys which have been accessed 8 to 15 times, in keys[3];\n // the (up to) 16 sets of keys which have been accessed 16 to 31 times, in keys[4];\n // etc, etc.\n private IDictionary&lt;int, HashSet&lt;TKey&gt;&gt; keys;\n\n public LfuEvictableCollection()\n : this(0)\n {\n }\n\n public LfuEvictableCollection(int capacity)\n {\n uses = new Dictionary&lt;TKey, KeyUse&gt;(capacity);\n keys = new Dictionary&lt;int, HashSet&lt;TKey&gt;&gt;(Msb(long.MaxValue) + 1);\n Initialize();\n }\n\n // Get the most significant bit (index) of n, assumed positive\n // (for long.MaxValue, signed 64-bit integer maximum, this is 62)\n // or -1, if n is zero\n private static int Msb(long n)\n {\n if (n &gt; 0)\n {\n var max = long.MaxValue;\n var msb = 0;\n while (n &lt;= max) max /= 2;\n max += 1;\n while (0 &lt; (max /= 2)) msb++;\n return msb;\n }\n return KeyUse.None;\n }\n\n // Get the logarithm base 2 of the least often used keys' use count,\n // or -1 if no keys have ever been used\n private int Min()\n {\n var msb = 0;\n while (msb &lt; keys.Count &amp;&amp; keys[msb].Count &lt; 1)\n {\n msb++;\n }\n return msb &lt; keys.Count ? msb : KeyUse.None;\n }\n\n protected virtual void Initialize()\n {\n TotalUseCount = 0;\n keys.Clear();\n uses.Clear();\n }\n\n #region IUseTrackingCollection&lt;TKey&gt; implementation\n public void Use(TKey key)\n {\n var use = uses[key];\n var last = use.Msb;\n var next = use.Increment();\n TotalUseCount++;\n if (last &lt; next)\n {\n if (last &gt; KeyUse.None)\n {\n keys[last].Remove(key);\n }\n if (!keys.ContainsKey(next))\n {\n keys.Add(next, new HashSet&lt;TKey&gt;());\n }\n keys[next].Add(key);\n }\n }\n\n public IEnumerable&lt;TKey&gt; GetLeastFrequentlyUsed(int maxCount)\n {\n if (maxCount &lt;= 0)\n {\n throw new ArgumentOutOfRangeException(\"maxCount\", \"must be strictly greater than zero\");\n }\n var msb = Min();\n if (msb &gt; KeyUse.None)\n {\n while (maxCount &gt; 0 &amp;&amp; msb &lt; this.keys.Count)\n {\n var keys = this.keys[msb];\n foreach (var key in keys)\n {\n maxCount--;\n yield return key;\n }\n msb++;\n }\n }\n if (maxCount &gt; 0)\n {\n foreach (var key in this.uses.Keys)\n {\n if (maxCount &gt; 0)\n {\n maxCount--;\n yield return key;\n }\n else\n {\n break;\n }\n }\n }\n }\n\n public long TotalUseCount { get; private set; }\n #endregion\n\n #region ICollection&lt;TKey&gt; implementation\n public void Add(TKey key)\n {\n var use = new KeyUse();\n uses.Add(key, use);\n }\n\n public void Clear()\n {\n Initialize();\n }\n\n public bool Contains(TKey key)\n {\n return uses.ContainsKey(key);\n }\n\n public void CopyTo(TKey[] array, int index)\n {\n var keys = uses.Keys.ToArray();\n keys.CopyTo(array, index);\n }\n\n public bool Remove(TKey key)\n {\n KeyUse use;\n if (uses.TryGetValue(key, out use))\n {\n var msb = use.Msb;\n TotalUseCount -= use.Count;\n if (keys.ContainsKey(msb))\n {\n keys[msb].Remove(key);\n }\n uses.Remove(key);\n return true;\n }\n return false;\n }\n\n public int Count\n {\n get\n {\n return uses.Count;\n }\n }\n\n public bool IsReadOnly\n {\n get\n {\n return false;\n }\n }\n #endregion\n\n #region IEnumerable&lt;TKey&gt; implementation\n public IEnumerator&lt;TKey&gt; GetEnumerator()\n {\n return ((IEnumerable&lt;TKey&gt;)uses.Keys).GetEnumerator();\n }\n #endregion\n\n #region IEnumerable implementation\n System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()\n {\n return GetEnumerator();\n }\n #endregion\n}\n</code></pre>\n\n<p>(Yes, I know this is C# and not Java but I believe it is relatively straightforward, and shouldn't be too difficult to port to Java, if you so wish)</p>\n\n<p>Performance figures-wise, on an Intel Duo Core 2 @ 2.9 Ghz desktop box running Windows 7 64bit + .NET 4.0, and after I adapt my test to the cache size (10,000 slots) and working set (1,000,000 items) that you mentioned</p>\n\n<p>-- only with a greater number of requests, 5 times fold (i.e., 10 millions, instead of 2 millions) --</p>\n\n<p>I observe:</p>\n\n<pre><code>For LRU:\nCache size = 10,000\nNumber of items = 1,000,000\nNumber of requests = 10,000,000\nTime elapsed: ~ 10 seconds\n\nFor LFU:\nCache size = 10,000\nNumber of items = 1,000,000\nNumber of requests = 10,000,000\nTime elapsed: ~ 14 seconds\n</code></pre>\n\n<p>(again, in the test case I assumed of an equiprobable distribution of frequencies over the set of accessed keys, more LRU-friendly than it is to LFU)</p>\n\n<p>Because my generic cache library is quite involved and opinionated, I can't post the full source code here for obvious readability reasons, but it is browsable <a href=\"https://github.com/ysharplanguage/GenericMemoryCache\" rel=\"nofollow\">here</a>.</p>\n\n<p>Hope this helps,</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-31T00:06:20.803", "Id": "98637", "ParentId": "42898", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T21:02:45.873", "Id": "42898", "Score": "3", "Tags": [ "java", "performance", "hash-map", "cache", "complexity" ], "Title": "LFU-like web caching replacement algorithm" }
42898
<p>The task (<a href="https://cw.felk.cvut.cz/courses/a4b33alg/task.php?task=orcharddivision" rel="nofollow">from this site</a>) is to create a program that will solve a problem where a matrix (size n * n), which contains integers, is to be divided into four parts, the sums of which are as close to each other as possible. They have to be divided left to right all the way and those parts (top/bottom), can be divided without the imaginary line touching. The output is the difference between the part with the largerst sum and the one with the smallest.</p> <pre><code>public class Main { Scanner scan = new Scanner(System.in); int [][] area_values; int size; int max_co; int y_divide; int x_divide_top; int x_divide_bottom; int left_top; int right_top; int left_bottom; int right_bottom; /** * @param args the command line arguments */ public static void main(String[] args) { Main main = new Main(); main.read(); main.division(); main.result(); } void read() { size = scan.nextInt(); arrayLoad(); max_co = size - 1; } void arrayLoad() { area_values = new int [size][size]; for (int i = 0; i &lt; size; i++) { for (int j = 0; j &lt; size; j++) { add(scan.nextInt(),i,j); } } } void add(int num, int x, int y) { for (int i = x; i &lt; size; i++) { for (int j = y; j &lt; size; j++) { area_values[i][j] += num; } } } int block_value(int by, int bx, int ey, int ex) { int value = area_values[ex][ey]; if (bx == 0 &amp;&amp; by ==0) {} else if (bx != 0 &amp;&amp; by !=0) { value -= area_values[bx-1][ey]; value -= area_values[ex][by-1]; value += area_values[bx-1][by-1]; } else if (bx == 0) { value -= area_values[ex][by-1]; } else if (by == 0) { value -= area_values[bx-1][ey]; } return value; } void division() { east_to_west(); top_division(); bottom_division(); } void top_division() { int left; int right; int min_Dif = Integer.MAX_VALUE; int dif; for (int i = 0; i &lt; max_co; i++) { left = block_value(0,0,i,y_divide); right = block_value(i+1,0,max_co,y_divide); dif = Math.abs(left-right); if (dif &lt; min_Dif) { min_Dif = dif; left_top = left; right_top = right; } } } void bottom_division() { int left; int right; int min_Dif = Integer.MAX_VALUE; int dif; for (int i = 0; i &lt; max_co; i++) { left = block_value(0,y_divide+1,i,max_co); right = block_value(i+1,y_divide+1,max_co,max_co); dif = Math.abs(left-right); if (dif &lt; min_Dif) { min_Dif = dif; left_bottom = left; right_bottom = right; } } } void east_to_west() { int top; int bottom; int min_Dif = Integer.MAX_VALUE; int dif; int y_div = 1; for (int i = 0; i &lt; max_co; i++) { top = block_value(0,0,max_co,i); bottom = block_value(0,i+1,max_co,max_co); dif = Math.abs(top-bottom); if (dif &lt; min_Dif) { min_Dif = dif; y_div = i; } } y_divide = y_div; } void result() { int min_top = Math.min(left_top, right_top); int min_bottom = Math.min(left_bottom, right_bottom); int min = Math.min(min_top, min_bottom); int max_top = Math.max(left_top, right_top); int max_bottom = Math.max(left_bottom, right_bottom); int max = Math.max(max_top, max_bottom); int result = Math.abs(max-min); System.out.println(result); } } </code></pre> <p>It works just fine, but I always exceed the time limit by fractions of a second. Is there any way of speeding this up? I was told about using <code>bufferedReader</code>, instead of <code>Scanner</code>, but how would I do that? Some of the input comes from a keyboard, number by number, and some from a file.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T21:24:05.417", "Id": "73947", "Score": "0", "body": "Could you include the link to the problem?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T21:25:43.173", "Id": "73949", "Score": "1", "body": "I am not sure you will be able to access it.\nhttps://cw.felk.cvut.cz/courses/a4b33alg/task.php?task=orcharddivision" } ]
[ { "body": "<p>You definitely should use a <code>BufferedReader</code>. Take a look at the <a href=\"https://github.com/Abrackadabra/omni/blob/master/coding/java/src/io/InputReader.java\" rel=\"nofollow\">class</a> I use when I am solving problems of this kind.</p>\n\n<p>Besides, your reading subroutine works in O(n<sup>4</sup>), which, for <em>n</em> about 10<sup>3</sup>, is a bit too much. I think your program just gets killed after it exceeds the time limit, leaving you thinking that you are very close.</p>\n\n<p>You seem to want to construct a matrix of patrial sums. Can you think of a way to construct in it O(n<sup>2</sup>)?</p>\n\n<p>Also, your solution is not correct. Consider a test</p>\n\n<pre><code>4\n0 4 0 0\n2 0 0 0 \n2 0 0 0\n0 2 0 0\n</code></pre>\n\n<p>Your solution outputs 4, when the correct answer is obviously 2.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T21:50:54.493", "Id": "73956", "Score": "0", "body": "Thanks, I will try to come up with an edit for the reading routine.\nI will also look into my solution, but I believe it is correct, since all of the sets of data it works thorugh in time (up to around 400x400) come up with the correct output number." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T22:08:29.707", "Id": "73958", "Score": "0", "body": "Yes, your test makes it fail and I now see why. It does not see the benefit of splitting it after the second line, because it sees no difference between 6,4 and 4,6, therefore making the wrong decision.\nThe fact that if given enough time it comes to the correct conclusion in all of the test data is probably due to the fact that the school chooses data, where the first step does not have more than one solution. But I will definetly try to do it anyways." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T22:15:56.300", "Id": "73961", "Score": "0", "body": "That's kinda sad. You should approach your professor and ask him to strengthen the tests." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T22:18:17.593", "Id": "73962", "Score": "0", "body": "Or they just missed it. Also, most of the people at our school are just being introduced to programming." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T21:41:24.360", "Id": "42902", "ParentId": "42900", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T21:19:23.867", "Id": "42900", "Score": "5", "Tags": [ "java", "performance", "matrix" ], "Title": "Orchard Partitioning in to close-to-equal sectors" }
42900
<p>I recieve a number n and then recieve n*n integers, representing a matrix, or an array of [n][n]. I want to create an array [n][n], where every cell contains the sum of all cells "left and above" from the original array, while not creating the array, just using the values. For example, the cell [5][7], will contain the sum of the block [0][0] to [5][7] out of the original array.</p> <p>I seriously need to simplify or speed up my code.</p> <pre><code>void read() { size = scan.nextInt(); arrayLoad(); } void arrayLoad() { area_values = new int [size][size]; for (int i = 0; i &lt; size; i++) { for (int j = 0; j &lt; size; j++) { add(scan.nextInt(),i,j); } } } void add(int num, int x, int y) { for (int i = x; i &lt; size; i++) { for (int j = y; j &lt; size; j++) { area_values[i][j] += num; } } } </code></pre> <p>This is O(n^4), which, as you may be able to tell, is not exactly easy for n 4+ digits.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T23:04:08.737", "Id": "73970", "Score": "0", "body": "The first array in input using the scanner. The first number is the size of the array, which will be input." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T23:06:30.633", "Id": "73971", "Score": "0", "body": "Yes, but you say: `So, I have an array [n][n], which contains integers. I want to create a new array of the same size` ... I only see one array... are you building the array at the same times as adding it up?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T23:33:38.673", "Id": "73978", "Score": "0", "body": "I updated the question. I hope you understand my meaning now." } ]
[ { "body": "<p>This is an interesting problem. I think your solution will be possible and much, much faster if you <a href=\"http://en.wikipedia.org/wiki/Memoization\">use memoization</a>. This is the process where you remember your previous calculations and reuse them in your current calculations.</p>\n\n<p>So, for example, suppose you process your array row-by-row.... if your input 2D array is:</p>\n\n<pre><code>1 1 1 1 1 1 1\n1 1 1 1 1 1 1\n1 1 1 1 1 1 1\n1 1 1 1 1 1 1\n1 1 1 1 1 1 1\n1 1 1 1 1 1 1\n1 1 1 1 1 1 1\n</code></pre>\n\n<p>And we were now processing the second row, and fourth column, our current result would look like (our current position is marked with a <code>?</code>):</p>\n\n<pre><code>1 2 3 4 5 6 7\n2 4 6 ? 0 0 0\n0 0 0 0 0 0 0\n0 0 0 0 0 0 0\n0 0 0 0 0 0 0\n0 0 0 0 0 0 0\n0 0 0 0 0 0 0\n</code></pre>\n\n<p>Now, at that position, we know that the value will be 8 because we are human, and can see that. The best algorithm on the computer though, to get that 8, is that we can split the data we know in to 4 areas....</p>\n\n<p>Consider the input data again (I have marked our spot with the parenthesis):</p>\n\n<pre><code>1 1 1 1 1 1 1\n1 1 1(1)1 1 1\n1 1 1 1 1 1 1\n1 1 1 1 1 1 1\n1 1 1 1 1 1 1\n1 1 1 1 1 1 1\n1 1 1 1 1 1 1\n</code></pre>\n\n<p>The 4 areas that we can think of as special are:</p>\n\n<ol>\n<li>the value we are processing right now (the value <code>1</code>)</li>\n<li>the column above the us (contains the values <code>[1]</code>)</li>\n<li>the row we have processed so far (contains the values <code>[1, 1, 1]</code>)</li>\n<li>the <strong>rectangle</strong> above-left of where we are so far (contains the value <code>[1, 1, 1]</code> as well)</li>\n</ol>\n\n<p>Now, what is the sum of the values in the rectangle? We know that, because we have our grid right now which looks like:</p>\n\n<pre><code>1 2(3)4 5 6 7\n2 4 6 ? 0 0 0\n0 0 0 0 0 0 0\n0 0 0 0 0 0 0\n0 0 0 0 0 0 0\n0 0 0 0 0 0 0\n0 0 0 0 0 0 0\n</code></pre>\n\n<p>So, the rectangle from (0,0) to (0,2) has the sum <code>3</code> which has already been calculated (and which I have marked with parenthesis).</p>\n\n<p>We have also calculated the sum of the data in the row to the left of us... look at the grid again:</p>\n\n<pre><code>1 2(3)4 5 6 7\n2 4(6)? 0 0 0\n0 0 0 0 0 0 0\n0 0 0 0 0 0 0\n0 0 0 0 0 0 0\n0 0 0 0 0 0 0\n0 0 0 0 0 0 0\n</code></pre>\n\n<p>The sum of the values in the row to the left is the difference between the rectangle above left, and the rectangle plain-left, or <code>6 - 3</code> == <code>3</code>.</p>\n\n<p>Similarly, the sum of the values in the column above us, is the sum of the rectangle above us, less the rectangle above-left of us.</p>\n\n<p>So, for any position in the solution matrix, the solution-sum of the values is:</p>\n\n<ol>\n<li>the value at this point</li>\n<li>plus the sum of all values above-left of us</li>\n<li>plus the sum of all values above us</li>\n<li>plus the sum of all values to the left.</li>\n</ol>\n\n<p>Using a more convenient input format than the scanner, this can all be done in a single loop....</p>\n\n<pre><code>int[][] sumAboveLeft(int[] datasource) {\n if (datasource == null || datasource.length == 0 || datasource.length != datasource[0] * datasource[0] + 1) {\n throw new IllegalArgumentException();\n }\n // first value in the source data is the matriz size\n final int size = datasource[0];\n // because the first value is the size, we expect the loop limit to be unusual.\n final int limit = datasource.length - 1;\n\n int[][] result = new int[size][size];\n\n for (int i = 0; i &lt; limit; i++) {\n // convert the linnear/flat address to a row/column\n int row = i / size;\n int col = i % size;\n\n // rectangle-sum above us\n int abovesum = row &gt; 0 ? result[row - 1][col] : 0;\n // rectangle-sum to left of us\n int leftsum = col &gt; 0 ? result[row][col - 1] : 0;\n // rectangle-sum above-left of us.\n int aboveleftsum = (col &gt; 0 &amp;&amp; row &gt; 0) ? result[row - 1][col - 1] : 0;\n // our value at this point (note the index+1 offset because the first value is the size)\n int val = datasource[i + 1];\n // the sum here is\n // the value here\n // plus above-left-rectangle-sum\n // plus above-column-sum\n // plus left-row-sum\n result[row][col] = val\n + aboveleftsum\n + (leftsum - aboveleftsum)\n + (abovesum - aboveleftsum);\n }\n return result;\n\n}\n</code></pre>\n\n<p>I have put a lot of comments in there for you...</p>\n\n<p>I have also tested it with:</p>\n\n<pre><code>public static void main(String[] args) {\n System.out.println(Arrays.deepToString(sumAboveLeft(new int[]{\n 7,\n 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1,\n })));\n}\n</code></pre>\n\n<p>So, the process can be done in <em>O(n)</em>, where n is the number of members in the matrix.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T23:55:02.933", "Id": "73981", "Score": "1", "body": "Thank you so much! I was stuck for a long time and you have made it so clear. Thank you for taking the time to educate a newbie, such as myself." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T23:46:56.403", "Id": "42912", "ParentId": "42906", "Score": "12" } } ]
{ "AcceptedAnswerId": "42912", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T22:47:26.493", "Id": "42906", "Score": "3", "Tags": [ "java" ], "Title": "Partial sums of two dimensional array" }
42906
<p>I have written this class that will write a <code>JTable</code> to a tab delimited file so that it can be opened in Excel. It works great, but is there any way to make it better or have it directly open in Excel without having to go through the import screens all of the time? How can I tidy up this code to work or operate more efficiently?</p> <pre><code>import java.io.File; import java.io.FileWriter; import java.io.IOException; import javax.swing.JTable; import javax.swing.table.TableModel; public class excel { String columnNames[] = { "Column 1", "Column 2", "Column 3" }; String dataValues[][] = { { "12", "234", "67" }, { "-123", "43", "853" }, { "93", "89.2", "109" }, { "279", "9033", "3092" } }; JTable table; excel() { table = new JTable( dataValues, columnNames ); } public void toExcel(JTable table, File file){ try{ TableModel model = table.getModel(); FileWriter excel = new FileWriter(file); for(int i = 0; i &lt; model.getColumnCount(); i++){ excel.write(model.getColumnName(i) + "\t"); } excel.write("\n"); for(int i=0; i&lt; model.getRowCount(); i++) { for(int j=0; j &lt; model.getColumnCount(); j++) { excel.write(model.getValueAt(i,j).toString()+"\t"); } excel.write("\n"); } excel.close(); }catch(IOException e){ System.out.println(e); } } public static void main(String[] o) { excel cv = new excel(); cv.toExcel(cv.table,new File("H:\\cs.tbv")); } } </code></pre>
[]
[ { "body": "<p>Most of the issues with this code are stylistic and violations of Java conventions rather than functional.</p>\n\n<pre><code>public class excel {\n</code></pre>\n\n<p>Class names should always be capitalized (e.g., <code>public class Excel</code>). Your class should probably also be named more descriptively and appropriately. Your class isn't Microsoft Excel. It's a class which converts <code>JTable</code> data into a CSV. So it would make more sense to name your class <code>JTableConverter</code> or something like that.</p>\n\n<pre><code>String columnNames[] = { \"Column 1\", \"Column 2\", \"Column 3\" };\n</code></pre>\n\n<p>Class fields should always have an explicit access modifier (<code>public</code>, <code>private</code>, or <code>protected</code>). Generally, if they're constants (as you use them), they are either <code>public static final</code> or <code>private static final</code> with the name in <code>ALL_CAPS_WITH_UNDERSCORES</code>. For an understanding of <code>static</code>, you can see <a href=\"https://stackoverflow.com/questions/413898/what-does-the-static-keyword-do-in-a-class\">this StackOverflow Q&amp;A</a>.</p>\n\n<p>So... <code>private static final String[] COLUMN_NAMES = { \"Column 1\", \"Column 2\", \"Column 3\" };</code></p>\n\n<pre><code>excel() {\n table = new JTable( dataValues, columnNames );\n}\n</code></pre>\n\n<p>Constructors and methods should also have an explicit access modifier. (<code>public JTableConverter()</code>)</p>\n\n<pre><code>public void toExcel(JTable table, File file) {\n</code></pre>\n\n<p>Method names should generally be verbs or verb phrases (such as <code>convertToExcel</code>). Also, since you're passing in the <code>JTable</code> to be used, it would make more sense for this to be a <code>static</code> method rather than an instance method. If you want it to be an appropriate instance method, there's no need to pass in the <code>JTable</code> at all, since the instance will already have access to the <code>JTable table</code> field.</p>\n\n<pre><code>excel.close();\n</code></pre>\n\n<p>Releasing or closing resources should pretty much always be done in a <code>finally</code> block, which is guaranteed<a href=\"https://stackoverflow.com/questions/12430642/what-are-the-circumstances-under-which-a-finally-block-will-not-execute\">*</a> to run. i.e.,</p>\n\n<pre><code>FileWriter writer = new FileWriter(file);\ntry {\n //stuff\n}\ncatch(IOException ioe) {\n //handling\n}\nfinally {\n try {\n writer.flush();\n writer.close();\n }\n catch(IOException ioe) {\n //handling\n }\n}\n</code></pre>\n\n<p>And, finally ...</p>\n\n<pre><code>public static void main(String[] o) {\n excel cv = new excel();\n cv.toExcel(cv.table,new File(\"H:\\\\cs.tbv\"));\n}\n</code></pre>\n\n<p>It's a bit nitpicky, but it's usually better to have your <code>main</code> method in a separate driver class (like <code>JTableConverterDriver</code>).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-02T22:41:11.877", "Id": "74638", "Score": "0", "body": "If he's using Java 7, he should use the try-with-resource statement, it will close automaticly." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-02T22:43:35.057", "Id": "74639", "Score": "1", "body": "@Marc-Andre Very true. Too used to coding in Java 6. That's what I get for spending the majority of my time coding for big companies that take years to adopt change, haha." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-02T18:09:48.580", "Id": "43233", "ParentId": "42914", "Score": "5" } }, { "body": "<blockquote>\n <p>is there a way to have it directly open in Excel without having to go through the import screens all of the time?</p>\n</blockquote>\n\n<p>The easiest way may be:</p>\n\n<ul>\n<li>Use comma-delimited instead of tab-delimited</li>\n<li>Make the extension \"csv\" instead of \"tbv\"</li>\n<li><a href=\"https://stackoverflow.com/q/12473480/49942\">See here</a> for how to escape commas</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-02T19:21:39.573", "Id": "43240", "ParentId": "42914", "Score": "2" } } ]
{ "AcceptedAnswerId": "43233", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T00:18:42.083", "Id": "42914", "Score": "5", "Tags": [ "java", "excel" ], "Title": "Writing a JTable to a tab delimited file" }
42914
<blockquote> <p>Given a number, this program would find "all permutations of the pairs that add to squares" from 1 to number.</p> <p>E.g: Given an input number of 16, one of the possible answers would be:</p> <pre><code>8:1:15:10:6:3:13:12:4:5:11:14:2:7:9:16 </code></pre> <p>and its reverse.</p> </blockquote> <p>Note that the function called <code>hasIntegerRoot</code> has been commented out for a purpose. I would appreciate if reviewer would chose me to use <code>hasIntegerRoot</code> over currently used <code>List&lt;Integer&gt; squareList</code>.</p> <p>I'm looking for code review, best practices, optimizations etc. </p> <p>Verifying Complexity (where \$n\$ is the input number):</p> <ul> <li>Time: \$O(n!)\$</li> <li>Space: \$O(n!)\$</li> </ul> <p> <pre><code>public final class PairSquare { private PairSquare() {}; /** * Given a number, this program would find "all permutations of the pairs that add to squares" from 1 to number" * * @param num The number upto which adjacent numbers should sum to a sqaure * @return A List of all the lists/chains of integers such that adjacent numbers sum upto a square. */ public static List&lt;List&lt;Integer&gt;&gt; pairSquare (int num) { if (num &lt;= 0) throw new IllegalArgumentException("The input number " + num + " should be less than equal to zero."); final List&lt;List&lt;Integer&gt;&gt; pairSquaresList = new ArrayList&lt;List&lt;Integer&gt;&gt;(); final List&lt;Integer&gt; squareList = squareList(num); final LinkedHashSet&lt;Integer&gt; elements = new LinkedHashSet&lt;Integer&gt;(); for (int i = 1; i &lt;= num; i++) { elements.add(i); getSqaureLists(i, num, elements, pairSquaresList, squareList); elements.remove(i); } return pairSquaresList; } private static List&lt;Integer&gt; squareList(int num) { int limit = num + (num - 1); int n = 2; final List&lt;Integer&gt; sqaureList = new ArrayList&lt;Integer&gt;(); int square; while ((square = n * n) &lt;= limit) { sqaureList.add(square); n++; } return sqaureList; } // private static boolean hasIntegerRoot(int x) { // double root = Math.sqrt(x); // return root == (int)root; // } private static void getSqaureLists(int currNum, int num, LinkedHashSet&lt;Integer&gt; elements, List&lt;List&lt;Integer&gt;&gt; pairSquareList, List&lt;Integer&gt; squareList) { if (elements.size() == num) { pairSquareList.add(new ArrayList&lt;Integer&gt;(elements)); return; } for (int i = 1; i &lt;= num; i++) { // a number has already been added in the list. deduping. if (elements.contains(i)) continue; // // checking if the adjacent numbers add up to a square of an int. // if (hasIntegerRoot(i + currNum)) { // elements.add(i); // getSqaureLists(i, num, elements, pairSquareList, squareList); // } if (squareList.contains(i + currNum)) { elements.add(i); getSqaureLists(i, num, elements, pairSquareList, squareList); } elements.remove(i); } return; } public static void main(String[] args) { List&lt;Integer&gt; list1 = Arrays.asList(8, 1, 15, 10, 6, 3, 13, 12, 4, 5, 11, 14, 2, 7, 9, 16); List&lt;Integer&gt; list2 = Arrays.asList(16, 9, 7, 2, 14, 11, 5, 4, 12, 13, 3, 6, 10, 15, 1, 8); List&lt;List&lt;Integer&gt;&gt; listOfLists = new ArrayList&lt;List&lt;Integer&gt;&gt;(); listOfLists.add(list1); listOfLists.add(list2); Assert.assertEquals(listOfLists, pairSquare(16)); } } </code></pre>
[]
[ { "body": "<p>Since you don't seem to be concerned with the order of any of the collections of objects you use, only membership in those collections, <code>Set</code> is probably the better <code>Collection</code> to use, instead of <code>List</code>. I imagine that <code>Set.contains</code> is going to be more efficient than <code>List.contains</code>.</p>\n\n<p>Also, it's not clear to me that recursion is the way to go here. If I were you, I would try to walk through the code with a low value for the input number and see what it's doing. It looks like for every integer between 1 and num, you're calling <code>getSqaureLists</code> num x num times. That seems like overkill. Recursion typically does some work and then passes a smaller set of work to the recursive call. You need to clarify how you split up that work. If that's not working, a iterative solution might be clearer. </p>\n\n<p>You also have some code to check for duplicates. You shouldn't need to do that. Whether you a doing an iterative or recursive solution, you should be able to avoid ever testing duplicate values. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T02:50:08.660", "Id": "42921", "ParentId": "42918", "Score": "5" } }, { "body": "<p><strong>Meaningful names</strong> - names like <code>PairSqaure</code>, <code>squareList</code>, <code>pairSquareList</code> do not add any information about the code, and are similar enough to confuse. Other names like <code>i</code>, <code>num</code>, <code>elements</code> are even less helpful. <code>findPairsThatAddUpToSquares(int maxValue)</code> is much more valuable, and make most of the documentation redundant.</p>\n\n<p><strong>Don't use the same name twice</strong> - you use <code>squareList</code> as a method name as well as a variable name, this is unreadable, and potentially error prone.</p>\n\n<p><strong>Don't overkill</strong> - the problem is finding all pairs of numbers which correspond to some restriction - it's like writing a big table with n lines and n rows, and marking each one which fits - that would be \\$O(n^2)\\$, anything more complex would be wrong. Your use of recursion is unclear, and I can't see the point of it a simple loop would suffice:</p>\n\n<pre><code>for (int highNum = 2; highNum &lt;= maxNum; highNum++) {\n for (int lowNum = 1; lowNum &lt; highNuml; lowNum++) {\n if (fitsTheBill(lowNum, highNum)) {\n results.add(new int[] { lowNum, highNum });\n results.add(new int[] { highNum, lowNum });\n }\n }\n}\n</code></pre>\n\n<p><strong>Use correct container</strong> - using a pre-calculated table of squares is fine, but if you put it in an <code>ArrayList</code>, each <code>contains</code> will cost you \\$O(n)\\$. Using <code>Set</code> will do the same thing in \\$O(1)\\$.</p>\n\n<p><strong>Unclear requirements</strong> - \"all permutations of the pairs that add to squares\" - what I understand from this is that the result should be a list of <em>pairs</em> containing [n,m] and [m,n] for each pair that adds to a square, you sample output though is two arrays containing a list of numbers in which every <code>item[i]+item[i+1]</code> adds up to a square. This may be what you meant, but this hardly constitutes <em>all permutations</em> of such an answer - <code>15:10:6:3:13:12:4:5:11:14:2:7:9:16:8:1</code> will also qualify, but it is not part of your answer...</p>\n\n<p>Here is a refactored solution with complexity of \\$O(n^2)\\$ in time and \\$O(n)\\$ in space:</p>\n\n<pre><code>public final class PairsThatAddUpToSquaresFinder {\n\n private PairsThatAddUpToSquaresFinder() {};\n\n public static List&lt;List&lt;Integer&gt;&gt; findPairsThatAddUpToSquares (int maxValue) {\n if (maxValue &lt;= 0) throw new IllegalArgumentException(\"The input number \" + maxValue + \" should be less than equal to zero.\");\n\n final List&lt;Integer&gt; pairsThatAddUpToSquares = new ArrayList&lt;Integer&gt;();\n final Set&lt;Integer&gt; precalculatedSquares = calculateAllSquaresUpTo(maxValue);\n for (int highNum = 2; highNum &lt;= maxValue; highNum++) {\n for (int lowNum = 1; lowNum &lt; highNuml; lowNum++) {\n if (precalculatedSquares.contains(lowNum + highNum)) {\n pairsThatAddUpToSquares.add(lowNum);\n pairsThatAddUpToSquares.add(highNum);\n }\n }\n }\n final List&lt;List&lt;Integer&gt;&gt; result = new ArrayList&lt;List&lt;Integer&gt;&gt;();\n result.add(pairsThatAddUpToSquares);\n result.add(Collections.reverse(pairsThatAddUpToSquares.clone()));\n return result;\n }\n\n private static List&lt;Integer&gt; calculateAllSquaresUpTo(int maxValue) {\n int limit = maxValue + (maxValue - 1);\n int n = 2;\n final List&lt;Integer&gt; sqaureList = new ArrayList&lt;Integer&gt;();\n int square;\n while ((square = n * n) &lt;= limit) {\n sqaureList.add(square);\n n++;\n }\n return sqaureList;\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T09:00:38.050", "Id": "42942", "ParentId": "42918", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T01:42:04.647", "Id": "42918", "Score": "1", "Tags": [ "java", "algorithm", "backtracking" ], "Title": "All permutations of the pairs that add to squares" }
42918
<p>I'm looking for a design pattern or suggestions that can help refactor my code into something a bit less repetitive. I have a method that has several sequential steps (10-15) that if any of them fail must record detail about the failure to a log and rollback all previous portions of the transaction. The example is below. </p> <p>I have thought about taking each try catch and turning it into an individual method but then I have to pass around my undo stack (among several other variables) and I still have to conditionally abort the method and process the undo stack. I've briefly looked into the Momento and Command patterns but both seemed to grow the line count by a fair margin. </p> <pre><code>EnumResult TransactionThatRollsBack() { var undoLog = new Stack&lt;Action&gt;(); try { MoveInventory(inv, src, dest); undoLog.Push(() =&gt; MoveInventory(inv,dest,src)); } catch (Exception ex) { RecordError("InventoryError", ex, inv, src, dest); Undo(undoLog); return EnumResult.FailedInventoryMove; } try { NotifyReportingOfMove(inv, user); undoLog.Push(() =&gt; NotifyReportingOfUnMove(inv, user)); } catch (Exception ex) { RecordError("NotifyReportingOfMove", ex, inv, user); Undo(undoLog); return EnumResult.FailedReportingMove; } try { AddUserToSweepstakes(user); undoLog.Push(() =&gt; RemoevUserFromSweepstakes(user)); } catch (Exception ex) { RecordError("AddUserToSweepstakes", ex, user); Undo(undoLog); return EnumResult.FailedSweepstakesAdd; } ... return EnumResult.Success } </code></pre>
[]
[ { "body": "<p>Much of that needs to be there. You could modify things to use a single try-catch though:</p>\n\n<pre><code> var undoLog = new Stack&lt;Action&gt;();\n var errorContainer = new ErrorContainer{ message = \"Unknown error\", enumResult = EnumResult.UnknownError };\n\n try\n {\n errorContainer = GenerateError(EnumResult.FailedInventoryMove, \"InventoryError\", inv, src, dest);\n MoveInventory(inv, src, dest);\n undoLog.Push(() =&gt; MoveInventory(inv,dest,src));\n\n errorContainer = GenerateError(EnumResult.FailedReportingMove, \"NotifyReportingOfMove\", inv, user);\n NotifyReportingOfMove(inv, user);\n undoLog.Push(() =&gt; NotifyReportingOfUnMove(inv, user));\n\n ...\n\n return EnumResult.Success;\n }\n catch (Exception ex)\n {\n Undo(undoLog);\n LogError(errorContainer, ex);\n return errorContainer.enumResult;\n }\n</code></pre>\n\n<p>I don't know that you gain clarity by going this route, but if you can make the ErrorContainer work for you, it might be an option to reduce total lines of code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T05:05:20.313", "Id": "74017", "Score": "0", "body": "Thanks for the feedback. 1 hiccup on a single catch... Each part of the transaction that fails has to return a different Enum result and they may share similar exceptions." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T05:43:17.123", "Id": "74019", "Score": "0", "body": "I knew I forgot something. The EnumResult should have been added as an argument to GenerateError. Updated answer." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T04:13:31.960", "Id": "42927", "ParentId": "42920", "Score": "4" } }, { "body": "<p>You can remove repeated code if you record all your actions for executions and then execute them all at once with some generic exception handling. The idea is below. </p>\n\n<p>Sorry for some possible lapses, didn't write in C# for quite some time. However I hope that you'll find the whole idea to be helpful.</p>\n\n<pre><code> EnumResult TransactionThatRollsBack()\n {\n var undoLog = new SmartStack();\n undoLog.Push(() =&gt; MoveInventory(inv,dest,src), EnumResult.1);\n undoLog.Push(() =&gt; NotifyReportingOfUnMove(inv, user), EnumResult.2);\n undoLog.Push(() =&gt; RemoevUserFromSweepstakes(user), EnumResult.3);\n\n undoLog.execute();\n }\n\n class SmartStack {\n SortedDictionary&lt;Action, EnumResult&gt; actions; \n\n void push(Action a, EnumResult r) {\n actions.add(a, r);\n }\n\n void execute() {\n Stack&lt;Action&gt; completedActions = new Stack&lt;Action&gt;();\n foreach(KeyValuePair&lt;Action, EnumResult&gt; pair in actions) {\n try {\n pair.Key.Invoke();\n completedActions.push(pair.Key);\n }\n catch(Exception ex) {\n for (Action a in completedActions) {\n Undo(a);\n }\n return pair.Value;\n }\n }\n }\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T05:10:20.527", "Id": "74018", "Score": "0", "body": "Good idea, I had thought about the idea of (just like the undo log) using anonymous functions to represent the Perform, Undo, and Result on exception as well, looks like a possibly viable option. Seems to work good for single line calls, but if the content in the try is more than a line or 2 the nesting gets a bit ugly." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-03T12:29:02.857", "Id": "74714", "Score": "1", "body": "@AndreyTaptunov What would be in `Undo(a)` method? You can't invert arbitrary functions." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T04:40:49.177", "Id": "42930", "ParentId": "42920", "Score": "8" } }, { "body": "<p>Well I would personally want to cut down on all of that exception handling code.</p>\n\n<p>The easiest way in my mind is to create your own exceptions. \nNow, I understand you seem to need a message and enum associated with each chunk there so why not make that as a base transactionException and overload each case. </p>\n\n<pre><code>public class TransactionException : Exception\n{\n public TransactionException(string message,EnumResult result,Exception innerException) : base(message,innerException) { Result = result; }\n\n public EnumResult Result { get; private set; }\n}\n</code></pre>\n\n<p>Encapsulates the basic functionality of a transaction and now in specific cases you can do something like:</p>\n\n<pre><code>public class InventoryMoveException : TransactionException\n{\n public InventoryMoveException(Exception innerException) : this(\"InventoryError\",innerException) {}\n public InventoryMoveException(string message,Exception innerException) : base(message,EnumResult.FailedInventoryMove,innerException){}\n}\n</code></pre>\n\n<p>and with all that in place you should be able to throw a number of custom exceptions and wrap the whole thing in one catch block that will log the associated message and return the associated enum. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T14:37:02.537", "Id": "74062", "Score": "0", "body": "I like this approach. It provides relatively readable code as well in the method i'm talking about. Only downside is that I'd have to catch the exceptions in all of the calling methods and wrap them in a new Transaction exception, some of which are not my code base, so I'd have to make wrapper methods for those. Thanks for the idea." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T14:47:38.267", "Id": "74063", "Score": "0", "body": "@deepee1 Good! That is exactly the point. You SHOULD have a nested exception chain and can react at the desired point Transaction Failed-> TransactionException->UserAdditionException->NullArgumentException . you can fail graciously and still give an informative stack trace. bubble the exception. In fact I am against the idea of Error Enums in the first place, that swallows the exception. in your example you will know a userException occured but not on what object or under what circumstance. keep throwing exceptions till Presentation layer,let the final use circumstance dictate error handling." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T14:57:31.090", "Id": "74065", "Score": "0", "body": "you could add probably add `Undo(undoLog);` to the exceptions as well" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T15:22:09.113", "Id": "74071", "Score": "1", "body": "@Malachi well I'd be hesitant of coupling logging with exceptions, I only added the message because the exception has a message anyway, they are all in the same domain. I would be more inclined to fire off a log event and add undoLog into the EventArgs, allowing any kind of logging subscriptions. (although tbh it would actually be a composite logger interface but you get the idea..)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T17:42:29.903", "Id": "74095", "Score": "0", "body": "that sounds about right." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T12:02:54.423", "Id": "42952", "ParentId": "42920", "Score": "4" } } ]
{ "AcceptedAnswerId": "42930", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T02:48:41.907", "Id": "42920", "Score": "10", "Tags": [ "c#", "error-handling", "stack" ], "Title": "Making an atomic transaction out of several operations" }
42920
<p>I have written the following Google Spreadsheet script that attempts to loop through all selected cells and then update the value so that it adds an indent, by adding</p> <pre><code>=CONCAT(REPT( CHAR( 160 ), 5),"' + value[row] + '") </code></pre> <p>around the value.</p> <p>Is there a better way to achieve this?</p> <pre><code>var ss = SpreadsheetApp.getActiveSpreadsheet(); function indentText() { var values = ss.getActiveRange().getValues(); var newValues = new Array(); for (i = 0; i &lt; values.length; i++) { if (values[i][0] != '') { newValues.push(['=CONCAT(REPT( CHAR( 160 ), 5),"' + values[i][0] + '")']); } else { newValues.push(['']); } } ss.getActiveRange().setValues(newValues); }; function onOpen() { var sheet = SpreadsheetApp.getActiveSpreadsheet(); var entries = [{ name : "Indent Text", functionName : "indentText" }]; sheet.addMenu("Indent Text", entries); }; </code></pre>
[]
[ { "body": "<p>Interesting question,</p>\n\n<p>there is clearly a lack in the Google Script API to indent cells..</p>\n\n<p>Still, I find the <code>CONCAT</code> approach ugly, if one wants to indent 2 times, the formula will be:</p>\n\n<pre><code>=CONCAT(REPT( CHAR( 160 ), 5),\"=CONCAT(REPT( CHAR( 160 ), 5),\"'Hello World'\")\")\n</code></pre>\n\n<p>Which is ugly, I would simply pre-calculate the prefix and concatenate in the script and not let the formula do the work. This will also make un-indenting much easier.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-04T16:22:03.483", "Id": "43421", "ParentId": "42922", "Score": "3" } }, { "body": "<p>I can't offer a better way to accomplish this, but I can offer a few notes.</p>\n\n<ul>\n<li>I like that you declared <code>ss</code> at a global scope, but <code>ss</code> isn't a very good variable name. Even if it is what Google uses in their API documentation.</li>\n<li>I tend to avoid using <code>!=</code> in an <code>If</code> if I'm taking action on <code>==</code> as well.</li>\n<li>It might seem silly, but it makes sense to define an empty string \"constant\". It's difficult at a glance to tell if if this is space or an empty string. Don't trade a few keystrokes for readability.</li>\n<li>You're inconsistent in which type of quotes you're using. You switched from single quotes in <code>indentText()</code> to double quotes in <code>onOpen()</code>.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-25T03:10:09.337", "Id": "58002", "ParentId": "42922", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T02:56:17.713", "Id": "42922", "Score": "3", "Tags": [ "google-apps-script", "google-sheets" ], "Title": "Looping through selected cells to indent text" }
42922
<p>Bidi, short for Bi-directional text is text containing text in both text directionalities, both right-to-left (RTL or dextrosinistral) and left-to-right (LTR or sinistrodextral). It generally involves text containing different types of alphabets, but may also refer to boustrophedon, which is changing text directionality in each row.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T03:52:03.290", "Id": "42924", "Score": "0", "Tags": null, "Title": null }
42924
Bidi, short for Bi-directional text is text containing text in both text directionalities, both right-to-left (RTL or dextrosinistral) and left-to-right (LTR or sinistrodextral). It generally involves text containing different types of alphabets, but may also refer to boustrophedon, which is changing text directionality in each row.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T03:52:03.290", "Id": "42925", "Score": "0", "Tags": null, "Title": null }
42925
<pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;assert.h&gt; typedef struct Node NODE; struct Node { int value; int is_leaf; struct Node *right; struct Node *left; }; NODE *new_leaf(void) { NODE *leaf = malloc(sizeof(NODE)); assert(leaf); leaf-&gt;is_leaf = 1; leaf-&gt;value = 0; leaf-&gt;right = NULL; leaf-&gt;left = NULL; return leaf; } int insert(NODE *node, int value) { assert(node); if (node-&gt;is_leaf) { node-&gt;is_leaf = 0; node-&gt;value = value; node-&gt;left = new_leaf(); node-&gt;right = new_leaf(); } else if (node-&gt;value &lt; value) { return insert(node-&gt;left, value); } else if (node-&gt;value &gt; value) { return insert(node-&gt;right, value); } return -1; } int contains(NODE *node, int value) { assert(node); if (node-&gt;is_leaf) { return 0; } else if (node-&gt;value &lt; value) { return contains(node-&gt;left, value); } else if (node-&gt;value &gt; value) { return contains(node-&gt;right, value); } return 1; } int max_height(NODE *node) { assert(node); if (node-&gt;is_leaf) { return 0; } int left_height = max_height(node-&gt;left); int right_height = max_height(node-&gt;right); if (left_height &gt; right_height) { return 1 + left_height; } else { return 1 + right_height; } } void destroy(NODE *tree) { free(tree); } int main(void) { NODE *tree = new_leaf(); insert(tree, 7); printf("contains 7? : %d\n", contains(tree, 7)); insert(tree, 6); printf("contains 6? : %d\n", contains(tree, 6)); insert(tree, 5); printf("contains 5? : %d\n", contains(tree, 5)); printf("height should be 3, is : %d\n", max_height(tree)); insert(tree, 8); printf("contains 8? : %d\n", contains(tree, 8)); printf("height should be 3, is : %d\n", max_height(tree)); printf("no contains 1? : %d\n", contains(tree, 9)); destroy(tree); } </code></pre> <p>Looking for general style advice, and if I missed any memory leaks. </p> <p>Specific question: does <code>destroy</code>ing the tree at the end free up all of the memory allocated for every node in the tree? If so, how? If not, how can I ensure that occurs? Also, am I using asserts correctly? It's very different than the languages I have used previously.</p>
[]
[ { "body": "<p>Firstly, in C, <code>ALL_CAPS</code> is generally used only for macros. Hence, I wouldn't use the name <code>NODE</code> as a <code>typedef</code> for your <code>struct node</code>, but instead something like <code>typedef struct Node node_type;</code>. Further, generally C is written using <code>lowercase_with_underscores</code>, so I'd rename it to <code>struct node</code>. </p>\n\n<p>Using an <code>assert</code> in your <code>new_leaf</code> function on what you get back from <code>malloc</code> is fine in my books, as this will terminate the process if the OS can't give you back any memory, in which case you're unlikely to be able to do anything anyway.</p>\n\n<p>Your function <code>int contains(NODE *node, int value)</code> doesn't really need an <code>assert</code>. If the user gives you a <code>NULL</code> node, then you can immediately just <code>return 0</code>. Giving a <code>NULL</code> to this function shouldn't terminate the program. A similar argument can be made for <code>max_height</code>. </p>\n\n<p>Of course, the biggest problem is that no, your <code>destroy</code> function definitely does NOT clean up all the memory allocated by the program. Tools like <a href=\"http://valgrind.org/\">valgrind</a> can help to inform you if you have any memory leaks lurking around. In this case, however, it's very easy to see that the only memory that will be reclaimed is the memory for the root node (whatever you call <code>destroy</code> with).</p>\n\n<p>Fixing this is pretty simple: it's just using a recursive algorithm that you've basically already used in <code>insert</code> and <code>contains</code>:</p>\n\n<pre><code>void destroy(node_type root)\n{\n // If we have a non-NULL pointer, we need to\n // recursively free its left and right children,\n // and then free it.\n if(root) {\n destroy(root-&gt;left);\n destroy(root-&gt;right);\n free(root);\n }\n}\n</code></pre>\n\n<p>A few other comments:</p>\n\n<ul>\n<li>I'm not a big fan of 2 space indentation. It's not enough to (easily) visually scope blocks. I'd much rather 4 spaces.</li>\n<li>You might want to start looking into how to user header files to split up interface and implementation as a next step (if you haven't already).</li>\n<li>I'm not a big fan of explicitly having keeping track of what is a leaf with <code>is_leaf</code>. It means that any node that is down the bottom will have 2 extra dynamic allocations performed to have leaf values (see <code>insert</code>). Instead, I'd just set the <code>left</code> and <code>right</code> pointers to be <code>NULL</code>, and leave it at that. You can easily write an <code>is_leaf</code> function that simply checks that both pointers are <code>NULL</code>. </li>\n<li>The API is a bit deficient (no deletion of a value, for example), but I'm guessing this is done as a learning exercise, so that's ok.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T06:56:17.607", "Id": "42934", "ParentId": "42931", "Score": "5" } }, { "body": "<p>Specific questions first:</p>\n\n<ol>\n<li><p>No, your <code>destroy</code> function does not destroy the entire tree - it just frees the current node and you'll leak all other nodes. You will have to implement a recursive delete similar to all your other functions:</p>\n\n<pre><code>void destroy(NODE *node)\n{\n if (!node-&gt;is_leaf)\n {\n destroy(node-&gt;left);\n destroy(node-&gt;right);\n }\n free(node);\n}\n</code></pre></li>\n<li><p>I think your usage of <code>assert</code> is quite sensible. Just be aware that asserts are typically removed when build with <code>NDEBUG</code> defined - in that case your code will just segfault.</p></li>\n</ol>\n\n<p>Some general remarks:</p>\n\n<ol>\n<li><p><code>UPPERCASE</code> names are typically only used for macros and not for typedefs.</p></li>\n<li><p>I don't quite see the point of returning a value from insert. You always return -1 anyway.</p></li>\n<li><p>Personally I'm not a fan of implementations where an element of the data structure is used to also represent the entry into the data structure. You are effectively leaking the internals if your implementation to the user. An alternative API would something like this:</p>\n\n<p>In your header:</p>\n\n<pre><code>typedef struct BinarySearchTree BinarySearchTree;\n\nBinarySearchTree* bst_new_tree();\nvoid bst_insert(BinarySearchTree* tree, int value);\nint bst_contains_value(BinarySearchTree* tree, int value);\nint bst_max_height(BinarySearchTree* tree);\n</code></pre>\n\n<p>In your implementation</p>\n\n<pre><code>struct BinarySearchTree\n{\n Node *root;\n}\n\n....\n</code></pre>\n\n<p>This way any user of you data structure doesn't know anything about the internals which in turn makes it easy to change the implementation without affecting anything else.</p>\n\n<p>Typedefing the struct in the header but only defining it in the implementation file is called an opaque type - a type where the consumer of the header does not know anything about the internals of it.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T06:59:00.703", "Id": "42935", "ParentId": "42931", "Score": "2" } }, { "body": "<p>It doesn't use memory very efficiently:</p>\n\n<ul>\n<li>The first node is initially a 'leaf' node which contains no useful value</li>\n<li>Every leaf node contains no useful value</li>\n<li>Every non-leaf node (which contains a value) contains two empty leaf nodes</li>\n</ul>\n\n<p>It's a bit hard to see what's happening: initially-empty leaf nodes later have a value inserted into them.</p>\n\n<p>A cleaner implementation might be:</p>\n\n<ul>\n<li>Every Node contains a value; the value is inserted in the Node when the Node is created and never changed afterwards</li>\n<li>A tree which contains no values is represented by a null Node pointer (i.e. zero Node instances)</li>\n<li>Left and right nodes aren't added until they're needed</li>\n</ul>\n\n<p>To implement this:</p>\n\n<ul>\n<li>Add a <code>int value</code> parameter to the new_leaf function</li>\n<li>Remove the is_leaf member of the node</li>\n<li>Create left and right nodes just-in-time i.e. not before/until they are needed</li>\n</ul>\n\n<p>For example:</p>\n\n<pre><code>struct Node {\n int value;\n struct Node *right;\n struct Node *left;\n};\n\nNODE *new_leaf(int value) {\n NODE *leaf = (NODE*)malloc(sizeof(NODE));\n assert(leaf);\n leaf-&gt;value = value;\n leaf-&gt;right = NULL;\n leaf-&gt;left = NULL;\n return leaf;\n}\n\nint insert(NODE *node, int value) {\n assert(node);\n if (node-&gt;value &lt; value) {\n if (node-&gt;left)\n return insert(node-&gt;left, value);\n else\n node-&gt;left = new_leaf(value);\n } else { // if (node-&gt;value &gt;= value)\n if (node-&gt;right)\n return insert(node-&gt;right, value);\n else\n node-&gt;right = new_leaf(value);\n }\n return -1;\n}\n\nint contains(NODE *node, int value) {\n assert(node);\n if (node-&gt;value == value) {\n return 1;\n } else if (node-&gt;value &lt; value) {\n if (node-&gt;left)\n return contains(node-&gt;left, value);\n } else { // if (node-&gt;value &gt; value)\n if (node-&gt;right)\n return contains(node-&gt;right, value);\n } \n return 0;\n}\n\nint max_height(NODE *node) {\n assert(node);\n int left_height = (node-&gt;left) ? max_height(node-&gt;left) : 0;\n int right_height = (node-&gt;right) ? max_height(node-&gt;right) : 0;\n if (left_height &gt; right_height) {\n return 1 + left_height;\n } else {\n return 1 + right_height;\n }\n}\n\nvoid destroy(NODE *tree) {\n NODE *left = tree-&gt;left;\n NODE *right = tree-&gt;right;\n free(tree);\n if (left)\n destroy(left);\n if (right)\n destroy(right);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T09:11:11.807", "Id": "42943", "ParentId": "42931", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T05:30:38.200", "Id": "42931", "Score": "5", "Tags": [ "c", "memory-management", "tree", "binary-search" ], "Title": "Binary Search Tree implementation" }
42931
<blockquote> <p>Write a program in Java that takes a positive integer and prints out all ways to multiply smaller integers that equal the original number, without repeating sets of factors. In other words, if your output contains 4 * 3, you should not print out 3 * 4 again as that would be a repeating set. Note that this is not asking for prime factorization only.</p> </blockquote> <p>Here is the sample from one solution:</p> <p>Example: </p> <blockquote> <pre><code>$ java -cp . PrintFactors 32 </code></pre> <p>32 * 1</p> <p>16 * 2</p> <p>8 * 4</p> <p>8 * 2 * 2</p> <p>4 * 4 * 2</p> <p>4 * 2 * 2 * 2</p> <p>2 * 2 * 2 * 2 * 2</p> </blockquote> <p>I'm looking for code review, best practices, optimizations etc.</p> <p>Verifying Complexity: \$O(n!)\$ - time, where \$n\$ is the input number.</p> <p></p> <pre><code>public final class PrintFactors { private PrintFactors() {} public static void printFactors(int number) { if (number &lt;= 0) throw new IllegalArgumentException("The number should be greater than 0."); printFactorsList(number, number + "*" + 1 + "\n", number); } private static void printFactorsList(int dividend, String factorString, int prevDivisor) { /* * This function contains factorString as an argument to facilitate the recursive call for subsequent * factors until it reaches prime values. For example, let's say input number = 32 and when i = 8 it prints * 8*(32/8) ==&gt; 8 * 4 but the subsequent reduction of 4 is needed and this is done by recursively passing in 4 * as number. But we also want to maintain the chain "8 * ". So this makes the carry over string as an input * argument for the helper function printFactorsList */ for (int divisor = dividend - 1; divisor &gt;= 2; divisor--) { if (dividend % divisor != 0) continue; if (divisor &gt; prevDivisor) continue; int quotient = dividend / divisor; /* * 32*1 16*2 8*4 8*2*2 4*4*2 4*2*2*2 2*2*2*2*2 * * Note: as we go right, the values keeps descending. */ if (quotient &lt;= divisor) { if (quotient &lt;= prevDivisor) { System.out.println(factorString + divisor + "*" + quotient); } } printFactorsList(quotient, factorString + divisor + "*", divisor); } } public static void main(String[] args) { printFactors(12); System.out.println(); printFactors(32); } } </code></pre>
[]
[ { "body": "<pre><code>public static void printFactors(int number) {\n if (number &lt;= 0) {\n</code></pre>\n\n<p>You should include the number into the exception's text.</p>\n\n<pre><code> throw new IllegalArgumentException(\"The number should be greater than 0.\");\n }\n printFactorsList(number, number + \"*\" + 1 + \"\\n\", number);\n}\n</code></pre>\n\n<p>That's a bad name for a function.</p>\n\n<pre><code>private static void printFactorsList(int dividend, String factorString, int prevDivisor) {\n</code></pre>\n\n<p>This should be formatted as javadoc.</p>\n\n<pre><code> /*\n * This function contains factorString as an argument to facilitate the recursive call for subsequent\n * factors until it reaches prime values. For example, let's say input number = 32 and when i = 8 it prints\n * 8*(32/8) ==&gt; 8 * 4 but the subsequent reduction of 4 is needed and this is done by recursively passing in 4\n * as number. But we also want to maintain the chain \"8 * \". So this makes the carry over string as an input\n * argument for the helper function printFactorsList\n */\n</code></pre>\n\n<p>Why not start this loop from prevDivisor?\nAlso, you can optimize this loop by storing numbers in factorized form and generating all divisors less than something on the fly. This will be much faster because you will iterate only over valid divisors. You can also memoize all solutions for a number and reuse them.</p>\n\n<pre><code> for (int divisor = dividend - 1; divisor &gt;= 2; divisor--) {\n\n if (dividend % divisor != 0) {\n continue;\n }\n\n if (divisor &gt; prevDivisor) {\n continue;\n }\n\n int quotient = dividend / divisor;\n\n /*\n * 32*1 16*2 8*4 8*2*2 4*4*2 4*2*2*2 2*2*2*2*2\n *\n * Note: as we go right, the values keeps descending.\n */\n</code></pre>\n\n<p>Merge this two ifs into one.</p>\n\n<pre><code> if (quotient &lt;= divisor) {\n if (quotient &lt;= prevDivisor) {\n System.out.println(factorString + divisor + \"*\" + quotient);\n }\n }\n printFactorsList(quotient, factorString + divisor + \"*\", divisor);\n }\n}\n\npublic static void main(String[] args) {\n</code></pre>\n\n<p>You are not reading from anywhere. Is this the intended behavior?</p>\n\n<pre><code> printFactors(32);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T09:12:18.350", "Id": "42944", "ParentId": "42939", "Score": "3" } }, { "body": "<p>for (int divisor = dividend - 1; divisor >= 2; divisor--)</p>\n\n<p>In the above for loop, the loop can also be started from (dividend/2), because for all divisors > dividend/2, the Mod will always be &lt;0.</p>\n\n<p>So, starting the loop from dividend/2, might also reduce the runtime. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-04T05:10:59.730", "Id": "52408", "ParentId": "42939", "Score": "0" } }, { "body": "<p>Instead of</p>\n\n<pre><code> for (int divisor = dividend - 1; divisor &gt;= 2; divisor--)\n</code></pre>\n\n<p>you could start the loop from <code>Math.min(divisor/2, prevDivisor)</code>, which means you execute <code>if (dividend % divisor != 0)</code> about half as often and you don't need to test <code>if (divisor &gt; prevDivisor)</code> at all.</p>\n\n<p>Instead of</p>\n\n<pre><code> if (quotient &lt;= divisor) {\n if (quotient &lt;= prevDivisor) {\n</code></pre>\n\n<p>you could just test <code>if (quotient &lt;= divisor)</code>. You have already guaranteed that if you get to this step, then <code>divisor &lt;= prevDivisor</code>, so whenever <code>quotient &lt;= divisor</code> it will always be true that <code>quotient &lt;= prevDivisor</code>.</p>\n\n<p>I'm not a fan of <code>continue</code> statements. In this case, I'd put the rest of the body of the loop inside the <code>if</code> statement (which would test <code>if (dividend % divisor == 0)</code>, of course).</p>\n\n<p>I'm pretty sure this algorithm is \\$O(n!)\\$, but I have a strong hunch one could find a much tighter bound on running time. The vast majority of the loops do not call the function recursively; the maximum number of calls directly from a single loop is just the number of proper divisors of <code>dividend</code>.</p>\n\n<p>It might improve running time if the loop iterated over the list of divisors of <code>dividend</code> instead of consecutive integers. The list of divisors is easily generated from the prime factorization, which you can pass into each invocation of the function. (The prime factorization of <code>quotient</code> is just the prime factorization of <code>dividend</code> with its exponents reduced by the exponents of the prime factorization of <code>divisor</code>, so you only really have to factorize the original number before the first call.)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-05T13:37:16.440", "Id": "52509", "ParentId": "42939", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T08:40:14.330", "Id": "42939", "Score": "4", "Tags": [ "java", "algorithm", "primes", "combinatorics" ], "Title": "Prints out all ways to multiply smaller integers that equal the original number" }
42939
<p>Are all these steps correct and necessary?</p> <pre><code>&lt;?php if (isset($_SESSION['userID'])) { $userID = $_SESSION['userID']; $stmt = $mysqli-&gt;prepare( "SELECT usergroup, firstname FROM tbl_users WHERE userID = ? "); $stmt-&gt;bind_param('i', $userID); $stmt-&gt;execute(); $stmt-&gt;store_result(); $stmt-&gt;bind_result($usergroup, $firstname); $stmt-&gt;fetch(); $_SESSION['usergroup'] = $usergroup; $_SESSION['firstname'] = $firstname; $stmt-&gt;close(); } ?&gt; </code></pre>
[]
[ { "body": "<p>More or less, they are... I was using <a href=\"http://de3.php.net/manual/en/mysqli-stmt.get-result.php\" rel=\"nofollow\"><code>get_result</code></a> and fetching object more often, but if you want to have the results bound directly to variables, your code is what you need.</p>\n\n<p>By the way, consider using some ORM. I'm using Doctrine2 for my PHP stuff and I'm very satisfied with it</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-02T00:49:12.087", "Id": "43186", "ParentId": "42950", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T11:24:49.043", "Id": "42950", "Score": "3", "Tags": [ "php", "mysqli" ], "Title": "Are all these steps necessary with prepared statement?" }
42950
<p>How secure is this encryption? Secondly, is there something I could do to "turn it up a notch" and make it 'more' secure?</p> <pre><code>Imports System.Security.Cryptography Public Class clsCrypt Private TripleDES As New TripleDESCryptoServiceProvider 'create and return the key and initialization vector hash Private Function TruncateHash(ByVal key As String, ByVal length As Integer) As Byte() Dim sha1 As New SHA1CryptoServiceProvider ' Hash the key. Dim keyBytes() As Byte = System.Text.Encoding.Unicode.GetBytes(key) Dim hash() As Byte = sha1.ComputeHash(keyBytes) ' Truncate or pad the hash. ReDim Preserve hash(length - 1) Return hash End Function 'initialize the class Sub New(ByVal key As String) ' Initialize the crypto provider. TripleDES.Key = TruncateHash(key, TripleDES.KeySize \ 8) TripleDES.IV = TruncateHash("", TripleDES.BlockSize \ 8) End Sub 'encrypt the passed text Public Function EncryptData(ByVal plaintext As String) As String ' Convert the plaintext string to a byte array. Dim plaintextBytes() As Byte = System.Text.Encoding.Unicode.GetBytes(plaintext) ' Create the stream. Dim ms As New System.IO.MemoryStream ' Create the encoder to write to the stream. Dim encStream As New CryptoStream(ms, TripleDES.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write) ' Use the crypto stream to write the byte array to the stream. encStream.Write(plaintextBytes, 0, plaintextBytes.Length) encStream.FlushFinalBlock() ' Convert the encrypted stream to a printable string. Return Convert.ToBase64String(ms.ToArray) End Function 'decrypt passed text Public Function DecryptData(ByVal encryptedtext As String) As String ' Convert the encrypted text string to a byte array. Dim encryptedBytes() As Byte = Convert.FromBase64String(encryptedtext) ' Create the stream. Dim ms As New System.IO.MemoryStream ' Create the decoder to write to the stream. Dim decStream As New CryptoStream(ms, TripleDES.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Write) ' Use the crypto stream to write the byte array to the stream. decStream.Write(encryptedBytes, 0, encryptedBytes.Length) decStream.FlushFinalBlock() ' Convert the plaintext stream to a string. Return System.Text.Encoding.Unicode.GetString(ms.ToArray) End Function End Class </code></pre> <p>Lastly, would this encryption class function the same if I passed in a different key in different <code>Subs</code>? Example:</p> <pre><code>Private Sub EmployeeFrm_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load Dim strKey As String = "Key1" 'encryption Key Dim clsEncrypt As clsCrypt 'Assigns a variable to clsCrypt class clsEncrypt = New clsCrypt(strKey) ' creates a new isntance of the clsCrypt class </code></pre> <p>And also:</p> <pre><code>Private Sub InsertBtn_Click(sender As System.Object, e As System.EventArgs) Handles InsertBtn.Click Dim strKey As String = "Strong3rKeY!" 'encryption Key Dim clsEncrypt As clsCrypt 'Assigns a variable to clsCrypt class clsEncrypt = New clsCrypt(strKey) ' creates a new isntance of the clsCrypt class </code></pre> <p>Both are in the same form, just during different events.</p> <p>Is this even a good way to utilize encryption? I am using it to encrypt specific strings and insert them into the database.</p>
[]
[ { "body": "<p>Some issues:</p>\n\n<ol>\n<li>No MAC => say hello to padding oracles. This is fatal flaw that allows decryption of the message in many usage scenarios (when there is an active attacker).</li>\n<li>You use CBC mode with constant IV. A new IV must be chosen for each message. It should be unpredictable and random.</li>\n<li><p>Your keying is only secure with <em>really</em> strong passwords (over 100 bits of entropy). I recommend using an actual binary key drawn from a secure CSPRNG encoded with Base64 instead of a password.</p>\n\n<p>A related stylistic problem is that you don't clearly distinguish between keys (which should be uniformly random) and passwords.</p></li>\n<li><p>Does the key ever leave the trusted systems? It looks like you're hardcoding a key into a client, which might run on an untrusted machine. Even if it stays on the server, put it in a config file, not the code.</p>\n\n<p>Your program should be secure even if the whole code is known. Logistically it's also much easier to keep a config file secure, since it doesn't need to be checked into version control.</p></li>\n<li><p>Why would you choose 3DES over AES in new code? AES is faster and stronger. It also has 128 bit blocks instead of 64 bit blocks, so it doesn't weaken once you encrypt a couple of gigabytes using the same key.</p></li>\n<li>All those streams are unnecessarily complicated. Simply call <code>encryptor.TransformFinalBlock</code> on a byte array instead.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T15:42:37.180", "Id": "74304", "Score": "0", "body": "Thanks for the reply! I am really quite new (typical response) so I don't know all the 'ins and outs' of what you're saying. For example, MAC, CBC mode, #6. The Key is being hardcoded in because I'm not sure how else to pass it into the Encryption Class. Referring to your suggestion, if I put the key in a config file, how do I utilize it? Or is that just for storing? Feel free to edit my OP as you deem necessary, if you'd like to elaborate on some of my areas in which I lack knowledge. Thanks!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T15:24:33.923", "Id": "43067", "ParentId": "42954", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T13:11:01.067", "Id": "42954", "Score": "1", "Tags": [ "security", "vb.net", "cryptography" ], "Title": "How can this Encryption Class be more secure?" }
42954
<p>I am developing a UI Application for a very simple phone app, the UI is based entirely on the state of Call in a container provided to me by a third party library. </p> <p>Below is a sample Call object that I am working with;</p> <pre><code>public class Call { private boolean isTannoyCall; private long callStart; private int callId; private int callState; private CallDirection mCallDirection = CallDirection.OUTGOING; private int mediaStatus; private boolean mediaHasVideoStream; private long connectStart; private int lastStatusCode; private boolean callIsMuted; private boolean callIsInConference; //removed getters and setters } </code></pre> <p>A populated call object is then passed around my application, in various places I have to carry out business logic to check if I should be carrying out an action etc. Below is an example of an event listener method for new calls within the app.</p> <pre><code>public void update() { int activeCallCount = 0; int incomingCallCount = 0; for (Call call : container.getCalls()) { boolean isIncomingDirection = call.getCallDirection() == CallDirection.INCOMING; boolean isIncomingCall = isIncomingDirection &amp;&amp; call.getCallState() == CallState.INCOMING &amp;&amp; !call.isTannoyCall(); boolean isActiveCall = call.isActive() &amp;&amp; call.getCallState() != call.InvState.INCOMING &amp;&amp; !call.isTannoyCall(); if (isIncomingCall) { incomingCallCount++; } else if (isActiveCall) { activeCallCount++; } boolean isMissedCall = isIncomingDirection &amp;&amp; call.getCallState() == call.InvState.DISCONNECTED &amp;&amp; call.getCallStart() == 0 &amp;&amp; !call.isTannoyCall(); if (isMissedCall) { missedCallManager.increment(); } } incomingCallUpdate(incomingCallCount); activeCallUpdate(activeCallCount); } </code></pre> <p>In areas of the application where I need to do a lot of boolean based checks, like sample 1. How can I do this whilst keeping the code maintainable? As every time I need to add a new condition (e.g. the latest "don't update if tannoy call"), I have to modify the appropriate <code>if</code> statements.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T15:21:57.083", "Id": "74070", "Score": "0", "body": "Minor issues in your post that you could fix : I would add the language to your question and there is one code block that is missing a bracket in the formatted block. Except for that excellent question!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T15:50:19.287", "Id": "74077", "Score": "0", "body": "Thanks, I originally avoided the language tag as I was hoping to attract answers from users with various programming styles :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T16:37:39.157", "Id": "74085", "Score": "0", "body": "In my experience, people here don't limit themselves to one language and answer if they have something to say!" } ]
[ { "body": "<p>It seems <a href=\"http://c2.com/cgi/wiki?DataEnvy\" rel=\"nofollow\">data</a>/<a href=\"http://c2.com/cgi/wiki?FeatureEnvySmell\" rel=\"nofollow\">feature</a> envy. Move the boolean conditions to the <code>Call</code> object:</p>\n\n<pre><code>public class Call {\n ...\n\n public boolean isIncomingDirection()\n return callDirection == CallDirection.INCOMING;\n }\n\n public boolean isIncomingCall() {\n return isIncomingDirection()\n &amp;&amp; callState == CallState.INCOMING &amp;&amp; !isTannoyCall;\n }\n\n public boolean isActiveCall() {\n return isActive()\n &amp;&amp; callState != InvState.INCOMING &amp;&amp; !isTannoyCall;\n }\n\n public boolean isMissedCall() {\n return isIncomingDirection()\n &amp;&amp; callState == InvState.DISCONNECTED\n &amp;&amp; callStart == 0\n &amp;&amp; !isTannoyCall;\n } \n}\n</code></pre>\n\n<p>See also: <em>Clean Code</em> by <em>Robert C. Martin</em>, <em>G14: Feature Envy</em></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T15:01:53.727", "Id": "74066", "Score": "5", "body": "One of the best books I've ever read! Get that book, read it, and then read it again!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T15:15:45.653", "Id": "74067", "Score": "1", "body": "This really helps with the first sample." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T14:27:20.273", "Id": "42959", "ParentId": "42955", "Score": "4" } } ]
{ "AcceptedAnswerId": "42959", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T13:21:55.403", "Id": "42955", "Score": "4", "Tags": [ "java", "design-patterns" ], "Title": "How to make business logic code maintainable when working with multiple states?" }
42955
<p>Below is my implementation of templated <code>Node</code> and <code>LinkedList</code> classes. I would really appreciate it if someone would give me pointers on what I can improve.</p> <pre><code>//LinkedList with SumLists() #include &lt;iostream&gt; #include &lt;set&gt; using namespace std; template&lt;class T&gt; class Node { public: T data; Node&lt;T&gt; * next; Node&lt;T&gt;(const T&amp; d):data(d), next() {} Node&lt;T&gt;(const Node&lt;T&gt;&amp; copyNode) : data(copyNode.data), next() {} private: Node&lt;T&gt;&amp; operator=(const Node&lt;T&gt;&amp;); }; template&lt;class T&gt; class LinkedList { public: Node&lt;T&gt; * head; Node&lt;T&gt; * tail; LinkedList(const LinkedList&amp; LL); LinkedList&amp; operator=(LinkedList byValList); LinkedList(): head(NULL), tail(NULL) {} LinkedList(Node&lt;T&gt; * newNode) : head(newNode), tail(newNode) {} ~LinkedList(); static LinkedList&lt;int&gt; sumLists(const LinkedList&lt;int&gt;&amp; LL1, LinkedList&lt;int&gt;&amp; LL2); void insertToTail(T val); void insertToHead(T val); void print(); void printBackwards(); }; template&lt;class T&gt; LinkedList&lt;T&gt;::LinkedList(const LinkedList&lt;T&gt;&amp; LL) : head(NULL), tail(NULL) { const Node&lt;T&gt; * curr = LL.head; if (!head &amp;&amp; curr) { head = new Node&lt;T&gt;(curr-&gt;data); tail = head; curr = curr-&gt;next; } while (curr) { Node&lt;T&gt; * newNode = new Node&lt;T&gt;(curr-&gt;data); tail-&gt;next = newNode; tail = newNode; curr = curr-&gt;next; } } template&lt;class T&gt; LinkedList&lt;T&gt;&amp; LinkedList&lt;T&gt;::operator=(LinkedList byValList) { std::swap(head, byValList.head); return *this; } template&lt;class T&gt; LinkedList&lt;T&gt;::~LinkedList() { Node&lt;T&gt; * curr = head; while (head) { head = head-&gt;next; delete curr; curr = head; } } template&lt;class T&gt; void LinkedList&lt;T&gt;::insertToTail(T val) { Node&lt;T&gt; * newNode = new Node&lt;T&gt;(val); if (tail == NULL) { newNode-&gt;next = tail; tail = newNode; head = newNode; return; } tail-&gt;next = newNode; tail = tail-&gt;next; } template&lt;class T&gt; void LinkedList&lt;T&gt;::insertToHead(T val) { Node&lt;T&gt; * newNode = new Node&lt;T&gt;(val); newNode-&gt;next = head; head = newNode; if (head-&gt;next == NULL) tail = newNode; } template&lt;class T&gt; void LinkedList&lt;T&gt;::print() { Node&lt;T&gt; * curr = head; while (curr) { cout&lt;&lt;curr-&gt;data&lt;&lt;" --&gt; "; curr = curr-&gt;next; } cout&lt;&lt;"NULL"&lt;&lt;endl; } template&lt;class T&gt; void LinkedList&lt;T&gt;::printBackwards() { Node&lt;T&gt; * curr; LinkedList ReversedList(new Node&lt;T&gt;(head-&gt;data)); curr = head-&gt;next; while (curr) { ReversedList.insertToHead(curr-&gt;data); curr = curr-&gt;next; } curr = ReversedList.head; while (curr) { cout&lt;&lt;curr-&gt;data&lt;&lt;" --&gt; "; curr = curr-&gt;next; } cout&lt;&lt;"NULL\n"; } template&lt;class T&gt; LinkedList&lt;int&gt; LinkedList&lt;T&gt;::sumLists(const LinkedList&lt;int&gt;&amp; LL1, LinkedList&lt;int&gt;&amp; LL2) { Node&lt;T&gt;* curr1 = LL1.head; Node&lt;T&gt;* curr2 = LL2.head; LinkedList&lt;int&gt; ResultList; int newData; int carry = 0; while (curr1 &amp;&amp; curr2) { newData = (curr1-&gt;data + curr2-&gt;data + carry) % 10; carry = (curr1-&gt;data + curr2-&gt;data + carry) / 10; ResultList.insertToTail(newData); curr1 = curr1-&gt;next; curr2 = curr2-&gt;next; } while (curr1 || curr2) { if (carry) { if (curr1) ResultList.insertToTail(curr1-&gt;data + carry); if (curr2) ResultList.insertToTail(curr2-&gt;data + carry); carry = 0; continue; } if (curr1) { ResultList.insertToTail(curr1-&gt;data); curr1 = curr1-&gt;next; } if (curr2) { ResultList.insertToTail(curr2-&gt;data + carry); curr2 = curr2-&gt;next; } } return ResultList; } int main() { LinkedList&lt;int&gt; LL1(new Node&lt;int&gt;(7)); LL1.insertToTail(1); LL1.insertToTail(6); LL1.insertToTail(5); LL1.insertToTail(4); LinkedList&lt;int&gt; LL2(new Node&lt;int&gt;(5)); LL2.insertToTail(9); LL2.insertToTail(2); LinkedList&lt;int&gt; LL = LL1.sumLists(LL1, LL2); LL.print(); LL2.print(); LL = LL2; LL.print(); LL2.print(); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T15:58:36.970", "Id": "74308", "Score": "1", "body": "By the way, you can remove `#include <set>` since it's used nowhere in the code." } ]
[ { "body": "<p>Some observations:</p>\n\n<p>Your data should (probably) be private. Otherwise, an enterprising developer will do this:</p>\n\n<pre><code>LinkedList&lt;int&gt; l;\n// naively delete contents of l\ndelete l.head;\n</code></pre>\n\n<p><code>Node</code> is an implementation detail of the list. It makes no sense to define it outside the class.</p>\n\n<p>That means, the code should look like this:</p>\n\n<pre><code>template&lt;class T&gt;\nclass LinkedList\n{\n// private:\n struct Node // Node is a private implementation detail\n {\n T data;\n Node *next;\n Node(const T&amp; d):data(d), next() {}\n Node(const Node&amp; copyNode) : data(copyNode.data), next() {}\n\n private:\n Node&amp; operator=(const Node&amp;);\n };\n Node* head;\n Node* tail;\n\npublic:\n // ... rest of code here\n};\n</code></pre>\n\n<p>After making head and tail private, you will need to add iteration and/or data retrieval API to your class.</p>\n\n<p>When designing a class, consider how you will look at it from the perspective of client code, not how it is implemented (i.e. you are implementing a \"list of instances of T\", not a \"list of instances of Node\"). That means you should not have a constructor receiving a Node*, but a constructor receiving a T instance.</p>\n\n<p>Your print and printBackwards functions should (probably) receive the output stream as a parameter (then, you can use the same code to print to a std::ostringstream, std::fstream, std::cout and so on).</p>\n\n<p>Your copy&amp;swap implementation of assignment should be written like this:</p>\n\n<pre><code>template&lt;class T&gt;\nLinkedList&lt;T&gt;&amp; LinkedList&lt;T&gt;::operator=(LinkedList byValList)\n{\n using std::swap; // enable ADL\n swap(*this, byValList); // implementation swaps by moving if there's a\n // LinkedList&lt;T&gt;::LinkedList&lt;T&gt;(LinkedList&lt;T&gt;&amp;&amp;)\n // defined; (consider defining it)\n\n return *this;\n}\n</code></pre>\n\n<p>This function could use a std::move:</p>\n\n<pre><code>template&lt;class T&gt;\nvoid LinkedList&lt;T&gt;::insertToTail(T val)\n{\n Node&lt;T&gt; * newNode = new Node&lt;T&gt;(std::move(val)); // &lt;&lt;&lt;&lt;&lt; \n // ... \n}\n</code></pre>\n\n<p>For a POD-type T it's fine without it, but what happens if I write</p>\n\n<pre><code>LinkedList&lt;std::string&gt; l;\nstd::string s{' ', 10000};\nl.insertToTail(s); // creates one copy of s for argument, and one for the node\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T16:15:40.027", "Id": "74079", "Score": "2", "body": "`implementation swaps by moving` if there is a move constructor. Otherwise it does it by copying. By default there is not a move constructor." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T16:42:41.300", "Id": "74086", "Score": "0", "body": "@LokiAstari, I hadn't known that (have an upvote :))." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T15:59:27.930", "Id": "42964", "ParentId": "42958", "Score": "9" } }, { "body": "<p>Please. Oh please stop doing this.</p>\n\n<pre><code>using namespace std;\n</code></pre>\n\n<p>If this was a header file you just polluted the global namespace for anybody that uses your file. This will get it banned from any serious project. This is done in textbooks for some reason and is fine for short ten line example programs. But once you get past 10 lines it has issues. Stop using it; it is a bad habbit that will get you into real problems on any decent sized project.</p>\n\n<p><a href=\"https://stackoverflow.com/q/1452721/14065\"><em>Why is “using namespace std;” considered bad practice?</em></a></p>\n\n<p>You do really the standard library is in the namespace std. So it only costs you 5 extra characters to use it.</p>\n\n<pre><code>std::list&lt;T&gt; myList;\n</code></pre>\n\n<p>Node is an implementation detail of the list. There is no reason for anybody using the list to know exactly how you implemented. Nor is there a reason to provide them with a <code>Node</code> class (as you will now need to maintain that concept).</p>\n\n<pre><code>template&lt;class T&gt;\nclass Node\n{\npublic:\n T data;\n Node&lt;T&gt; * next;\n Node&lt;T&gt;(const T&amp; d):data(d), next() {}\n Node&lt;T&gt;(const Node&lt;T&gt;&amp; copyNode) : data(copyNode.data), next() {}\n\nprivate:\n Node&lt;T&gt;&amp; operator=(const Node&lt;T&gt;&amp;);\n};\n</code></pre>\n\n<p>So I would make <code>Node</code> a private member of <code>LinkedList</code>.</p>\n\n<p>Its not really a copy constructor if you don't copy the <code>next</code> member.</p>\n\n<pre><code>Node&lt;T&gt;(const Node&lt;T&gt;&amp; copyNode) : data(copyNode.data), next() {}\n</code></pre>\n\n<p>But OK. I can see this as an optimization.\nBut personally I would have used a third constructor.</p>\n\n<pre><code>Node&lt;T&gt;(const Node&lt;T&gt;&amp; copyNode, Node&lt;T&gt;* next)\n : data(copyNode.data)\n , next(next) \n{}\n</code></pre>\n\n<p>Then you can pass NULL as the second parameter, to initialize next.</p>\n\n<p>So you have disabled the assignment operator:</p>\n\n<pre><code>private:\n Node&lt;T&gt;&amp; operator=(const Node&lt;T&gt;&amp;);\n</code></pre>\n\n<p>This is correct in C++03. But this is 2014 and C++11 is supported by all modern compilers and most already support C++14. So you should start using the modern version of the language.</p>\n\n<pre><code> Node&lt;T&gt;&amp; operator=(const Node&lt;T&gt;&amp;) = delete;\n</code></pre>\n\n<p>Your implementation of linked list uses NULL as a terminator (which is fine). <strong>But</strong> if you add a fake sentinel value to your list it makes the implementation much easier as you never have NULL pointers (and end points at the sentinel).</p>\n\n<p>In the copy constructor:</p>\n\n<pre><code> if (!head &amp;&amp; curr)\n</code></pre>\n\n<p>At this point <code>head</code> is always NULL. You just set it two lines above.</p>\n\n<p>The other thing to note about the copy is that it will leak if you throw an exception. Since you don't know what the type of <code>T</code> is you have no idea how it will react to being copied. If halfway through the copy it throws an exception you should clean up any memory allocated so far before letting the exception propagate out of the constructor.</p>\n\n<p>You are on the correct track with the assignment operator.</p>\n\n<pre><code>template&lt;class T&gt;\nLinkedList&lt;T&gt;&amp; LinkedList&lt;T&gt;::operator=(LinkedList byValList)\n{\n // BUT this line is not enough\n // Assignment should make a copy of all the elements.\n std::swap(head, byValList.head);\n\n\n // Usually this is implemented as:\n // Now you need to write a version of swap for this class\n // (both member and free standing)\n byValList.swap(*this);\n\n return *this;\n}\n</code></pre>\n\n<p>I would write them like this:</p>\n\n<pre><code>template&lt;class T&gt;\nLinkedList&lt;T&gt;::swap(LinkedList&lt;T&gt;&amp; rhs) noexcept // swap is supposed to be \n{ // free from exception\n std::swap(head, rhs.head); // throwing\n std::swap(tail, rhs.tail);\n}\n\ntemplate&lt;class T&gt;\nvoid swap(LinkedList&lt;T&gt;&amp; lhs, LinkedList&lt;T&gt;&amp; rhs) {lhs.swap(rhs);}\n</code></pre>\n\n<p>In the destructor:<br>\nYou don't use <code>curr</code> to do anything useful. Remove it.</p>\n\n<pre><code> Node&lt;T&gt; * curr = head;\n\n curr = head;\n</code></pre>\n\n<p>In your insert methods. I personally would return a reference to <code>*this</code> (see below). But in both your insert methods you check for empty is always a bit weird before assigning the other end. I would break the test for empty into its own method <code>empty()</code> then you can test <code>empty()</code> before doing your special case code.</p>\n\n<pre><code>template&lt;class T&gt;\nLinkedList&lt;T&gt;&amp; LinkedList&lt;T&gt;::insertToTail(T val);\n</code></pre>\n\n<p>This allows you to use operator chaining.</p>\n\n<pre><code>LinkedList&lt;T&gt; list;\nlist.insertToTail(1).insertToTail(2).insertToTail(3);\n</code></pre>\n\n<p>Nothing wrong with a print method. But I would do three additional things. As the <code>print()</code> method does not modify the content of the list it should be marked as <code>const</code>. Rather than always printing to <code>std::cout</code> I would pass the output stream as a parameter (it can default to <code>std::cout</code> when none is provided. I would also write the output operator <code>operator&lt;&lt;</code> as that is the normal way of printing in C++.</p>\n\n<pre><code>template&lt;class T&gt;\nvoid LinkedList&lt;T&gt;::print(std::ostream&amp; stream = std::cout) const;\n\nstd::ostream&amp; operator&lt;&lt;(std::ostream&amp; stream, LinkedList&lt;T&gt; const&amp; data)\n{\n data.print(stream);\n return stream;\n}\n</code></pre>\n\n<p>That's an expensive print when done backwards.<br>\nBut once you have the list reversed. Why not re-use your standard print function?</p>\n\n<pre><code>template&lt;class T&gt;\nvoid LinkedList&lt;T&gt;::printBackwards(std::ostream&amp; stream = std::cout) const\n{\n LinkedList&lt;T&gt; rev;\n for(Node&lt;T&gt;* curr = rev.head; curr != NULL; curr = curr-&gt;next)\n { rev.insertToHead(curr-&gt;data);\n }\n rev.print(stream);\n}\n</code></pre>\n\n<p>Finally. In the sumLists. Its fine upto the point. where one list is empty. But the second part where one list is empty is over complex and you have a lot of nested ifs. Why not check and do each list individually.</p>\n\n<pre><code>template&lt;class T&gt;\nLinkedList&lt;int&gt; LinkedList&lt;T&gt;::sumLists(const LinkedList&lt;int&gt;&amp; LL1, LinkedList&lt;int&gt;&amp; LL2)\n{\n // First part good.\n\n // Only one is true.\n // But if you look at the code it is neater.\n // and more self contained.\n while (curr1)\n {\n if (carry)\n {\n ResultList.insertToTail(curr1-&gt;data + carry);\n carry = 0;\n continue;\n }\n ResultList.insertToTail(curr1-&gt;data);\n curr1 = curr1-&gt;next;\n }\n\n while (curr2)\n {\n if (carry)\n {\n ResultList.insertToTail(curr2-&gt;data + carry);\n carry = 0;\n continue;\n }\n ResultList.insertToTail(curr2-&gt;data + carry);\n curr2 = curr2-&gt;next;\n }\n}\n</code></pre>\n\n<p>You will also notice that the two loops are very similar. So you can break that code into a separate method and call it twice.</p>\n\n<pre><code>template&lt;class T&gt;\nLinkedList&lt;int&gt; LinkedList&lt;T&gt;::sumLists(const LinkedList&lt;int&gt;&amp; LL1, LinkedList&lt;int&gt;&amp; LL2)\n{\n // First part good.\n\n // Only one is true.\n // But if you look at the code it is neater.\n // and more self contained.\n AddStuffToListOne(curr1, ResultList);\n AddStuffToListOne(curr2, ResultList);\n\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T16:53:00.293", "Id": "74087", "Score": "0", "body": "Thank you so much for taking the time for such a thorough review. This will be very helpful for me in improving my C++ programming." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T18:30:04.143", "Id": "74098", "Score": "0", "body": "Loki, what do I need the free-standing swap function for?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T21:09:24.187", "Id": "74126", "Score": "0", "body": "The free standing swap help for Kernig look-up (AKA ADL look-up). If you write: `swap(ll1, ll2);` where ll1 and ll2 are `LinkedList<int>` Then it will using Kernig look-up to find your swap implementation which is better than the default swap." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T03:40:27.037", "Id": "74187", "Score": "0", "body": "For being such a long standing contributor to this site, I don't think I have ever invited you to [the chat room](http://chat.stackexchange.com/rooms/8595/the-2nd-monitor). Feel free to come and talk to the regulars sometime. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-28T10:04:27.553", "Id": "200466", "Score": "1", "body": "@LokiAstari I've a humble request to you, please add a section in your answer for complete class code after review. Just for the purpose of comparison in both. Your review is very helpful and it will be more beneficial for beginners to understand the differences you made in the above question code. Thanks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-28T16:08:24.380", "Id": "200546", "Score": "0", "body": "@Superman: Not in the near future. I am a bit overloaded at the moment. But if you do it I will link to it from my question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-28T16:21:00.343", "Id": "200551", "Score": "0", "body": "No problem at all. I'll definitely do this. Right now I'm working on your another review of a beginner linked list. You might see my comments there. I've coded the way you explained, I need to spend sometime on it to understand every bit. Thanks for your awesome explanation. If you can refer me g++ with c++ 11 reference I'll be thankful to you. I'm facing errors only due to the version incompatibility. I'm new to C++." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T16:10:10.143", "Id": "42966", "ParentId": "42958", "Score": "31" } }, { "body": "<p>I suspect there is a BUG in sumLists:</p>\n\n<p>The following part</p>\n\n<blockquote>\n<pre><code>if (carry)\n{\n if (curr1)\n ResultList.insertToTail(curr1-&gt;data + carry);\n if (curr2)\n ResultList.insertToTail(curr2-&gt;data + carry);\n carry = 0;\n continue;\n}\n</code></pre>\n</blockquote>\n\n<p>should be replaced with</p>\n\n<pre><code>if (carry)\n{\n if (curr1)\n {\n ResultList.insertToTail(curr1-&gt;data + carry);\n curr1 = curr1-&gt;next;\n }\n if (curr2)\n {\n ResultList.insertToTail(curr2-&gt;data + carry);\n curr2 = curr2-&gt;next;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-30T19:14:02.450", "Id": "398540", "Score": "0", "body": "Hi, nice catch for a first answer :) Maybe it would also help OP if you explained what you think the bug is, it would also make for a better answer" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-30T18:42:25.960", "Id": "206598", "ParentId": "42958", "Score": "0" } } ]
{ "AcceptedAnswerId": "42966", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T13:43:11.207", "Id": "42958", "Score": "33", "Tags": [ "c++", "linked-list" ], "Title": "LinkedList with Node implementation" }
42958
<p>Basically I have taken over a project and found a table that has the following video and video title fields in it (why they didn't create a separate linked table is beyond me):</p> <pre><code>[VIDEOURL] [VIDEOTITLE] [COUKVIDEO1URL] [COUKVIDEO2URL] [COUKVIDEO3URL] [COUKVIDEO4URL] [COUKVIDEO1TITLE] [COUKVIDEO2TITLE] [COUKVIDEO3TITLE] [COUKVIDEO4TITLE] </code></pre> <p>Can this query be improved to get a single list of titles and urls from the above fields:</p> <pre><code>SELECT t.VIDEOURL, t.VIDEOTITLE FROM ( SELECT VIDEOURL, VIDEOTITLE FROM [VincentV5].[dbo].[MARCMSITEMPRESENTATION] UNION SELECT [COUKVIDEO1URL] AS VIDEOURL, [COUKVIDEO1TITLE] AS VIDEOTITLE FROM [VincentV5].[dbo].[MARCMSITEMPRESENTATION] UNION SELECT [COUKVIDEO2URL] AS VIDEOURL, [COUKVIDEO2TITLE] AS VIDEOTITLE FROM [VincentV5].[dbo].[MARCMSITEMPRESENTATION] UNION SELECT [COUKVIDEO3URL] AS VIDEOURL, [COUKVIDEO3TITLE] AS VIDEOTITLE FROM [VincentV5].[dbo].[MARCMSITEMPRESENTATION] UNION SELECT [COUKVIDEO4URL] AS VIDEOURL, [COUKVIDEO4TITLE] AS VIDEOTITLE FROM [VincentV5].[dbo].[MARCMSITEMPRESENTATION] ) t WHERE t.VIDEOURL != '' AND t.VIDEOTITLE != '' </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T16:34:18.327", "Id": "74084", "Score": "3", "body": "this schema makes me shiver.." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T18:39:56.337", "Id": "74099", "Score": "0", "body": "Can you modify or add a new table? I'm not good in SQL, but I really feel that the real problem is not the query but the table. I know that sometime you can't modify existing table or have some limitations of some kinds." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T08:46:25.127", "Id": "74243", "Score": "1", "body": "@Marc-Andre unfortunately not, the data is being replicated from some internal systems and I am unable to touch that or the db server" } ]
[ { "body": "<p>There is no telling how the database will optimize the query plan for this, but I would expect that the best query plan would involve applying the predicates to the tables before the union is done. Doing a UNION of multiple small result sets would be more efficient than doing a union on large sets and then filtering the results.</p>\n\n<p>The UNION operation requires a lot of scanning because UNION is also a DISTINCT process (you only have one record of each value in the result).</p>\n\n<p>So, two things.</p>\n\n<p>If you are sure that the values in in a column-pair will not also be in any of the other column-pairs, then you can replace the <code>UNION</code> with the faster <code>UNION ALL</code>.</p>\n\n<p>If you are sure that a column-pair is unique, or empty, then you can avoid the DISTINCT process completely.</p>\n\n<p>I would write the query as:</p>\n\n<pre><code> SELECT VIDEOURL,\n VIDEOTITLE\n FROM [VincentV5].[dbo].[MARCMSITEMPRESENTATION]\n WHERE [VIDEOURL] != ''\n AND [VIDEOTITLE] != ''\n UNION ALL\n SELECT [COUKVIDEO1URL] AS VIDEOURL,\n [COUKVIDEO1TITLE] AS VIDEOTITLE\n FROM [VincentV5].[dbo].[MARCMSITEMPRESENTATION]\n WHERE [COUKVIDEO1URL] != ''\n AND [COUKVIDEO1TITLE] != ''\n UNION ALL\n SELECT [COUKVIDEO2URL] AS VIDEOURL,\n [COUKVIDEO2TITLE] AS VIDEOTITLE\n FROM [VincentV5].[dbo].[MARCMSITEMPRESENTATION]\n WHERE [COUKVIDEO2URL] != ''\n AND [COUKVIDEO2TITLE] != ''\n UNION ALL\n SELECT [COUKVIDEO3URL] AS VIDEOURL,\n [COUKVIDEO3TITLE] AS VIDEOTITLE\n FROM [VincentV5].[dbo].[MARCMSITEMPRESENTATION]\n WHERE [COUKVIDEO3URL] != ''\n AND [COUKVIDEO3TITLE] != ''\n UNION ALL\n SELECT [COUKVIDEO4URL] AS VIDEOURL,\n [COUKVIDEO4TITLE] AS VIDEOTITLE\n FROM [VincentV5].[dbo].[MARCMSITEMPRESENTATION]\n WHERE [COUKVIDEO4URL] != ''\n AND [COUKVIDEO4TITLE] != ''\n</code></pre>\n\n<p>If values in one column-pair can appear in other column pairs, then change the <code>UNION</code> to <code>UNION ALL</code>.</p>\n\n<p>If the values can be duplicated in a column-pair, then add <code>DISTINCT</code> to each <code>SELECT</code>.</p>\n\n<p>Do both <code>DISTINCT</code> and <code>UNION ALL</code> if you need to.</p>\n\n<p>The idea is to make the data as small as possible before you start doing the big merging processes.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T18:48:15.600", "Id": "42972", "ParentId": "42967", "Score": "3" } } ]
{ "AcceptedAnswerId": "42972", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T16:30:12.703", "Id": "42967", "Score": "4", "Tags": [ "sql", "sql-server" ], "Title": "Best way to get two columns from a table" }
42967
<p>The problem was pretty straightforward and used two simple algorithms from our examples; the one for computing the sum, and the one for counting matches. The array for the problem wasn't provided, but you can easily write a method around it without actually having it, since she gave us the name and type of the array. The code for my solution is this:</p> <pre><code> public class Tests { private double[] grades; public int belowAverage() // Creates method for finding scores below the mean { double total = 0; for (double element1 : grades) // Computes total of array 'grades' { total=total + element1; } double mean = total / grades.length; //Uses total and the length of the array to computer the mean int matches = 0; for (double element2 : grades) //Uses mean to compute number of grades that are below the mean and { // increases matches for each one that is. if (element2 &lt; mean) {matches++;} } return matches; // Returns the number of matches. } } </code></pre> <p>Obviously the third line would change if you had the actual array. That was just kind of a placeholder. I tried to notate the code well enough to see where you get the total, then the mean, then compare each one to the mean to get matches that are less and increase your 'matches' variable for each match. I could have used the same 'element' variable for both loops since they're only used within the loops, but for clarity's sake in this example, I named them differently. I put all of these steps together in one method to solve this problem, but if I were going to write this sort of thing 'for real', I would assume it would probably need to calculate much more than just this small task (different averages, highest/lowest, etc.), so I would probably put each step in its own method so it could be used wherever you needed it.</p> <p>Can someone comment on this and tell me if I could have done this in another way or an easier way? Maybe I could have used arrays.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T17:08:53.733", "Id": "74089", "Score": "2", "body": "there is no point in the review, if you do not post the code you actually consider best! You should apply the refactorings you propose in your question itself and edit your question" } ]
[ { "body": "<ol>\n<li><p>From <em>Steve McConnell</em>, <em>Code Complete 2nd Edition</em>, <em>31.2 Layout Techniques</em>, p737:</p>\n\n<blockquote>\n <p>Using blank lines is a way to indicate how a program is organized. You can use them\n to divide groups of related statements into paragraphs, to separate routines from one\n another, and to highlight comments.</p>\n</blockquote>\n\n<p>It does not make sense if all groups contain only one line.</p></li>\n<li><p>This comment is mostly noise:</p>\n\n<pre><code>return matches; // Returns the number of matches.\n</code></pre>\n\n<p>as well as this one:</p>\n\n<pre><code>// Uses total and the length of the\n// array to computer the mean\ndouble mean = total / grades.length;\n</code></pre>\n\n<p>They don't say anything more that the code already does. I'd remove them. (<em>Clean Code</em> by <em>Robert C. Martin</em>: <em>Chapter 4: Comments, Noise Comments</em>)</p></li>\n<li><p>I would call both <code>element1</code> and <code>element2</code> as <code>element</code>. It's more common. Having <code>element1</code> and <code>element2</code> suggest a little bit that they are used together (but that's not the case).</p></li>\n<li><p>Comments like this are not too easy to read on because of the horizontal scrolling and the unnecessary spaces:</p>\n\n<pre><code>{ // increases matches for each one that is.\n</code></pre>\n\n<p>You could put them a line above of the method/loop/variable declaration (and eliminate them later).</p></li>\n<li><blockquote>\n <p>[...] if I were going to write this sort of thing 'for real', \n I would assume it would probably need to calculate much more \n than just this small task (different averages, \n highest/lowest, etc.), so I would probably put each step \n in its own method so it could be used wherever you needed it.</p>\n</blockquote>\n\n<p>You should to that now. It would eliminate most of the comments and increase the abstraction level of the method. A maintainer would be grateful, it's easier to get an overview what the method does (without the details) and you can still check them if you are interested in. Furthermore, you need to read and understand less code (not the whole original method) if you modify just a small part of it.</p>\n\n<p>Finally, cleaning the code usually costs less during writing than later. Now you probably know the details better than later, therefore it's faster.</p>\n\n<pre><code>public int scoresBelowMean() {\n double total = getGradesTotal();\n double mean = total / grades.length;\n return gradesCountBelowMean(mean);\n}\n\nprivate double getGradesTotal() {\n double total = 0;\n for (double element: grades) {\n total = total + element;\n }\n return total;\n}\n\nprivate int gradesCountBelowMean(double mean) {\n int matches = 0;\n for (double element: grades) {\n if (element &lt; mean) {\n matches++;\n }\n }\n return matches;\n}\n</code></pre>\n\n<p>(<em>Clean Code</em> by <em>Robert C. Martin</em>, <em>One Level of Abstraction per Function</em>, p36)</p></li>\n<li><p>Instead of doubles (and floating point numbers) you might want to use <code>BigDecimal</code>s. Floating point numbers are not precise. Here is an example:</p>\n\n<ul>\n<li><em>Effective Java, 2nd Edition, Item 48: Avoid float and double if exact answers are required</em></li>\n<li><a href=\"https://stackoverflow.com/q/3730019/843804\">Why not use Double or Float to represent currency?</a></li>\n</ul></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T20:09:38.780", "Id": "42975", "ParentId": "42968", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T16:54:49.733", "Id": "42968", "Score": "2", "Tags": [ "java", "array" ], "Title": "Computing sum and counting matches in an array" }
42968
<p>I have some code which works fine. First, it checks that dates format are valid and then, checks that first date is lower than second date. I had to use free input text and custom validator because multiple date formats are supported such as quarter number (2014 Q1) etc.</p> <p>But I find my code too long for what it's doing. Any advice on code improvement ? </p> <p><a href="http://jsfiddle.net/franchez/E6eUN/46/">DEMO</a></p> <pre><code>function check_handler(){ var from = $('#zeDateFrom').val(), to = $('#zeDateTo').val(); if(adu_date_format(from) &amp;&amp; adu_date_format(to)){ if( check_date_period(from.trim(), to.trim()) ){ alert('OK'); } else alert('Start Date must be lower then End Date.'); } else{ alert('Please use a valid date format. For your information, valid formats are:\ndd/mm/yyyy (e.g 11/12/2011)\n yyyy (e.g 2010)\n mm/yyyy (e.g 11/2009)\n and yyyy qq (e.g 2012 Q2).'); } } function check_date_period(from, to){ var result = false; var yearFrom, yearTo, monthFrom, monthTo, dayFrom, dayTo; // 0) If something to compare... if(from==""||to=="") return true; // 1) Test if input is type year only if(from.length==4){ yearFrom = from; monthFrom = 1; dayFrom = 1; } if(to.length==4){ yearTo = to; monthTo = 12; dayTo = 0; // 0 for last day of month } // 2) Test if input is type year[space] quarter var mySplit = from.split(" "); if(mySplit.length == 2){ yearFrom = mySplit[0]; dayFrom = 1; if(mySplit[1]=='Q1'){ monthFrom = 1; } if(mySplit[1]=='Q2'){ monthFrom = 4; } if(mySplit[1]=='Q3'){ monthFrom = 7; } if(mySplit[1]=='Q4'){ monthFrom = 10; } } mySplit = to.split(" "); if(mySplit.length == 2){ yearTo = mySplit[0]; dayTo = 0; if(mySplit[1]=='Q1'){ monthTo = 3; } if(mySplit[1]=='Q2'){ monthTo = 6; } if(mySplit[1]=='Q3'){ monthTo = 9; } if(mySplit[1]=='Q4'){ monthTo = 12; } } // 3) Test if input is type month/year mySplit = from.split("/"); if(mySplit.length == 2){ yearFrom = mySplit[1]; monthFrom = mySplit[0]; dayFrom = 1; } mySplit = to.split("/"); if(mySplit.length == 2){ yearTo = mySplit[1]; monthTo = mySplit[0]; dayTo = 0; // 0 for last day of month } // 4) test if input is type dd/mm/yyyy mySplit = from.split("/"); if(mySplit.length == 3){ yearFrom = mySplit[2]; monthFrom = mySplit[1]; dayFrom = mySplit[0]; } mySplit = to.split("/"); if(mySplit.length == 3){ yearTo = mySplit[2]; monthTo = mySplit[1]; dayTo = mySplit[0]; } // FINALLY: Compare dates // Note: 00 is month i.e. January monthFrom--; if(dayTo!=0) monthTo--; var dateOne = new Date(yearFrom, monthFrom, dayFrom); //Year, Month, Day var dateTwo = new Date(yearTo, monthTo, dayTo); //Year, Month, Day //alert(dayFrom+'/'+(monthFrom-1)+'/'+yearFrom+'---------'+dayTo+'/'+(monthTo-1)+'/'+yearTo) //alert(dateOne+'-'+dateTwo); if (dateOne &lt; dateTwo) { result = true; } return result; } function adu_date_format(text){ var result = false; // 0) If something to test... if(text=="") return true; // 1) Test if input is type year only if(text.length == 4){ if(text &gt;= 2000 &amp;&amp; text &lt;= 2030) result = true; } // 2) Test if input is type year[space] quarter var mySplit = text.split(" "); if(mySplit.length == 2){ if((mySplit[0] &gt;= 2000 &amp;&amp; mySplit[0] &lt;= 2030) &amp;&amp; (mySplit[1].length == 2 &amp;&amp; mySplit[1] &gt;= 'Q1' &amp;&amp; mySplit[1] &lt;= 'Q4')) result = true; } // 3) Test if input is type month/year mySplit = text.split("/"); if(mySplit.length == 2){ if((mySplit[0] &gt;= 1 &amp;&amp; mySplit[0] &lt;= 12) &amp;&amp; (mySplit[1] &gt;= 2000 &amp;&amp; mySplit[1] &lt;= 2030)) result = true; } // 4) test if input is type dd/mm/yyyy mySplit = text.split("/"); if(mySplit.length == 3){ if(mySplit[2] &gt;= 2000 &amp;&amp; mySplit[2] &lt;= 2030) result = true; } return result; } </code></pre>
[]
[ { "body": "<p>What jumps me most about this code is that all you do is in 2 functions.</p>\n\n<p>consider moving your \"parsing\" operations to separate functions, one for validating the format required for parsing and one for the actual parsing:</p>\n\n<pre><code>function isValidQuarterInput(datestring){\n return datestring.split(\" \").length == 2;\n}\n\nfunction parseQuarterInputToMonth(datestring){\n var mySplit = datestring.split(\" \");\n //move your Q1,Q2,... mapping here\n}\n</code></pre>\n\n<p><hr/>\nthen in check_date_period() you can just call the following</p>\n\n<pre><code>if(isValidQuarterInput(from)){monthFrom = parseQuarterInputToMonth(from);}\n// this is the alternative ternary operator\nmonthTo = isValidQuarterInput(to) ? parseQuarterInputToMonth(to) : monthTo;\n</code></pre>\n\n<p>your <code>var result = false</code> is unnecessary, as you never use it elsewhere, you can just do the following for return: </p>\n\n<pre><code>return dateOne &lt; dateTwo;\n</code></pre>\n\n<p><hr/>\nI personally would set a <code>boolean wasParsed</code> to be set to true on correct parsing of one input to jump to the <code>new Date()</code> part. This can potentially save execution time, but that's minor. You would have to move the parsing in the following order though:</p>\n\n<pre><code>var wasParsed = false;\nif(from.length==4){\n yearFrom = from; monthFrom = 1; dayFrom = 1;\n wasParsed = true;\n}\n\nif(!wasParsed){\n if(isValidQuarterInput(from)){\n wasParsed = true;\n monthFrom = parseQuarterInputToMonth(from);\n yearFrom = from.split(\" \")[0];\n dayFrom = 1;\n }\n}\n\nif(!wasParsed){\n //here is the full date parsing\n}\nvar dateOne = new Date(yearFrom, monthFrom, dayFrom); \nwasParsed = false;\n//repeat with to\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T18:44:09.237", "Id": "42971", "ParentId": "42969", "Score": "4" } } ]
{ "AcceptedAnswerId": "42971", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T16:56:59.033", "Id": "42969", "Score": "5", "Tags": [ "javascript", "datetime", "validation" ], "Title": "Date range validator" }
42969
<p>I am working through Kernighan and Ritchie to brush up on my C skills, so I thought I would invite critiques of my code.</p> <p>Here is my Hex-to-int function:</p> <pre><code>int htoi(char *str, unsigned long long *result) { int c; int i; int msnibble; int digits; const int nibbles[] = {'\x0','\x1','\x2','\x3', \ '\x4','\x5','\x6','\x7', \ '\x8','\x9','\xA','\xB', \ '\xC','\xD','\xE','\xF'}; if (NULL == result) { printf("Invalid pointer\n"); return -1; } if ('x' == str[1] || 'X' == str[1]) { msnibble = 2; digits = strlen(str) - 2; } else { msnibble = 0; digits = strlen(str); } if (digits &gt; 16) { printf("Too many hex digits\n"); return -1; } for (i=0, *result = 0; '\0' != (c = str[i+msnibble]); i++) { if ( c &gt;= 'a' &amp;&amp; c &lt;= 'f') { c = c - 'a' + 10; } else if (c &gt;= 'A' &amp;&amp; c &lt;= 'F') { c = c - 'A' + 10; } else if (c &gt;= '0' &amp;&amp; c &lt;= '9') { c -= '0'; } else { printf("Non Hex Character Detected; Exiting\n"); return -1; } *result = *result &lt;&lt; 4 | nibbles[c]; } return 0; } </code></pre> <p>I also tried a solution using the math library. Using pow, I would get correct output until I passed 0xffffffffffffffff and then it would be one greater than the correct answer. This is why I settled on using the array of nibbles.</p> <p><strong>Edit 1:</strong></p> <pre><code>int htoi(const char *str, unsigned long long *result) { int c; int i; int msnibble; int digits; if (NULL == result) { printf("Invalid pointer\n"); return -1; } if ('0' == str[0]) { if ('x' == str[1] || 'X' == str[1]) { msnibble = 2; digits = strlen(str) - 2; } else { msnibble = 0; digits = strlen(str); } } if (digits &gt; 16) { printf("Too many hex digits\n"); return -1; } else if (0 == digits) return -1; for (i=0, *result = 0; '\0' != (c = str[i+msnibble]); i++) { if ( c &gt;= 'a' &amp;&amp; c &lt;= 'f') { c = c - 'a' + 10; } else if (c &gt;= 'A' &amp;&amp; c &lt;= 'F') { c = c - 'A' + 10; } else if (c &gt;= '0' &amp;&amp; c &lt;= '9') { c -= '0'; } else { printf("Non hex character detected; Exiting\n"); return -1; } *result = *result &lt;&lt; 4 | c; } return 0; } </code></pre> <p><strong>Edit 2:</strong></p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &lt;stdlib.h&gt; enum status { NOINPUT = -1, INVPTR = -2, TOOBIG = -3, NOHEX = -4, NONHEX = -5}; int htoi(const char *str, unsigned long long *result); int main(int argc, char *argv[]) { unsigned long long result; if (argc &lt;= 1) { printf("No input!\n"); return EXIT_FAILURE; } if (0 &gt; htoi(argv[1],&amp;result)) return EXIT_FAILURE; else printf("Value = %llu, strtol says %lu\n", result, strtol(argv[1],NULL,16)); return EXIT_SUCCESS; } int htoi(const char *str, unsigned long long *result) { int c; int i; int msnibble = 0; int digits = 0; if (NULL == result) { printf("Invalid pointer\n"); return INVPTR; } if ('0' == str[0] &amp;&amp; 'x' == str[1] || 'X' == str[1]) { msnibble = 2; digits = strlen(str) - 2; } else { msnibble = 0; digits = strlen(str); } if (digits &gt; 16) { printf("Too many hex digits\n"); return TOOBIG; } else if (0 == digits) { printf("Nothing to do\n"); return NOHEX; } for (i=0, *result = 0; '\0' != (c = str[i+msnibble]); i++) { if ( c &gt;= 'a' &amp;&amp; c &lt;= 'f') c = c - 'a' + 10; else if (c &gt;= 'A' &amp;&amp; c &lt;= 'F') c = c - 'A' + 10; else if (c &gt;= '0' &amp;&amp; c &lt;= '9') c -= '0'; else { printf("Non hex character detected; Exiting\n"); return NONHEX; } *result = *result &lt;&lt; 4 | c; } return EXIT_SUCCESS; } </code></pre> <p><strong>Edit 3:</strong></p> <p>I decided to simplify the error reporting and get rid of the <code>printf</code>s. I also fixed the precedence error. I am omitting the braces on the <code>if</code>s because I am following <a href="https://www.kernel.org/doc/Documentation/CodingStyle" rel="nofollow">this</a>. I am trying to follow the kernel style. Next time, I will include that with my post. I apologize for any confusion. I also got rid of <code>i</code> and <code>msnibble</code> as the pointer arithmetic is much simpler. </p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &lt;stdlib.h&gt; int htoi(const char *str, unsigned long *result); int main(int argc, char *argv[]) { unsigned long result; if (argc &lt;= 1) { printf("No input!\n"); return EXIT_FAILURE; } if (0 &gt; htoi(argv[1],&amp;result)) return EXIT_FAILURE; else printf("Value = %llu, strtol says %lu\n", result, strtol(argv[1],NULL,16)); return EXIT_SUCCESS; } int htoi(const char *str, unsigned long *result) { int c; int digits; if ('0' == str[0] &amp;&amp; ('x' == str[1] || 'X' == str[1])) str += 2; digits = strlen(str); if (digits &gt; sizeof(long)*2 || 0 == digits) return -1; for (*result = 0; '\0' != (c = *str); str++) { if ( c &gt;= 'a' &amp;&amp; c &lt;= 'f') c = c - 'a' + 10; else if (c &gt;= 'A' &amp;&amp; c &lt;= 'F') c = c - 'A' + 10; else if (c &gt;= '0' &amp;&amp; c &lt;= '9') c -= '0'; else return -1; *result = *result &lt;&lt; 4 | c; } return 0; } </code></pre> <p><strong>Edit 4:</strong></p> <pre><code> #include &lt;stdlib.h&gt; #include &lt;limits.h&gt; #include &lt;errno.h&gt; int htoi(const char *s, unsigned long *res); int main(int argc, char *argv[]) { unsigned long res; if (argc &lt;= 1) { printf("No input!\n"); return EXIT_FAILURE; } if (0 &gt; htoi(argv[1],&amp;res)) return EXIT_FAILURE; else printf("Value = %llu, strtol says %lu\n", res, strtol(argv[1],NULL,16)); return EXIT_SUCCESS; } int htoi(const char *s, unsigned long *res) { int n; int digits; if ('0' == s[0] &amp;&amp; ('x' == s[1] || 'X' == s[1])) s += 2; for (*res = 0; '\0' != *s; s++) { n = 0; if ( *s &gt;= 'a' &amp;&amp; *s &lt;= 'f') { n = *s - 'a' + 10; } else if (*s &gt;= 'A' &amp;&amp; *s &lt;= 'F') { n = *s - 'A' + 10; } else if (*s &gt;= '0' &amp;&amp; *s &lt;= '9') { n = *s - '0'; } else { errno = EINVAL; return -1; } if (*res &gt; (ULONG_MAX/16)) { errno = ERANGE; return -1; } *res *= 16; *res += (unsigned long) n; } return 0; } </code></pre> <p><strong>Edit 5:</strong></p> <pre><code>#include &lt;stdlib.h&gt; #include &lt;limits.h&gt; #include &lt;errno.h&gt; int htoi(const char *s, unsigned long *res); int main(int argc, char *argv[]) { unsigned long res; if (argc &lt;= 1) { printf("No input!\n"); return EXIT_FAILURE; } if (0 &gt; htoi(argv[1],&amp;res)) return EXIT_FAILURE; else printf("Value = %llu, strtol says %lu\n", res, strtol(argv[1],NULL,16)); return EXIT_SUCCESS; } int htoi(const char *s, unsigned long *res) { if ('0' == s[0] &amp;&amp; ('x' == s[1] || 'X' == s[1])) s += 2; int c; unsigned long rc; for (rc = 0; '\0' != (c = *s); s++) { if ( c &gt;= 'a' &amp;&amp; c &lt;= 'f') { c = c - 'a' + 10; } else if (c &gt;= 'A' &amp;&amp; c &lt;= 'F') { c = c - 'A' + 10; } else if (c &gt;= '0' &amp;&amp; c &lt;= '9') { c = c - '0'; } else { errno = EINVAL; return -1; } if (rc &gt; (ULONG_MAX/16)) { errno = ERANGE; return -1; } rc *= 16; rc += (unsigned long) c; } *res = rc; return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T20:13:45.760", "Id": "74105", "Score": "1", "body": "Welcome to Code Review. Seems like you've understood exactly what we are about. I assume \"htoi\" = \"Hex to int conversion\"?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T20:15:40.997", "Id": "74106", "Score": "1", "body": "Yes, I apologize, this function is supposed to convert a string of hex characters into an integer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T20:19:59.773", "Id": "74107", "Score": "3", "body": "Tagged with \"reinventing-the-wheel\", since the function [`strtol`](http://www.cplusplus.com/reference/cstdlib/strtol/) can accomplish this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T01:15:48.393", "Id": "74166", "Score": "2", "body": "There shouldn't be a `-` in front of the macros. Also be sure to define the `enum` somewhere here, otherwise the above code won't compile. You should also use `EXIT_SUCCESS` instead, which is part of `<stdlib.h>`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T02:17:12.960", "Id": "74171", "Score": "0", "body": "I am used to seeing the positive errno, in the Linux kernel, prefixed with \"-\". Also, I was being lazy and wanted to use the defualt enum values, so I thought I could just prefix the \"-\". If I had many error codes, then would it be easier to read #defines? I have been meaning to look deeper into these matters, but haven't done so yet." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T02:20:52.870", "Id": "74173", "Score": "0", "body": "After switching to EXIT_SUCCESS I can \"echo $?\" and see the correct value returned. Thanks for all your help." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T02:41:40.567", "Id": "74174", "Score": "1", "body": "An `enum` would be more concise and better grouped than multiple `define`s." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T02:46:03.043", "Id": "74175", "Score": "2", "body": "@Steve Could you point out in the Linux kernel where you find that?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T03:50:48.637", "Id": "74191", "Score": "3", "body": "I've retained both revisions so that answers aren't invalidated. In general cases, no more than one improved code block is best as it could result in an extended review in the same post. If you feel that the most updated code could still be improved, please post a new follow-up post with reference to this one." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T04:08:27.567", "Id": "74198", "Score": "0", "body": "@syb0rg Yeah, I just pulled up a random file including errno.h; the path is arch/alpha/kernel/signal.c." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T04:12:03.770", "Id": "74201", "Score": "0", "body": "@Jamal and ChrisW, thanks for all the feedback. I think I am done with this one." } ]
[ { "body": "<p>Your indentation is messy (non-standard and not uniform).</p>\n\n<p>If the 2nd character is 'x' or'X' you don't also assert that the 1st character is '0'.</p>\n\n<p>You don't signal an error if the input string has zero length.</p>\n\n<p>I doubt you need <code>\\</code> at the end of the lines of code which initialize nibbles.</p>\n\n<p>The nibbles array is a waste of time and space, because <code>nibbles[c]</code> has the same value as <code>c</code> (so you might as well write <code>*result = *result &lt;&lt; 4 | c;</code>).</p>\n\n<p>The input parameter should be const (<code>const char*</code>).</p>\n\n<p>printf writes to stdout. If you want to log the cause of an error you should probably write to stderr instead.</p>\n\n<p>Aside from that, congratulations: it works!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T23:22:07.280", "Id": "74163", "Score": "0", "body": "@Steve I added a line about printf and stderr." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T21:35:14.030", "Id": "42984", "ParentId": "42976", "Score": "8" } }, { "body": "<p>Your 2nd version is incorrect (doesn't work): because it doesn't initialize <code>msnibble</code> and <code>digits</code> if <code>('0' != str[0])</code>.</p>\n\n<p>For this kind of reason it's dangerous to declare local variables before you assign a value to them.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T23:18:04.357", "Id": "42992", "ParentId": "42976", "Score": "2" } }, { "body": "<p>I think you should be returning different error values for different errors. You're returning <code>-1</code> for an invalid pointer, too many hex digits, no hex digits, and a non-hex character detected.</p>\n\n<p>Instead, choose separate error values for each of these (and any additional error types) and return the appropriate one. These can all be negative values, and you could still use <code>1</code>.</p>\n\n<p>Once you've chosen some error values, you could have an <code>enum</code> so that you can return a \"more specific\" type rather than just a number.</p>\n\n<p>Here's just a rough example, but you may end up with something different:</p>\n\n<pre><code>typedef enum { INVALID_PTR = -1, EXCESSIVE_HEX = -2, /* ... */ } Error;\n</code></pre>\n\n<p>To demonstrate with one of the error conditions:</p>\n\n<pre><code>if (NULL == result) {\n printf(\"Invalid pointer\\n\");\n return INVALID_PTR;\n}\n</code></pre>\n\n<p>However, if you have just one or two error types, you may not need this. You could just return the appropriate hard-coded error value.</p>\n\n<p>In either case, to make sure the reader is clear on your error-handling, you should then provide some documentation (such as comments) mentioning which error value corresponds with which error type. Those printed error statements are good for user feedback, but won't be enough if you need to deal with testing and maintainability on the code itself.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T23:20:50.027", "Id": "42993", "ParentId": "42976", "Score": "7" } }, { "body": "<p>Also, using long long is unnecessary since the bit wise operators only operate on integral types; I replaced them with longs. In addition, I changed</p>\n\n<pre><code>if (digits &gt; 16) \n</code></pre>\n\n<p>with </p>\n\n<pre><code>if (digits &gt; sizeof(long)*2) \n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T06:17:41.950", "Id": "43025", "ParentId": "42976", "Score": "1" } }, { "body": "<p><em>Reviewing your <strong>Edit 2</strong>…</em></p>\n\n<h3>Precedence bug</h3>\n\n<p>This does not do what you want, because <a href=\"http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Operator_precedence\"><code>&amp;&amp;</code> has higher precedence than <code>||</code></a>:</p>\n\n<pre><code>if ('0' == str[0] &amp;&amp; 'x' == str[1] || 'X' == str[1])\n</code></pre>\n\n<p>Very few people know all 17 levels of precedence of C operators by heart. I don't, either. Just make it a habit to use parentheses generously.</p>\n\n<h3>Error handling</h3>\n\n<p>A function that performs computation shouldn't also print output, since that would be an unexpected side effect that hurts code reusability. If you <em>must</em> print something, print to <code>stderr</code> to avoid contaminating <code>stdout</code>.</p>\n\n<p>You defined an <code>enum status</code>, but your <code>htoi()</code> function just returns an <code>int</code>. Either return an <code>enum status</code>, or just <code>#define</code> your status codes without bothering with the enum. If you do use an enum, make sure it is complete — you omitted <code>SUCCESS</code> (which I would prefer over <code>EXIT_SUCCESS</code>, since you aren't <code>exit()</code>ing the program). Also, you never use <code>NOINPUT</code>.</p>\n\n<p>In <code>htoi()</code>, you check for a null <code>result</code>. To be consistent, why don't you also check for a null <code>str</code>? (In C, it's customary to assume that the caller isn't stupid enough to pass you a null pointer, and dispense with such checks.)</p>\n\n<p>If I were writing <code>htoi()</code>, I would just keep things simple and have just return a success/failure indication without being more specific. In practice, checking for individual error codes is probably more trouble than it's worth. (That means I disagree with @Jamal's advice.)</p>\n\n<h3>Braces</h3>\n\n<p>Omitting braces with your if-elses is a filthy habit. Saving those few characters of source code just isn't worth the <a href=\"https://www.imperialviolet.org/2014/02/22/applebug.html\">danger</a>!</p>\n\n<p>If you really feel compelled to omit the braces, then also put the statement on the same line:</p>\n\n<pre><code>if (c &gt;= 'a' &amp;&amp; c &lt;= 'f') c = c - 'a' + 10;\nelse if (c &gt;= 'A' &amp;&amp; c &lt;= 'F') c = c - 'A' + 10;\nelse if (c &gt;= '0' &amp;&amp; c &lt;= '9') c -= '0';\nelse /* Non hex character */ return NONHEX;\n</code></pre>\n\n<h3>Iteration</h3>\n\n<p>You could simplify your code a lot by just incrementing the <code>str</code> pointer.</p>\n\n<pre><code>enum status htoi(const char *str, unsigned long long *result)\n{\n int c;\n int digits;\n\n if (NULL == result) {\n /* Invalid pointer */\n return INVPTR;\n }\n *result = 0;\n if (NULL == str) {\n result INVPTR;\n }\n\n if ('0' == str[0] &amp;&amp; ('x' == str[1] || 'X' == str[1])) {\n str += 2;\n }\n digits = strlen(str);\n if (digits &gt; 16) {\n /* Too many hex digits */\n return TOOBIG;\n } else if (0 == digits) {\n /* Nothing to do */\n return NOHEX;\n }\n\n for (; '\\0' != (c = *str); str++) {\n if (c &gt;= 'a' &amp;&amp; c &lt;= 'f') {\n c = c - 'a' + 10;\n } else if (c &gt;= 'A' &amp;&amp; c &lt;= 'F') {\n c = c - 'A' + 10;\n } else if (c &gt;= '0' &amp;&amp; c &lt;= '9') {\n c -= '0';\n } else {\n /* Non hex character detected */\n return NONHEX;\n }\n *result = *result &lt;&lt; 4 | c;\n }\n return SUCCESS;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T07:08:04.443", "Id": "43029", "ParentId": "42976", "Score": "7" } }, { "body": "<p>Your code looks nice and is easily readable. However I have a few problems with it.</p>\n\n<p>I disagree with your error return codes. This might be possible in one\nfunction, but if all functions were to do this it would become unmanageable.\nIt is also not the C way, which is more along the lines of <code>strtoul</code>\n(which you are approximating with <code>htoi</code>), which returns an error (NULL in\nits case) and sets <code>errno</code> to ERANGE or EINVAL.</p>\n\n<p>I would also not check for NULL pointers, as again it is not normal. And lastly, I dislike your method of range checking. Your function would balk for\nexample at 0x00000000000000001 (16 leading zeroes) but it is quite\nvalid. A better way is to check against ULONG_MAX before shifting left.</p>\n\n<p>Here is my version, for what it is worth:</p>\n\n<pre><code>int htoi(const char *s, unsigned long *result)\n{\n if ((*s == '0') &amp;&amp; (s[1] == 'x' || s[1] == 'X')) {\n s += 2;\n }\n for (*result = 0; *s; ++s) {\n int n = 0;\n if (*s &gt;= 'a' &amp;&amp; *s &lt;= 'f') {\n n = *s - 'a' + 10;\n } else if (*s &gt;= 'A' &amp;&amp; *s &lt;= 'F') {\n n = *s - 'A' + 10;\n } else if (*s &gt;= '0' &amp;&amp; *s &lt;= '9') {\n n = *s - '0';\n } else {\n errno = EINVAL;\n return -1;\n }\n if (*result &gt; (ULONG_MAX/16)) {\n errno = ERANGE;\n return -1;\n }\n *result *= 16;\n *result += (unsigned long) n;\n }\n return 0;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T20:32:23.420", "Id": "74351", "Score": "0", "body": "Great suggestions; I implemented them. Although, I wonder if it would be better to assign a variable c with the char value from the string, in case I forget to dereference the pointer. This is an exercise from K&R. Posting it here made it an even better exercise. Thanks!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T19:25:33.477", "Id": "43092", "ParentId": "42976", "Score": "4" } }, { "body": "<p>Reviewing your 4th edit:</p>\n\n<ul>\n<li>It's much better (more compact, less to go wrong)</li>\n<li><code>digits</code> is unused</li>\n<li>You could delay declaring 'n' until later, when you first assign a value to it</li>\n<li>The code would be slightly faster if you didn't reference pointers (i.e. <code>*res</code> and <code>*s</code>) so often and used a local variable (i.e. <code>rc</code> and <code>n</code>) instead</li>\n<li>If you return an error (e.g. from meeting an invalid digit) it might be better to do so without having altered (left a partially calculated value in) the caller's <code>*res</code></li>\n<li>This version doesn't return an error if you pass in a zero-length string</li>\n</ul>\n\n<p>For example:</p>\n\n<pre><code>int htoi(const char *s, unsigned long *res)\n{\n if ('0' == s[0] &amp;&amp; ('x' == s[1] || 'X' == s[1])) {\n s += 2;\n }\n if ('\\0' == *s) {\n errno = NOHEX;\n return -1;\n }\n unsigned long rc;\n int n;\n for (rc = 0; '\\0' != (n = *s); s++) {\n if ( n &gt;= 'a' &amp;&amp; n &lt;= 'f') {\n n = n - 'a' + 10;\n } else if (n &gt;= 'A' &amp;&amp; n &lt;= 'F') {\n n = n - 'A' + 10;\n } else if (n &gt;= '0' &amp;&amp; n &lt;= '9') {\n n = n - '0';\n } else {\n errno = EINVAL;\n return -1;\n }\n if (rc &gt; (ULONG_MAX/16)) {\n errno = ERANGE;\n return -1;\n }\n\n rc *= 16;\n rc += (unsigned long) n;\n }\n\n *res = rc;\n return 0;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T23:24:32.610", "Id": "43102", "ParentId": "42976", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "11", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T20:11:12.567", "Id": "42976", "Score": "15", "Tags": [ "c", "converting", "reinventing-the-wheel" ], "Title": "Hexadecimal to integer conversion function" }
42976
<p>I have been working on a project and I'm actually refactoring some code. I have encountered myself with lots of foreach and if statements, which could be easily replace with LINQ.</p> <p>But I have this code snippet, that I wonder how I could make it more functional style.</p> <pre><code>foreach (var notification in notifications) { if (_emailService.SendEmail(notification.Message.Subject, notification.Message.Body, notification.Message.MailTo)) { successNotificationIDs.AddRange(notification.ID); } else { errorCount++; } } </code></pre> <p>The <code>SendEmail</code> method of the <code>EmailService</code> returns a bool. If its execution has been successfully, it will add an <code>IEnumerable</code> of Int to a declared collection (<code>successNotificationsIDs</code>). If not, I will increase the <code>errorCount</code> variable.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T20:44:12.267", "Id": "74117", "Score": "0", "body": "What type `notifications` have? What type notification ID have?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T20:45:11.050", "Id": "74119", "Score": "0", "body": "They are a custom type." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T20:47:34.230", "Id": "74121", "Score": "0", "body": "Are you sure? Maybe notifications is a `List<T>`? Maybe ID is something like integer?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T20:50:35.043", "Id": "74122", "Score": "0", "body": "Sorry, I misread. Notifications is a IEnumerable<T>." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T13:16:41.207", "Id": "74285", "Score": "0", "body": "refactoring code is only useful when you are trying to speed something up, or you gotta deal with duplicate code because some devs copy and paster crap all over the place. What you are doing, is poking poop with a barge pole. There is nothing wrong with the code, changing it LINQ wont speed it up. If you really wanted to make better code and be smarter (instead of just look smarter) you would create an interface for emails and create a better object oriented application. Not just stirring code up for no reason. -1" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T13:17:42.327", "Id": "74286", "Score": "3", "body": "Since `SendEmail` is executed for a side-effect, it's inherently non functional and you should not use call it from LINQ." } ]
[ { "body": "<p>LINQ isn't a silver bullet. It stands for Language-INtegrated-<strong>Query</strong>, which allows <strong>querying</strong> objects.</p>\n\n<p>Querying objects isn't something that's supposed to have side-effects. However this is precisely what you loop's body is doing.</p>\n\n<p>Therefore, refactoring it to use LINQ, if at all possible, would make it much less readable than the <code>foreach</code> loop you have here.</p>\n\n<p>You could always create a <a href=\"http://msdn.microsoft.com/en-us/library/system.threading.tasks.task%28v=vs.110%29.aspx\"><code>Task</code></a> object for each <code>notification</code>, and then run that.</p>\n\n<hr>\n\n<p>Now the loop body you have, is using <code>AddRange</code> to add what appears to be a single value. Unless <code>notification.ID</code> is an <code>IEnumerable&lt;whatever&gt;</code>, you should be using the <code>Add</code> method to add a single value to your <code>successNotificationIDs</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T20:53:44.197", "Id": "74123", "Score": "0", "body": "ID is an IEnumerable<int> actually. I don't have access to the class, but it has already been informed to change its name." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T20:54:16.527", "Id": "74124", "Score": "4", "body": "I sure hope so - it's a very misleading name to have!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T23:12:49.820", "Id": "74158", "Score": "0", "body": "@sweeden I'll update this answer with an example when I have a minute." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T14:33:27.373", "Id": "74297", "Score": "0", "body": "@Mat'sMug: It's not really that wrong to use LINQ in this instance. There are lots of useful times where a 'query' doesn't directly get or set a property. Even in the setter of some properties, sometimes there are event bindings that could be considered side effects. I think it is a personal preference of coding style, which is beneficial when a query can be easily stacked with other LINQ queries to reduce directly writing multiple `foreach` loops." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T14:48:02.527", "Id": "74299", "Score": "1", "body": "Why do you mention `Task`? How will that help here?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T15:36:28.997", "Id": "74303", "Score": "0", "body": "@svick a `Task` would decouple the execution of `SendMail()` from the loop's body, allowing for asynchronous execution. They would be created using a LINQ `Select()` method call, which would merely *project* the `notifications` into an `IEnumerable<Task>`, which also decouples the evaluation of whether a task succeeded or failed. I think the loop has too many responsibilities/side-effects to be turned into anything remotely *functional* (as mentioned in [this comment](http://codereview.stackexchange.com/questions/42977/refactor-foreach-statement-to-linq/42979#comment74286_42977))." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T20:46:27.317", "Id": "42979", "ParentId": "42977", "Score": "12" } }, { "body": "<p>From Stackoverflow directly, this was posted as an answer.</p>\n\n<pre><code>var lookup = notifications.ToLookup(notification =&gt;\n _emailService.SendEmail(notification.Message.Subject, \n notification.Message.Body,\n notification.Message.MailTo));\n\nvar successfulIDs = lookup[true].SelectMany(notification =&gt; notification.ID);\nvar errorCount = lookup[false].Count();\n</code></pre>\n\n<p>Interesting as I didn't know the ToLookup method :).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T20:58:52.940", "Id": "74125", "Score": "1", "body": "This is a rather interesting approach, however I would seriously consider hitting an SMTP server as an async operation, especially with this kind of construct." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T23:11:26.373", "Id": "74157", "Score": "0", "body": "I will look into your answer. Thanks for the help :)!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T20:55:47.610", "Id": "42980", "ParentId": "42977", "Score": "4" } }, { "body": "<p>Why not just use <code>Where</code> and <code>Select</code> if you're just trying to get a list of successful IDs?</p>\n\n<p>ie.</p>\n\n<pre><code>var successfulIDs = notifications.Where(n =&gt; _emailService.SendEmail(n.Message.Subject, \n n.Message.Body,\n n.Message.MailTo)).\n Select(n =&gt; n.ID);\n</code></pre>\n\n<p>If the type of <code>notifications</code> isn't right then you should be able to use <code>Cast</code> to do that.</p>\n\n<p>To check how many failed, if you're able to use <code>Count</code>:</p>\n\n<pre><code>long errorCount = notifications.Count() - successfulIDs.Count();\n</code></pre>\n\n<p>I don't know what your types are, but you may be able to use <code>Length</code> instead of <code>Count</code> if not. Otherwise <code>Cast</code> and then <code>Count</code>.</p>\n\n<p>Additionally, here's the equivalent <code>foreach</code> in case you decide to stay with that.</p>\n\n<pre><code>foreach(var notification in notifications)\n if(_emailService.SendEmail(notification.Message.Subject,\n notification.Message.Body,\n notification.Message.MailTo))\n successNotificationIDs.AddRange(notification.ID);\n</code></pre>\n\n<p>...for which you should still be able to use the <code>errorCount</code> described above. Note that you can combine these into a single line (potentially sacrificing readability in this case).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T10:50:00.280", "Id": "74262", "Score": "0", "body": "What about the `errorCount++` line?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T12:54:51.310", "Id": "74279", "Score": "0", "body": "Yes. I have tried to go with that approach, but I need to inform the amount of notifications that failed to mailed. That's why I need the errorCount variable." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T13:11:35.053", "Id": "74283", "Score": "0", "body": "@Sweeden: Why do you need a separate variable to increase that count? You can likely just compare the `Count` of both. I've edited my answer." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T06:08:47.367", "Id": "43022", "ParentId": "42977", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T20:37:40.317", "Id": "42977", "Score": "10", "Tags": [ "c#", "linq", "email" ], "Title": "Refactor foreach statement to LINQ" }
42977
<p>Here is the code for the <code>CString</code> class that I created.</p> <pre><code>public class CString { public String reverse(String s) { char[] array = new char[s.length()]; array = s.toCharArray(); for(int i=0; i&lt;array.length/2; i++) { char tmp = array[i]; array[i] = array[array.length-1-i]; array[array.length-1-i] = tmp; } return charArrayToString(array); } public String charArrayToString(char[] array) { StringBuffer sb = new StringBuffer(); sb.append(array); return sb.toString(); } } </code></pre> <p>Is there any bug in the code? Are there more efficient ways to reverse a string?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T21:24:45.063", "Id": "74128", "Score": "6", "body": "Have you not checked for bugs yourself? We are not a debugging service. We review working code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T21:25:35.690", "Id": "74129", "Score": "1", "body": "Yes, it passed some simple tests." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T21:26:46.993", "Id": "74130", "Score": "0", "body": "Okay, just making sure. The second question is good, and we can help with that." } ]
[ { "body": "<p>The code appears to be functionally correct, although you could simply choose to use a <code>StringBuffer.reverse()</code>. There is some discussion of this <a href=\"https://stackoverflow.com/questions/2439141/what-is-the-most-efficient-algorithm-for-reversing-a-string-in-java\">here</a>.</p>\n\n<p>If you do need to roll your own reversing method, you can avoid using <code>StringBuffer</code>/<code>StringBuilder</code> at all and simply do <code>new String(array)</code> instead.</p>\n\n<p>As a general point, if you're not dealing with multithreaded code <a href=\"https://stackoverflow.com/questions/355089/stringbuilder-and-stringbuffer-in-java\">you should probably use <code>StringBuilder</code> in preference to <code>StringBuffer</code></a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T21:34:31.080", "Id": "42983", "ParentId": "42981", "Score": "10" } }, { "body": "<p>Reversing a string, accurately and efficiently. </p>\n\n<p>You are doing it accurately, yes. But, not very efficiently (although there are worse ways to do things).</p>\n\n<p><strong>NOTE::</strong> Palacsint is right that you are not handling null input and surrogate-pairs in the input data. Your solution is not completely accurate. Consider this answer a discussion of the efficiency only.... though I have also updated this answer to include a solution which deals with surrogate pairs efficiently</p>\n\n<p>To understand the efficiency side of things, you have to understand Java String internals.</p>\n\n<ul>\n<li>Strings are immutable, cannot be changed.</li>\n<li>Java is relatively slow at allocating/cleaning memory, try to avoid it.</li>\n<li>Java can 'inline' method calls and make methods really fast.</li>\n</ul>\n\n<p>So, the best way to make Java efficient is to create/use as little memory as possible, and still end up with a new String (instead of changing an existing string).</p>\n\n<p>Your code has 1 string already, you are creating another string. You cannot avoid that.</p>\n\n<p>What you can avoid though is what happens in between.</p>\n\n<h2>Your 'In Between'</h2>\n\n<p>What you are doing in between is a bit messy, and wasteful:</p>\n\n<blockquote>\n<pre><code> char[] array = new char[s.length()];\n array = s.toCharArray();\n</code></pre>\n</blockquote>\n\n<p>You create a new array, then you throw it away, and replace it with the <code>s.toCharArray()</code>... why?</p>\n\n<p>Could be just:</p>\n\n<pre><code> char[] array = s.toCharArray();\n</code></pre>\n\n<p>Also, you have a loop that swaps the chars... this is implemented like:</p>\n\n<blockquote>\n<pre><code>for(int i=0; i&lt;array.length/2; i++) {\n</code></pre>\n</blockquote>\n\n<p>This could be faster if you did it backwards ( <em>could be</em> - depending on which Java you use).</p>\n\n<pre><code>for (int i = array.length / 2; i &gt;= 0; i--) {\n</code></pre>\n\n<p>This way it only has to do the <code>array.length / 2</code> one time (though, as I say, some Java implementations will perhaps compile it to work out for you).</p>\n\n<p>Finally, the <code>charArrayToString()</code> is serious overkill....</p>\n\n<p>Converting to a StringBuilder then to a String is a waste of time/resources...</p>\n\n<blockquote>\n<pre><code>return charArrayToString(array);\n</code></pre>\n</blockquote>\n\n<p>can be</p>\n\n<pre><code>return new String(array);\n</code></pre>\n\n<p>EDIT: Also, as has been mentioned by <a href=\"https://codereview.stackexchange.com/a/42983/31503\">Richard Miskin</a>... and I <em>assumed</em> you were already using a <code>StringBuilder</code> .... StringBuilder is much more efficient in a single-thread situation than <code>StringBuffer</code>. Unless you have good reason, you always should use <code>StringBuilder</code>.</p>\n\n<h2>Efficient in-between ....</h2>\n\n<pre><code>public String reverse(String s) {\n char[] array = s.toCharArray();\n char tmp;\n for(int i = (array.length - 1) / 2; i &gt;= 0; i--) {\n tmp = array[i];\n array[i] = array[array.length-1-i];\n array[array.length-1-i] = tmp;\n }\n return new String(array);\n}\n</code></pre>\n\n<h2>Edit: a different way:</h2>\n\n<p>Here are some performance numbers...</p>\n\n<blockquote>\n<pre><code>String Reverse =&gt; 4473870 (hot 19.74881ms)\nString Reverse Surrogate Aware =&gt; 4473870 (hot 22.73488ms)\nString Reverse B =&gt; 4473870 (hot 25.16192ms)\nString Reverse StringBuilder =&gt; 4473870 (hot 31.60709ms)\nString Reverse StringBuilder NoNullCheck =&gt; 4473870 (hot 31.72952ms)\nString Reverse Orig =&gt; 4473870 (hot 36.83827ms)\n</code></pre>\n</blockquote>\n\n<p>For each of those 'hot' runs, I am reversing the order of 479829 words (linux.words) (and there are 4473870 characters in the data excluding newlines).</p>\n\n<ul>\n<li><p>the code I suggested above as the 'efficient in-between' does it in 20 milliseconds</p></li>\n<li><p>based on the discussion about <code>null</code> and Surrogate Pairs, the following code does this 'right', and runs in 23 milliseconds:</p>\n\n<pre><code>public String reverse(final String s) {\n if (s == null) {\n return null;\n }\n final char[] array = s.toCharArray();\n char tmp;\n for(int i=array.length/2; i &gt;= 0; i--) {\n tmp = array[i];\n array[i] = array[array.length-1-i];\n array[array.length-1-i] = tmp;\n }\n //surrogate pairs will have been swapped.\n //identify, and un-swap them.\n for (int i = 1; i &lt; array.length; i++) {\n if (Character.isHighSurrogate(array[i]) &amp;&amp; Character.isLowSurrogate(array[i - 1])) {\n tmp = array[i];\n array[i] = array[i - 1];\n array[i - 1] = tmp;\n }\n }\n return new String(array);\n}\n</code></pre></li>\n<li><p>The following code does it in 25 milliseconds </p>\n\n<pre><code>public String reverse(String s) {\n char[] array = new char[s.length()];\n for(int i=array.length - 1, j = 0; i &gt;= 0; i--, j++) {\n array[i] = s.charAt(j);\n }\n return new String(array);\n}\n</code></pre></li>\n<li><p>@palacsint's recommendation does it in 31 milliseconds: </p>\n\n<pre><code>public static String reverse(final String str) {\n if (str == null) {\n return null;\n }\n return new StringBuilder(str).reverse().toString();\n} \n</code></pre></li>\n<li><p>@palacsint's recommendation (without the null-check) does it in 31 milliseconds: </p>\n\n<pre><code>public static String reverse(final String str) {\n return new StringBuilder(str).reverse().toString();\n} \n</code></pre></li>\n<li><p>Your code does it in 37milliseconds.</p></li>\n</ul>\n\n<p>If you look at the code, my code creates three objects (char[] and new String() (which creates char[] as well))</p>\n\n<p>The <code>s.charAt()</code> code also creates three objects, but has a lot of calls to <code>String.charAt()</code>.</p>\n\n<p>The @palacsint recommendation creates 4 objects (StringBuffer, StringBuffer's internal char[], String, and String's internal char[]);</p>\n\n<p>That is true with and without the null-check.</p>\n\n<p>Your code creates 5 objects (6 if you count the first array which is likely to be compiled out...) : (char[] array, new StringBuffer, StringBuffer's char[], String, and String's char[])</p>\n\n<p>My guess is that there is a close correlation between our times simply because it takes 5ms to create 480,000 objects on the heap, plus some overhead of actual work.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T22:24:02.177", "Id": "74149", "Score": "4", "body": "*\"Java is relatively slow at allocating/cleaning memory, try to avoid it.*\" Fast memory allocation (i.e. memory retrieving by the VM) is not one of the key points of a GC-based system and managed-by-vm memory systems in general? As far I know, \"allocating\" memory in Java-like languages is pretty fast because there is no \"true\" allocation (i.e. calling a heap allocator to retrieve new chunks/pages of free memory), only is the VM retrieving you some piece of a larg amount of memory it allocated previously to avoid calling the slow \"mallocs\" continuously." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T22:25:49.760", "Id": "74150", "Score": "4", "body": "Also, GCs are not slow at collecting, they are pretty fast nowadays. The only problem is the indeterministic way they works (i.e. \"I don't know when the GC would stop my program to perform the collecting\"), which could be a problem in realtime systems (like videogames)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T23:20:51.140", "Id": "74160", "Score": "2", "body": "@Manu343726 - both your points are valid, but out of context for this discussion. What I am saying is 'using the heap (whether pre-malloc'd or not) is slower than not using the heap.'. Not having to GC some memory is faster than the alternative." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T23:21:45.143", "Id": "74162", "Score": "1", "body": "Edited the answer to include some comparative performance results." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T09:51:34.897", "Id": "74249", "Score": "0", "body": "@rolfl: +1, and hope you get a lot more +1's, too. Though Java isn't my language, I accidentally found this question (flag queue). I had to up-vote, if only for the effort that has clearly gone into this. Nice to see a CR answer that actually bothers with both the code and the reasons _why_" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T16:28:53.450", "Id": "74317", "Score": "0", "body": "@rolfl: That isn't necessarily even true, speaking just in terms of the memory. In a generational GC you can often create and destroy the ephemeral generation with a single pointer move each, if none of the ephemeral objects need moving to a different generation, and that cost only scales with the number to be moved, not the number not to be moved. Of course, the spirit of what you say is correct, not doing some operation is always faster than doing it, or at very least not more expensive." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-14T22:11:25.920", "Id": "412960", "Score": "1", "body": "Maybe i'm missing something but it doesn't seem like your efficient in-between method is actually reversing the string fully. Pass in any string with an even number of characters. Let's use \"Java\" as an example. When passed into your method you would expect \"avaJ\" as the output however you get \"aavJ\"." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-15T05:46:19.803", "Id": "412983", "Score": "1", "body": "@IZI_Shadow_IZI - you're right. The reason is because it has an off-by-one error. Good spotting. The broken code is indeed wrong: https://ideone.com/H81ICt ... in the same ideone, I put the revised code (changed `array.length/2` to `(array.length - 1) / 2`) in the `fixReverse` function. I am also going to edit my answer here." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2014-02-27T21:37:52.850", "Id": "42985", "ParentId": "42981", "Score": "36" } }, { "body": "<p>Learn from the existing implementations, they usually have solutions to corner cases and common pitfalls. For example, Apache Commons Lang <a href=\"http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html\" rel=\"nofollow noreferrer\"><code>StringUtils</code></a> also has a <a href=\"http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#reverse%28java.lang.String%29\" rel=\"nofollow noreferrer\"><code>reverse</code></a> function. Its <a href=\"http://svn.apache.org/viewvc/commons/proper/lang/trunk/src/main/java/org/apache/commons/lang3/StringUtils.java?view=markup#l6270\" rel=\"nofollow noreferrer\">implementation</a> is quite simple:</p>\n\n<pre><code>public static String reverse(final String str) {\n if (str == null) {\n return null;\n }\n return new StringBuilder(str).reverse().toString();\n} \n</code></pre>\n\n<p>It uses <a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html#reverse%28%29\" rel=\"nofollow noreferrer\"><code>StringBuilder.reverse</code></a> whose <a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html#reverse%28%29\" rel=\"nofollow noreferrer\">javadoc</a> mentions some special cases:</p>\n\n<blockquote>\n <p>If there are any surrogate pairs included in the sequence, \n these are treated as single characters for the reverse operation. \n Thus, the order of the high-low surrogates is never reversed.</p>\n</blockquote>\n\n<p>Here are a few tests:</p>\n\n<pre><code>@Test\npublic void testCstring() {\n assertEquals(\"\\uD800\\uDC00\", CString.reverse(\"\\uD800\\uDC00\")); // fails\n assertEquals(\"\\uD800\\uDC00\", CString.reverse(\"\\uDC00\\uD800\")); // OK\n}\n\n@Test\npublic void testStringUtils() throws Exception {\n assertEquals(\"\\uD800\\uDC00\", StringUtils.reverse(\"\\uD800\\uDC00\"));\n assertEquals(\"\\uD800\\uDC00\", StringUtils.reverse(\"\\uDC00\\uD800\"));\n}\n</code></pre>\n\n<p>I don't know too much about these surrogates but you should check it and handle them in your code. I suppose the JDK's implementation is more reliable and it's not coincidence that the handle them in the way they mention in the javadoc.</p>\n\n<p>There is a good question (with great answers) about surrogates on Stack Overflow: <a href=\"https://stackoverflow.com/q/5903008/843804\">What is a surrogate pair in Java?</a></p>\n\n<p>(See also: <em>Effective Java, 2nd edition</em>, <em>Item 47: Know and use the libraries</em>)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T20:06:04.643", "Id": "74345", "Score": "3", "body": "Handling surrugates isn't enough. You also need to handle combining characters." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2014-02-27T21:50:52.703", "Id": "42986", "ParentId": "42981", "Score": "17" } }, { "body": "<p>You can use Java 8 lambda functions to reverse a string without mutating or using any local variables. This code will illustrate the reverse function:</p>\n\n<pre><code>public static void reverse(String myString) {\n return myString\n .chars()\n .mapToObj(c -&gt; String.valueOf((char) c))\n .reduce(\"\", (sb, str) -&gt; str + sb); \n}\n</code></pre>\n\n<p>This code gets you the integer stream from the <code>String</code> object:</p>\n\n<pre><code>myString.chars()\n</code></pre>\n\n<p>Once you have the integer stream you can transform the integers to characters using the map function:</p>\n\n<pre><code>mapToObj(c -&gt; String.valueOf((char) c))\n</code></pre>\n\n<p>Then finally you can reduce your characters the way you want. Here I have prepended the characters to the final output string:</p>\n\n<pre><code>reduce(\"\", (sb, str) -&gt; str + sb);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-04-29T07:26:34.773", "Id": "371155", "Score": "0", "body": "This code is horribly slow for large strings. Did you ever try to reverse a Wikipedia article using that code? It can take minutes, but should only take microseconds." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-04-30T03:03:08.337", "Id": "371306", "Score": "0", "body": "Definitely this code can be optimized, I have given the basic approach on writing a cleaner code." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-04-29T05:57:03.843", "Id": "193184", "ParentId": "42981", "Score": "0" } } ]
{ "AcceptedAnswerId": "42985", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T21:20:59.407", "Id": "42981", "Score": "26", "Tags": [ "java", "strings", "array" ], "Title": "Reverse a String in Java" }
42981
<p>I have \$k\$ sorted <code>List</code>s, each of size \$n\$. Currently I have hard-coded 5 sorted <code>List</code>s each of size 3, but in general that is configurable. </p> <p>I would like to search for single element in each of the \$k\$ <code>List</code>s (or its predecessor, if it doesn't exist).</p> <p>Obviously I can binary search each List individually, resulting in a \$O(k*log(n))\$ runtime. But I think we can do better than that: after all, we're doing the same search \$k\$ times.</p> <p>Could this be improved?</p> <pre><code>private static TreeSet&lt;Integer&gt; tree = new TreeSet&lt;Integer&gt;(); public SearchItem(final List&lt;List&lt;Integer&gt;&gt; inputs) { tree = new TreeSet&lt;Integer&gt;(); for (List&lt;Integer&gt; input : inputs) { tree.addAll(input); } } public Integer getItem(final Integer x) { if(tree.contains(x)) { return x; } else { return tree.higher(x); } } public static void main(String[] args) { List&lt;List&lt;Integer&gt;&gt; lists = new ArrayList&lt;List&lt;Integer&gt;&gt;(); List&lt;Integer&gt; list1 = new ArrayList&lt;Integer&gt;(Arrays.asList(3, 4, 6)); List&lt;Integer&gt; list2 = new ArrayList&lt;Integer&gt;(Arrays.asList(1, 2, 3)); List&lt;Integer&gt; list3 = new ArrayList&lt;Integer&gt;(Arrays.asList(2, 3, 6)); List&lt;Integer&gt; list4 = new ArrayList&lt;Integer&gt;(Arrays.asList(1, 2, 3)); List&lt;Integer&gt; list5 = new ArrayList&lt;Integer&gt;(Arrays.asList(4, 8, 13)); lists.add(list1); lists.add(list2); lists.add(list3); lists.add(list4); lists.add(list5); SearchItem search = new SearchItem(lists); System.out.println(tree); Integer dataOuput = search.getItem(5); System.out.println(dataOuput); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T02:00:13.320", "Id": "74167", "Score": "0", "body": "Question: In your text you say: *I would like to search for single element in each of the k Lists (or its predecessor, if it doesn't exist).* but in your code you get the `*successor* not the *predecessor*. Which one is right?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T03:05:19.577", "Id": "74177", "Score": "0", "body": "@rolfl: I just updated the question.. I miss couple of important points.. I have rewrote most of the things.. Now take a look.. It will make sense now.. I guess now you will be angry as in the question lot of things might have change as corresponding to what you have suggested :(" } ]
[ { "body": "<p>I think you have some misguided assumptions here.</p>\n\n<p>For a start, what you have now is not \\$O(k \\log(n))\\$, it first scans and sorts all the data in to the tree, which is a \\$O(N \\log(N))\\$ operation, where \\$N\\$ is the cumulative data size (sum of input-array sizes). Then, the check on it, is a \\$O(\\log(N))\\$ check, so, your algorithm is in the order of \\$O(N\\log(N))\\$.</p>\n\n<p>The complexity you are worried about \\$O(k\\log(n))\\$ is really quite trivial. \\$k\\$ is a small number (5), and <code>log(n)</code> is always small... in many ways, after n = 128 it is effectively a constant....</p>\n\n<p>So, I would do the following:</p>\n\n<ol>\n<li>binary search each List</li>\n<li>keep the 'min' value</li>\n</ol>\n\n<p>with the code:</p>\n\n<pre><code>Integer result = null;\nfor (List&lt;Integer&gt; data : lists) {\n int pos = Collections.binarySearch(data, input);\n if (pos &gt;= 0) {\n //exact match, return\n return data.get(pos);\n }\n pos = -pos - 1;\n if (pos &lt; data.size()) {\n Integer found = data.get(pos);\n if (result == null || result.compareTo(found) &gt; 0) {\n result = found;\n }\n }\n}\nreturn result;\n</code></pre>\n\n<p>Now, if you wanted to be fancy, and you wanted the fastest response times, you could put each binary search in to a <code>Callable&lt;Integer&gt;</code>, and run them in parallel....</p>\n\n<p>Then rank the results, and teturn it all in time complexity \\$O(\\log(n))\\$ assuming \\$k\\$ is less than your hardware CPU count.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T21:57:37.523", "Id": "42988", "ParentId": "42982", "Score": "8" } }, { "body": "<p>Two quick notes about the code in the question:</p>\n\n<ol>\n<li><p>A bug: a client could create more than one instance of the class but all of them will use the same <code>TreeSet</code> instance since it's static.</p></li>\n<li><pre><code>public Integer getItem(final Integer x) {\n if(tree.contains(x)) {\n return x;\n } else {\n return tree.higher(x);\n }\n}\n</code></pre>\n\n<p>The following is the same:</p>\n\n<pre><code>public Integer getItem(final Integer x) {\n return tree.ceiling(x);\n}\n</code></pre></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T00:16:07.590", "Id": "42998", "ParentId": "42982", "Score": "5" } } ]
{ "AcceptedAnswerId": "42988", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T21:25:23.543", "Id": "42982", "Score": "11", "Tags": [ "java", "optimization", "performance", "algorithm", "search" ], "Title": "Finding an element in multiple sorted lists efficiently" }
42982
<p>In this assignment, I'm supposed to split a string using <code>strtok</code>. (The assignment consists of the comment and the function definition; I fill in the function body.)</p> <p>It works as far as I've tested. But it seems a little ugly to me. Perhaps it's my Java background, but somehow this just doesn't feel right. Specific concerns:</p> <ul> <li>Is this easily readable to a more experienced C programmer?</li> <li>Can this be made more idiomatic somewhere?</li> <li>Is it feasible to split this into several functions? Where would you split it?</li> <li>Any corner cases where it might break? Does it leak memory?</li> </ul> <pre class="lang-c prettyprint-override"><code>/* Parses a string into tokens (command line parameters) separated by space. * Builds a dynamically allocated array of strings. Pointer to the array is * stored in variable pointed by argv. * * Parameters: * argv: pointer to the variable that will store the string array * input: the string to be parsed (the original string can be modified, if needed) * * Returns: * number of space-separated tokens in the string */ int parse_cmdline(char ***argv, char *input) { char *token; int len, num; len = 4; *argv = malloc(len * sizeof(char *)); if (*argv == NULL) { return 0; } for (num = 0;; num++, input = NULL) { token = strtok(input, " "); if (token == NULL) { break; } if (num &gt;= len) { char **temp; len *= 2; temp = realloc(*argv, len * sizeof(char *)); if (temp == NULL) { for (int i = 0; i &lt; num; i++) { free((*argv)[i]); } free(*argv); *argv = NULL; return 0; } *argv = temp; } (*argv)[num] = strdup(token); if ((*argv)[num] == NULL) { for (int i = 0; i &lt; num; i++) { free((*argv)[i]); } free(*argv); *argv = NULL; return 0; } } return num; } </code></pre>
[]
[ { "body": "<p>The key point in tokenizing strings is that</p>\n\n<blockquote>\n <p>The number of resulting token would not be known in prior</p>\n</blockquote>\n\n<p>One good approach is the one you have followed,</p>\n\n<ul>\n<li>Allocate some memory</li>\n<li>Use it</li>\n<li>Allocate more if needed</li>\n</ul>\n\n<p>I want to answer some of the questions that you have asked.</p>\n\n<blockquote>\n <p>Is it feasible to split this into several functions? Where would you\n split it?</p>\n</blockquote>\n\n<p>As you see, there is the <em>repetition</em> of error handling (freeing up the argv array). Well this can be separated into another function.</p>\n\n<blockquote>\n <p>Is this easily readable to a more experienced C programmer?</p>\n</blockquote>\n\n<p>Not sure of the level of expertise you mean, but I can <em>read it and understand</em> without any problems. I am a 2 year experienced C Professional.</p>\n\n<blockquote>\n <p>Any corner cases where it might break? Does it leak memory?</p>\n</blockquote>\n\n<p>There is no obvious memory leak I could see in the program. But you can use tools like <em>valgrind</em> to detect such leaks.</p>\n\n<p>I am just posting few code, that I would use, if I am given the same program.</p>\n\n<pre><code>int free_argv_q(struct queue *q)\n{\n int i;\n int q_len = q_length(q);\n\n for (i = 0; i &lt; q_len; i++) {\n char *arg = dequeue(q);\n free(arg);\n }\n\n return 0;\n}\n\nint parse_cmdline(char ***argv, char *input)\n{\n int i;\n int argc = 0;\n\n char *arg = NULL;\n char *token = NULL;\n\n struct queue q;\n\n token = strtok(input, \" \");\n\n do {\n /* strdup may fail due to low memory */\n arg = strdup(token);\n\n if (arg == NULL) {\n free_argv_q(&amp;q);\n return 0;\n }\n\n /* add to queue */\n enqueue(&amp;q, arg);\n token = strtok(NULL, \" \");\n } while (token);\n\n /* length of the queue is the number of splits */\n argc = q_length(&amp;q);\n\n *argv = malloc(argc * sizeof(char *));\n\n if (*argv == NULL) {\n free_argv_q(&amp;q);\n return 0;\n }\n\n /* now we have all memory allocated */\n for (i = 0; i &lt; argc; i++)\n argv[i] = dequeue(&amp;q);\n\n return argc;\n}\n</code></pre>\n\n<p>The explanation is as follows.</p>\n\n<ul>\n<li>I use a <strong>queue</strong> to split the tokens and store them. Well this would grow dynamically.</li>\n<li>After parsing whole input, the <code>argv</code> array is allocated</li>\n<li><code>argc</code> is the length of the queue</li>\n<li>Memory allocation failures are handled though</li>\n<li>The cleanup function is separated</li>\n</ul>\n\n<p><strong>Note:</strong> The implementation of queue is skipped for simplicity. Hope this program is self <em>explanatory</em>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T16:53:49.307", "Id": "43149", "ParentId": "42990", "Score": "3" } } ]
{ "AcceptedAnswerId": "43149", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T22:23:11.993", "Id": "42990", "Score": "8", "Tags": [ "c", "strings", "memory-management" ], "Title": "Tokenizing string using strtok" }
42990
<p>I am now writing a small bash script that updates an Intel NIC driver to the latest version from the official website. Is there any way to improve\simplify the script? I want to avoid a lot of "if...else" stuff. Helpful tips will be appreciated!</p> <pre><code>#! /bin/bash DRV_PKG_NAME="e1000e-3.0.4.tar.gz" DRV_PKG_URL="http://downloadmirror.intel.com/15817/eng/e1000e-3.0.4.tar.gz" # Downloading driver and extracting it to current directory echo "Downloading and extracting driver package..." if wget -q ${DRV_PKG_URL} &amp;&amp; tar zxvf ${DRV_PKG_NAME} &gt;/dev/null ; then echo "Done!" else exit 1 fi # Installing required build dependencies if necessary echo "Installing build dependencies..." if apt-get install -y build-essential linux-headers-$(uname -r) &gt;/dev/null ; then echo "Done!" else exit 1 fi # Going into the driver source directory cd e1000e-3.0.4/src/ # Building driver and updating initramfs echo "Building module and updating initramfs..." if { make install &amp;&amp; update-initramfs -k all -u; } &gt;/dev/null ; then echo "Done!" else exit 1 fi echo "Purging unnecessary build dependencies..." if apt-get -y purge build-essential &gt;/dev/null ; then echo "Done!" else exit 1 fi # Restarting iface echo "Restarting iface!" { ifdown eth0 &amp;&amp; ifup eth0; } &amp;&gt;/dev/null # Checking installed driver version if [[ $(modinfo -F version e1000e) == "3.0.4-NAPI" ]] ; then echo "Driver succesfully installed!" exit 0 else echo "Something Wrong...Try to re-install!" exit 1 fi </code></pre>
[]
[ { "body": "<p>Here is simplified version of the script:</p>\n\n<pre><code>#! /bin/bash\n\nDRV_PKG_NAME=\"e1000e-3.0.4.tar.gz\"\nDRV_PKG_URL=\"http://downloadmirror.intel.com/15817/eng/e1000e-3.0.4.tar.gz\"\nERR_LOG=\"err.log\"\n\n# Redirecting all stderr \nexec 2&gt;$ERR_LOG\n\n# Function declaration\nerror_action () {\n echo \"Failed!\" \n exit 1\n}\n\n# Downloading driver and extracting it to the current directory\necho \"Downloading and extracting driver package...\"\n\nwget -q ${DRV_PKG_URL} &amp;&amp; tar zxf ${DRV_PKG_NAME} || error_action\n\n# Installing required build dependencies if necessary\necho \"Installing build dependencies...\"\n\napt-get install -y build-essential linux-headers-$(uname -r) &gt;/dev/null || error_action\n\n# Going into the driver source directory\ncd e1000e-3.0.4/src/ \n\n# Building driver and updating initramfs\necho \"Building module and updating initramfs...\"\n\n{ make install &amp;&amp; update-initramfs -k all -u; } &gt;/dev/null || error_action \n\necho \"Purging unnecessary build dependencies...\"\n\napt-get -y purge build-essential &gt;/dev/null || error_action\n\n# Restarting iface\necho \"Restarting iface...\"\n\n{ ifdown eth0 &amp;&amp; ifup eth0; } &amp;&gt;/dev/null || error_action\n\n# Checking installed driver version\nif [[ $(modinfo -F version e1000e) == \"3.0.4-NAPI\" ]]; then\n echo \"Driver successfully installed!\"\nelse \n echo \"Something wrong... Try depmod -a or re-install again!\"\n exit 1\nfi\n\nexit 0\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T03:08:55.080", "Id": "43005", "ParentId": "42991", "Score": "2" } }, { "body": "<p>If you want to avoid the <code>if</code>..<code>else</code> constructs you have strewn throughout the script (which is commendable), the best thing to do is to use a <code>bash</code> function with an appropriate name (e. g. <code>fail</code>) to do the thing you're doing throughout the script for you. My rule of thumb is that if I'm writing the same code more than thrice, I'm Doing It Wrong and something needs to be abstracted.</p>\n\n<p>Also, <code>bash</code> has built-in mechanism for \"did that thing I just tried work\" tests, namely <code>||</code> chains, which execute the command after the <code>||</code> if the previous command has a <em>nonzero</em> exit code, as well as <code>&amp;&amp;</code>, which only executes the next command if the previous command has a <em>zero</em> exit code. For example, if I rewrite one of your <code>if</code>..<code>else</code> clauses thusly:</p>\n\n<pre><code>fail() {\n echo \"$*\"\n exit 1\n}\n\n# Example:\nwget -q ${DRV_PKG_URL} &amp;&amp; tar zxf ${DRV_PKG_NAME} || fail \"Unable to download from ${DRV_PKG_URL}\" &amp;&amp; echo \"Done!\"\n</code></pre>\n\n<p>..if the <code>wget</code> succeeds, the call to <code>fail</code> is skipped, and we proceed to <code>echo</code>. If <code>wget</code> fails, we run call <code>fail</code>, which intrinsically exits the script after displaying the specified message.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T20:14:27.893", "Id": "74347", "Score": "0", "body": "`&& echo \"Done!\"` will not work properly in the following case: `{ make install && update-initramfs -k all -u; } >/dev/null || error_action && echo \"Done!\"`\n`echo` will be executed even if the previous command fails." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T21:47:57.837", "Id": "74366", "Score": "0", "body": "@powerthrash I think that can be fixed with `set -o pipe fail` up at the top of the script." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T18:43:14.930", "Id": "43085", "ParentId": "42991", "Score": "4" } }, { "body": "<h2>Simplifying the if-else that exit on failure</h2>\n\n<p>When the failure case of an <code>if</code> exits, you could move the success case out of the <code>if</code>, right after it, which will make it a bit shorter. And instead of an <code>if</code>, you could further simplify using the <code>||</code> operator. For example given this pattern:</p>\n\n<blockquote>\n<pre><code>if cmd; then\n echo \"Done!\"\nelse\n exit 1\nfi\n</code></pre>\n</blockquote>\n\n<p>You could simplify as:</p>\n\n<pre><code>cmd || exit 1\necho \"Done!\"\n</code></pre>\n\n<p>You could apply this to all your ifs where you exit in case of failure.</p>\n\n<p>But rather than just fail quietly, it would be better to do as <a href=\"https://codereview.stackexchange.com/users/37726/dopeghoti\">@dopeghoti</a> suggested and create a <code>fail</code> function and print some text in case of failure.</p>\n\n<pre><code>fail() {\n echo \"$*\"\n exit 1\n}\n\ncmd || fail 'Ouch, command failed'\necho \"Done!\"\n</code></pre>\n\n<h2>Excessive comments</h2>\n\n<p>You have many obvious comments that add no value at all:</p>\n\n<pre><code># Downloading driver and extracting it to current directory\necho \"Downloading and extracting driver package...\"\n\n# Going into the driver source directory\ncd e1000e-3.0.4/src/ \n</code></pre>\n\n<p>In general, it's best when the code is self-explanatory. And in your script it's already the case, so you can remove all comments.</p>\n\n<h2>Error checking</h2>\n\n<p>Although you were careful to check errors in general, you forgot one:</p>\n\n<pre><code>cd e1000e-3.0.4/src/ \n</code></pre>\n\n<p>Sure, if the <code>tar</code> earlier was successful, then this directory <em>must</em> exist, right? But what if one year later you update your script to get the package from <code>e1000e-3.1.14.tar.gz</code> instead and (heaven forbid) forget to update this directory name later in the script? If the <code>cd</code> command fails the script will happily continue and run the remaining commands, building whatever source you may have in the current directory instead of the right one. This will be safer:</p>\n\n<pre><code>cd e1000e-3.0.4/src/ || fail oopsie\n</code></pre>\n\n<h2>Use more constants</h2>\n\n<p>It would be better to move more constants near the top of the file:</p>\n\n<pre><code>DRV_BASE_NAME=e1000e-3.0.4\nDRV_SRC_DIR=$DRV_BASE_NAME/src\nDRV_PKG_NAME=$DRV_BASE_NAME.tar.gz\nDRV_PKG_URL=http://downloadmirror.intel.com/15817/eng/$DRV_PKG_NAME\nMODULE_NAME=e1000e\nMODULE_VERSION=3.0.4-NAPI\n</code></pre>\n\n<p>It will make the script easier to maintain.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-31T07:04:18.667", "Id": "52147", "ParentId": "42991", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T23:09:36.803", "Id": "42991", "Score": "12", "Tags": [ "bash", "linux", "shell" ], "Title": "Bash script that updates Intel e1000e driver" }
42991
<p>I have an ASP.NET MVC 5 web application using the repository pattern, and I have several controllers that need to call my <code>_loggingService</code> (queries audit logs) to get the last updated information for certain pages, not all pages.</p> <p>I want to abstract this method into a common place, so that I don't have duplicated code in each controller where it is used.</p> <p>I don't want to use the base controller, because I don't want to have to inject my service dependency into every controller, because it isn't used on a lot of controllers.</p> <p>I don't want to make a common static class in my Application Layer, because I want to test it, and I want to avoid a static implementation.</p> <p>I can't put it in another project, because it will create a circular reference to my Web Application Project because it is populating the <code>LastUpdatedViewModel</code>, which is an object on several other viewmodels in the project.</p> <p>How do I architect this?</p> <p><code>HttpGet</code> for an <code>EditPage</code>:</p> <pre><code>[HttpGet] public virtual ActionResult Edit() { var settings = settingsService.GetSettingsForType(SettingTypeEnum.Application); var viewModel = new AppSettingsEditViewModel { KeyBitLengthList = GetKeyBitLengthListItems(), LastUpdatedViewModel = GetLastUpdated(Url.Action(MVC.ApplicationSettings.Edit(), Request.Url.Scheme, Request.Url.Host)), ....... } } </code></pre> <p><code>GetLastUpdated</code> is the method I want to extract. Here it is:</p> <pre><code>public LastUpdatedViewModel GetLastUpdated(string url) { var auditLog = _loggingService.GetMostRecentAudit(url); if (auditLog != null) { var lastUpdatedViewModel = new LastUpdatedViewModel { LastUpdated = String.Format("{0} {1} {2}", "Last Updated:", auditLog.UserAccountEmail, auditLog.CreatedDate) }; return lastUpdatedViewModel; } return null } </code></pre> <p>BONUS POINTS for whomever can give me an elegant solution on how to get <code>Request.Url.Scheme</code> and <code>Request.Url.Host</code> mocked, and implemented in Unit Tests for our controllers, as we DO currently have unit tests on those. I'd also like to get this code tested and passing. Currently, my only solution to get tests passing was to just check for nulls on <code>Request</code> and <code>Request.Url</code>, and if either of those were null, return null in <code>GetLastUpdated()</code>, like so:</p> <pre><code>private LastUpdatedViewModel GetLastUpdated() { if (Request == null) return null; if (Request.Url == null) return null; var url = Url.Action(MVC.EmailTemplate.EditSmtpSettings(), Request.Url.Scheme, Request.Url.Host); var auditLog = _loggingService.GetMostRecentAudit(url); if (auditLog != null) { var lastUpdatedViewModel = new LastUpdatedViewModel { LastUpdated = String.Format("{0} {1} {2}", "Last Updated:", auditLog.UserAccountEmail, auditLog.CreatedDate) }; return lastUpdatedViewModel; } return null; } </code></pre> <p>Which isn't a solution at all, only working code. What I need is a dynamic method that accepts a string URL parameter generated from a controller using T4MVC, that calls the service layer and builds my <code>LastUpdatedViewModel</code>.</p> <p>Here is a controller test that fails because <code>Request</code> is null:</p> <pre><code>[Test] public void EditGET_ModalityKeyBitLengthSettingInList_ViewModelModalityKeyBitLengthEqual() { var appSettings = new List&lt;Setting&gt; { new Setting { Key = SettingsConstants.ModalityKeyBitLength, Value = "1024" } }; AutoMocker.Get&lt;ISettingsService&gt;() .Stub(x =&gt; x.GetSettingsForType(SettingTypeEnum.Application)) .Return(appSettings); AutoMocker.ClassUnderTest.ControllerContext = MockControllerContext(); var result = AutoMocker.ClassUnderTest.Edit() as ViewResult; var viewModel = result.Model as AppSettingsEditViewModel; Assert.AreEqual(1024, viewModel.Settings.ModalityKeyBitLength); } protected ControllerContext MockControllerContext() { var context = MockRepository.GenerateStub&lt;ControllerContext&gt;(); var httpContext = MockRepository.GenerateStub&lt;HttpContextBase&gt;(); var session = MockRepository.GenerateStub&lt;HttpSessionStateBase&gt;(); httpContext.Stub(x =&gt; x.Session).Return(session); httpContext.Expect(x =&gt; x.Cache).Return(HttpRuntime.Cache).Repeat.Any(); context.HttpContext = httpContext; return context; } </code></pre> <p>What I had done in another area of the application that used T4MVC was to just rip T4MVC out, and I added const strings in the service layer for URLs that we needed when we were building emails to send in our service layer.</p> <p>Is T4MVC able to be implemented elegantly? The more I use it the more it just seems like a problem rather than a solution. But that's probably because I'm doing it wrong.</p>
[]
[ { "body": "<p>Well, my first attempt is to suggest injecting a mapper into the controllers you want to do this for (assuming you are using a DI framework. If not anyone of the popular choices out there will meet your needs. AutoMapper, Unity, Autofaq etc).</p>\n\n<pre><code>public interface IMap&lt;TTarget, TSource&gt; \n where TTarget: class\n where TSource: class\n{\n TTarget Map(TSource source);\n}\n\npublic interface ILoggingServiceAdapter : IMap&lt;TTarget, TSource&gt;\n{\n // any other items you wish to expose from your logging service\n}\n\npublic class LoggingServiceMapper : ILoggingServiceAdapter \n{ \n private readonly LoggingService _loggingService;\n public LoggingServiceMapper(LoggingService loggingService)\n {\n _loggingService = loggingService;\n }\n\n public LastUpdatedViewModel Map(string url)\n {\n var auditLog = _loggingService.GetMostRecentAudit(url);\n if (auditLog != null)\n {\n var lastUpdatedViewModel = new LastUpdatedViewModel\n {\n LastUpdated = String.Format(\"{0} {1} {2}\", \"Last Updated:\", auditLog.UserAccountEmail, auditLog.CreatedDate)\n };\n return lastUpdatedViewModel;\n }\n return null;\n }\n}\n</code></pre>\n\n<p>Hence your methods would now look like</p>\n\n<pre><code>private readonly ILoggingServiceAdapter _loggingService;\n\npublic MyControllerConstructor(ILoggingServiceAdapter loggingService)\n{\n _loggingService = loggingService;\n}\n[HttpGet]\npublic virtual ActionResult Edit()\n{\n var settings = settingsService.GetSettingsForType(SettingTypeEnum.Application);\n\n var viewModel = new AppSettingsEditViewModel\n {\n KeyBitLengthList = GetKeyBitLengthListItems(),\n LastUpdatedViewModel = _loggingService.Map(Url.Action(\n MVC.ApplicationSettings.Edit(),\n Request.Url.Scheme,\n Request.Url.Host)),\n .......\n }\n}\n</code></pre>\n\n<p>Now I don't know about the BONUS option, but if you wanted to further eliminate the need\nto always be specifying the Scheme and Host when Creating the action you could consider writing an extension class on UrlHelper.</p>\n\n<pre><code>public static class UrlHelperExtensions\n{\n public static string Action(this UrlHelper urlHelper, string action, Uri uri) {\n return urlHelper.Action(action, uri.Scheme, uri.Host);\n }\n}\n</code></pre>\n\n<p>Hence your code now becomes like:</p>\n\n<pre><code>[HttpGet]\npublic virtual ActionResult Edit()\n{\n var settings = settingsService.GetSettingsForType(SettingTypeEnum.Application);\n\n var viewModel = new AppSettingsEditViewModel\n {\n KeyBitLengthList = GetKeyBitLengthListItems(),\n LastUpdatedViewModel = _loggingService.Map(Url.Action(\n MVC.ApplicationSettings.Edit(),\n Request.Url)),\n .......\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T02:56:58.153", "Id": "74176", "Score": "0", "body": "Great suggestion. I really like it, thank you for taking the time to reply. I would love to implement it, but I'd rather not implement AutoMapper, instead I would rather write my own custom mapping utilities. I'm assuming TTarget, TSource are AutoMapper provided classes?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T03:06:46.617", "Id": "74178", "Score": "0", "body": "No, this is just your own interface to work behind a mapping layer. TTarget and TSource are just any generic class. This then might allow you to inject mapping services if you wished into your controllers." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T04:06:51.967", "Id": "74197", "Score": "0", "body": "What's supposed to be in the adapter in your example? Your edit method is still calling the Logging Service directly... Am I missing something here?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T04:16:03.213", "Id": "74202", "Score": "0", "body": "Sorry, no the _loggingService is an implementation of the ILoggingServiceAdapter interface so it's calling the loggingservice itself indirectly through this interface/class" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T16:58:24.913", "Id": "74324", "Score": "0", "body": "This put me on the right track, architecture-wise, although I ended up doing a few things a little differently. So marking your answer as accepted. Thank you." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T01:57:30.330", "Id": "43003", "ParentId": "42995", "Score": "2" } } ]
{ "AcceptedAnswerId": "43003", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T23:18:48.527", "Id": "42995", "Score": "3", "Tags": [ "c#", "unit-testing", "asp.net-mvc-5" ], "Title": "Web application using the repository pattern" }
42995
<p>The below code is for printing level-by-level in a binary tree:</p> <pre><code>//level order printing public static void levelOrderPrint(Node root){ Queue&lt;Node&gt; que = new LinkedList&lt;Node&gt;(); Node mark = new Node(0); if(root != null){ que.add(root); que.add(mark); } while(!que.isEmpty()){ Node temp = que.poll(); if(temp != mark) System.out.print(temp.key); if(temp == mark){ if(que.peek() == mark || que.isEmpty()){ return; } que.add(mark); System.out.println(); } if(temp.left != null){ que.add(temp.left); } if(temp.right != null){ que.add(temp.right); } } } </code></pre> <p>I would like to know if there are any bugs or possible optimizations.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T00:12:06.337", "Id": "74165", "Score": "3", "body": "Hi and welcome to Code Review! To the best of your knowledge does this code works ? We won't review your code if you think there is bug in it, but if you think all your code works as expected we will happily review your code!" } ]
[ { "body": "<p>This is good code.</p>\n\n<h2>General</h2>\n\n<p>While it does what it says it will do, here is one beef I have with it, but it's a small one:</p>\n\n<blockquote>\n<pre><code> Node temp = que.poll();\n if(temp != mark)\n System.out.print(temp.key);\n</code></pre>\n</blockquote>\n\n<p>No braces, no indenting, code meaning is confused.....</p>\n\n<p>That should be:</p>\n\n<pre><code> Node temp = que.poll();\n if(temp != mark) {\n System.out.print(temp.key);\n }\n</code></pre>\n\n<p>There is a fair amount of debate about using '1-liner' <code>if</code> statements. The following are reasons why I despise them:</p>\n\n<ul>\n<li>the meaning of the code becomes white-space defined (like your indenting problem above). There are whole languages ( <em>cough</em> Pythong <em>cough</em> ) which are defined by whitespace. Java is defined by braces <code>{}</code>. Use them.</li>\n<li>If you use a version-control-system like CVS, SVN, Git, etc. then small changes to code blocks can become visually big in a change-log. Adding one line to the code means updating 3 lines.</li>\n<li>it can lead to bugs where people do not put braces in to lines where there should be two statements.</li>\n<li>etc.</li>\n<li>etc.</li>\n</ul>\n\n<p>I don't like 1-liners Sam-I-Am</p>\n\n<p>OK. But, as code goes, yours is good. How can it be better?</p>\n\n<h2>Improvements</h2>\n\n<ul>\n<li><p>You can make <code>mark</code> a private static final instance:</p>\n\n<pre><code>private static final Node MARK = new Node(0);\n</code></pre></li>\n<li><p>The following statement has redundancy:</p>\n\n<blockquote>\n<pre><code> if(que.peek() == mark || que.isEmpty()){\n return;\n }\n</code></pre>\n</blockquote>\n\n<p>it could be:</p>\n\n<pre><code> if(que.isEmpty()){\n return;\n }\n</code></pre>\n\n<p>It is not possible for the queue to have two consecutive marks, so the peek can never be a mark.</p></li>\n<li><p>Now, back to that indentation on the <code>println()</code> method call... here's your code:</p>\n\n<blockquote>\n<pre><code> if(temp != mark)\n System.out.print(temp.key);\n if(temp == mark){\n if(que.peek() == mark || que.isEmpty()){\n return;\n }\n que.add(mark);\n System.out.println();\n }\n</code></pre>\n</blockquote>\n\n<p>if you had correct braces, etc. you would see that you would be better off with an if/else condition, and that will save an <code>if</code> check:</p>\n\n<pre><code> if(temp != mark) {\n System.out.print(temp.key);\n } else {\n if(que.peek() == mark || que.isEmpty()){\n return;\n }\n que.add(mark);\n System.out.println();\n }\n</code></pre></li>\n<li><p><code>System.out.println(...)</code> and all the <code>print*(...)</code> variants are slow (they are synchronized). Your code would be faster if you used a system like:</p>\n\n<pre><code>StringBuilder sb = new StringBuilder();\n....\n\n if (temp != mark) {\n sb.append(temp.key);\n } else {\n ....\n sb.append(\"\\n\");\n }\n\n....\nSystem.out.print(sb);\n</code></pre></li>\n</ul>\n\n<h2>Conclusion</h2>\n\n<p>Otherwise, this is good code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T01:33:16.617", "Id": "43001", "ParentId": "42997", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T23:46:17.117", "Id": "42997", "Score": "3", "Tags": [ "java", "algorithm", "tree" ], "Title": "Printing the values on each level of a Binary Tree" }
42997
<p>Things I can think of include integer overflow, if the input type is int, etc. But other than that, what do you think is wrong with this code, design-wise, style-wise, and also in terms of other edge/corner cases?</p> <p><strong>binaryheap.h</strong></p> <pre><code>#ifndef INCLUDE_BINARYHEAP_H_ #define INCLUDE_BINARYHEAP_H_ #include &lt;vector&gt; #include &lt;iterator&gt; #include &lt;cmath&gt; // Assume min heap template &lt;class T&gt; class BinaryHeap { private: unsigned long heap_size_; std::vector&lt;T&gt; data_; // typedef typename std::vector&lt;T&gt;size_type heap_size_; void SiftUp(unsigned long node); void SiftDown(unsigned long node); public: BinaryHeap(unsigned long num_elements); BinaryHeap(); ~BinaryHeap() {} // Misc Operations (using STL namimg). unsigned long count() { return heap_size_;} // Get count of objects. void clear(); // clear the object for reuse. // Main operations allowed by the data structure. template &lt;class I&gt; int Heapify(I start, I end); const T FindXtrma(); const T ExtractXtrma(); void Insert(const T&amp; data); // Insert(key) void Delete(unsigned long element); // Delete(element) void IncreaseKey(unsigned long element, const T&amp; change); void DecreaseKey(unsigned long element, const T&amp; change); unsigned long get_size(){return(heap_size_);} /* void Merge(class &amp;Heap); */ }; #endif // INCLUDE_BINARYHEAP_H_ </code></pre> <p><strong>binaryheap.cpp</strong></p> <pre><code>#include &lt;binaryheap.h&gt; #include &lt;vector&gt; #include &lt;algorithm&gt; template &lt;class T&gt; BinaryHeap&lt;T&gt;::BinaryHeap(unsigned long num_elements) { heap_size_ = num_elements; data_.reserve(num_elements); } template &lt;class T&gt; BinaryHeap&lt;T&gt;::BinaryHeap() { heap_size_ = 0; } template &lt;class T&gt; void BinaryHeap&lt;T&gt;::SiftDown(unsigned long node) { unsigned long lchild = 2*node+1; unsigned long rchild = 2*node+2; bool rexists = rchild &lt; heap_size_; bool lexists = lchild &lt; heap_size_; if (!lexists &amp;&amp; !rexists) return; bool left_small; if (rexists &amp;&amp; data_[lchild] &gt; data_[rchild]) left_small = false; else left_small = true; if (data_[lchild] &lt; data_[node] &amp;&amp; left_small) { std::swap(data_[node], data_[lchild]); SiftDown(lchild); } else if (data_[rchild] &lt; data_[node] &amp;&amp; rexists &amp;&amp; !left_small) { std::swap(data_[node], data_[rchild]); SiftDown(rchild); } } template &lt;class T&gt; void BinaryHeap&lt;T&gt;::SiftUp(unsigned long node) { long parent = floor(node/2)-(node+1)%2; bool pexists = parent &gt;= 0; if (pexists &amp;&amp; data_[parent] &gt; data_[node]) { std::swap(data_[parent], data_[node]); SiftUp(parent); } } template &lt;class T&gt; template &lt;class I&gt; int BinaryHeap&lt;T&gt;::Heapify(I start, I end) { unsigned long d = std::distance(start, end); if (data_.size() != 0) this-&gt;clear(); if (heap_size_ == 0) heap_size_ = d; // may be warn them. if (d != heap_size_) heap_size_ = d; for (I i = start; i != end; ++i) data_.push_back(*i); for (unsigned long i = heap_size_-1; i &lt;= heap_size_; --i) { SiftDown(i); } return 0; } template &lt;class T&gt; const T BinaryHeap&lt;T&gt;::FindXtrma() { if (heap_size_ &lt;= 0) return ((T)(0)); return data_.front(); // return this-&gt;data_[0]; } template &lt;class T&gt; const T BinaryHeap&lt;T&gt;::ExtractXtrma() { if (heap_size_ &lt;= 0) return ((T)(0)); T max_value = data_.front(); std::swap(data_.front(), data_.back()); data_.pop_back(); --heap_size_; SiftDown(0); return max_value; } template &lt;class T&gt; void BinaryHeap&lt;T&gt;::Insert(const T&amp; new_node) { data_.push_back(new_node); SiftUp(data_.size()-1); ++heap_size_; } template &lt;class T&gt; void BinaryHeap&lt;T&gt;::Delete(unsigned long element) { if (element &gt;= heap_size_) return; std::swap(data_[element], data_.back()); data_.pop_back(); --heap_size_; SiftUp(element); SiftDown(element); } template &lt;class T&gt; void BinaryHeap&lt;T&gt;::IncreaseKey(unsigned long element, const T&amp; change) { data_[element] = data_[element]+change; SiftDown(element); } template &lt;class T&gt; void BinaryHeap&lt;T&gt;::DecreaseKey(unsigned long element, const T&amp; change) { data_[element] = data_[element]-change; SiftUp(element); } template &lt;class T&gt; void BinaryHeap&lt;T&gt;::clear() { if (data_.size() &gt; 0) data_.clear(); } template class BinaryHeap&lt;int&gt;; template class BinaryHeap&lt;float&gt;; template class BinaryHeap&lt;unsigned int&gt;; template class BinaryHeap&lt;long&gt;; template int BinaryHeap&lt;int&gt;::Heapify(std::vector&lt;int&gt;::iterator, std::vector&lt;int&gt;::iterator); template int BinaryHeap&lt;float&gt;::Heapify(std::vector&lt;float&gt;::iterator, std::vector&lt;float&gt;::iterator); template int BinaryHeap&lt;unsigned int&gt;::Heapify(std::vector&lt;unsigned int&gt;::iterator, std::vector&lt;unsigned int&gt;::iterator); template int BinaryHeap&lt;long&gt;::Heapify(std::vector&lt;long&gt;::iterator, std::vector&lt;long&gt;::iterator); </code></pre> <p><strong>binaryheap_gtest.cpp</strong></p> <pre><code>#include &lt;binaryheap.h&gt; #include &lt;vector&gt; #include "gtest/gtest.h" using namespace std; namespace { template&lt;class T&gt; class BHeapTest : public ::testing::Test { public: BinaryHeap&lt;T&gt; b1; BHeapTest() { b1 = BinaryHeap&lt;T&gt;(1000);} virtual ~BHeapTest() {} protected: vector&lt;T&gt; data_; virtual void SetUp() { unsigned long max_val = 2000; for (T i = 1000; i &lt; (T)max_val; ++i) data_.push_back(i); b1.Heapify(data_.begin(), data_.end()); } virtual void TearDown() { data_.clear(); } }; typedef ::testing::Types&lt;int, unsigned int, long&gt; MyTypes; TYPED_TEST_CASE(BHeapTest, MyTypes); TYPED_TEST(BHeapTest, SimpleTest) { EXPECT_EQ(1000, this-&gt;b1.FindXtrma()); EXPECT_EQ(1000, this-&gt;b1.get_size()); this-&gt;b1.Insert(3000); EXPECT_EQ(1000, this-&gt;b1.FindXtrma()); EXPECT_EQ(1001, this-&gt;b1.get_size()); this-&gt;b1.Delete(0); EXPECT_EQ(1001, this-&gt;b1.FindXtrma()); EXPECT_EQ(1000, this-&gt;b1.get_size()); this-&gt;b1.DecreaseKey(999, 1000); EXPECT_EQ(999, this-&gt;b1.FindXtrma()); EXPECT_EQ(1000, this-&gt;b1.get_size()); this-&gt;b1.IncreaseKey(0,1000); EXPECT_EQ(1001, this-&gt;b1.FindXtrma()); EXPECT_EQ(1000, this-&gt;b1.get_size()); } TYPED_TEST(BHeapTest, ComplexTest) { EXPECT_EQ(1000, this-&gt;b1.FindXtrma()); EXPECT_EQ(1000, this-&gt;b1.get_size()); for (int i = 0; i &lt; 10; ++i) this-&gt;b1.ExtractXtrma(); EXPECT_EQ(1010, this-&gt;b1.FindXtrma()); EXPECT_EQ(990, this-&gt;b1.get_size()); for (int i = 0; i &lt; 10; ++i) this-&gt;b1.ExtractXtrma(); EXPECT_EQ(1020, this-&gt;b1.FindXtrma()); EXPECT_EQ(980, this-&gt;b1.get_size()); this-&gt;b1.Insert(3232); EXPECT_EQ(981, this-&gt;b1.get_size()); } } // namespace int main(int argc, char **argv) { ::testing::InitGoogleTest(&amp;argc, argv); return RUN_ALL_TESTS(); } </code></pre>
[]
[ { "body": "<p>Since you seem to be tryingy to mimic the style of STL containers (at least, that's what your comments say), there are several things you could improve:</p>\n\n<h2>STL containers subtypes</h2>\n\n<p>Most of the STL containers have subtypes. I am pretty sure that some parts of the standard library use these subtypes. Therefore, if you want your code to work with the generic algorithms, you better add those subtypes:</p>\n\n<ul>\n<li><code>value_type</code>: probably be an alias for <code>T</code>, or <code>std::vector&lt;T&gt;::value_type</code>.</li>\n<li><code>size_type</code>: in your case, it would be <code>unsigned long</code> since it is the type you use for the size of your heap. Generally, the type <code>std::size_t</code> is used for <code>size_type</code> though. The best solution in your case would be <code>std::vector&lt;T&gt;::size_type</code></li>\n<li><code>reference</code>: often <code>T&amp;</code>.</li>\n<li>There are many other subtypes. Look at <a href=\"http://en.cppreference.com/w/cpp/container/vector\">the documentation for <code>std::vector</code></a> and see which one you can take from the underlying <code>std::vector</code> and which one you better let alone (for example, you don't provide anything to work with iterators and you don't provide any mechanism for allocators).</li>\n</ul>\n\n<h2>Size of the heap</h2>\n\n<p>First of all, you have two functions to obtain the size of your heap, <code>count</code> and <code>get_size</code>, which is redundant. <code>count</code> is there so that your heap looks like an STL container, however, the standard method name to get the size of a container is <code>size</code>, not <code>count</code>. There is no need for the function <code>get_size</code>: it is a duplicate, it does not conform to STL naming, and it does not even conform to the case of your other functions.</p>\n\n<p>I find the fact that the size of your heap does not correspond to the size of the underlying <code>std::vector</code> rather troubling. When I write this:</p>\n\n<pre><code>BinaryHeap&lt;int&gt; foo(8);\n</code></pre>\n\n<p>I know that enough memory has been reserved for 8 elements, but I would expect the size to be 0. Moreover, if I write this:</p>\n\n<pre><code>BinaryHeap&lt;int&gt; foo(8);\nfoo.FindXtrma();\n</code></pre>\n\n<p>I then have no idea what my value will be since the size is 8 and I did not control the inserted values. Generally speaking, you probably should implement <code>size</code> like this to avoid surprises:</p>\n\n<pre><code>size_type size() const\n{\n return data_.size();\n}\n</code></pre>\n\n<p>There are probably other things which could be improved: make your <code>BinaryHeap</code> more like a STL container by enabling a support for allocators for example (you could forward the allocator stuff directly to the underlying <code>std::vector</code> to avoid having to actually handle them). Also, instead of a real container, you could try to make your <code>BinaryHeap</code> a container adapter (like <code>std::stack</code> or <code>std::queue</code>) so that it can use an <code>std::vector</code> or an <code>std::deque</code> (or any conforming container).</p>\n\n<h2>Miscellaneous C++ stuff</h2>\n\n<p><em>It has been more than a year since the review, but it seems that it has some views, so I thought that it could be a good idea to complete it with some miscellaneous additional comments...</em></p>\n\n<ul>\n<li><p>You have template code in a <code>.cpp</code> file, this is really error-prone since templates are not compiled (their specializations are instantiated and compiled when needed). If you want to write a template library with separate interface and implementation, then put the interface in a <code>.h</code> file and include a <code>.inl</code> or <code>.tpp</code> file at the end of the header (these are the most common extensions for \"implementation header files\") with the implementation.</p></li>\n<li><p>You should <code>const</code>-qualify functions that do not alter the state of the class. For example, <code>count</code> (or <code>size</code> as I mentioned before) does not alter the heap and can be <code>const</code>-qualified to document that.</p></li>\n<li><p>Sometimes, your names should be more explicit. For example, <code>template &lt;class I&gt;</code> isn't explicit enough. It is easy to guess that it accepts iterators, but which kind of iterators? From the implementation, I think that it can accept <a href=\"http://en.cppreference.com/w/cpp/concept/ForwardIterator\">forward iterators</a>, so you should use names which reflect that fact:</p>\n\n<pre><code>template &lt;class ForwardIterator&gt;\nint Heapify(ForwardIterator start, ForwardIterator end);\n</code></pre></li>\n<li><p>By the way, this function does not return anything useful, it always return <code>0</code>, which is at best useless and at worst confusing (and undocumented). The best thing to do is to make your function return <code>void</code> so that it is clear that it isn't returning anything:</p>\n\n<pre><code>template &lt;class ForwardIterator&gt;\nvoid Heapify(ForwardIterator start, ForwardIterator end);\n</code></pre></li>\n<li><p>You can replace this loop:</p>\n\n<pre><code>for (I i = start; i != end; ++i)\n data_.push_back(*i);\n</code></pre>\n\n<p>...by a call to <a href=\"http://en.cppreference.com/w/cpp/algorithm/copy\"><code>std::copy</code></a> from the standard header <code>&lt;algorithm&gt;</code> with <a href=\"http://en.cppreference.com/w/cpp/iterator/back_inserter\"><code>std::back_inserter</code></a> to automatically perform the calls to <code>push_back</code> on the <code>data_</code>.</p>\n\n<pre><code>std::copy(start, end, std::back_inserter(data_));\n</code></pre></li>\n<li><p>Whenever possible, try to initialize what you can into a constructor initialization list instead of initializing things in the constructor body. Take for example this constructor:</p>\n\n<pre><code>template &lt;class T&gt;\nBinaryHeap&lt;T&gt;::BinaryHeap(unsigned long num_elements)\n{ heap_size_ = num_elements;\n data_.reserve(num_elements);\n}\n</code></pre>\n\n<p>It is trivial to initialize <code>heap_size_</code> from the initialization list, and feeding an integer to an <code>std::vector</code> constructor will actually be equivalent to a call to <code>reserve</code>. That means that you can write this constructor as:</p>\n\n<pre><code>template &lt;class T&gt;\nBinaryHeap&lt;T&gt;::BinaryHeap(unsigned long num_elements):\n heap_size_(num_elements),\n data_(num_elements)\n{}\n</code></pre></li>\n<li><p>This boolean initialization looks rather complicated:</p>\n\n<pre><code>bool left_small;\nif (rexists &amp;&amp; data_[lchild] &gt; data_[rchild])\n left_small = false;\nelse\n left_small = true;\n</code></pre>\n\n<p>You can make a one-liner out of it which shouldn't be harder to read:</p>\n\n<pre><code>bool left_small = !(rexists &amp;&amp; data_[lchild] &gt; data_[rchild]);\n</code></pre>\n\n<p>You can even change it a little bit to remove the leading <code>operator!</code>:</p>\n\n<pre><code>bool left_small = !rexists || data_[lchild] &lt;= data_[rchild];\n</code></pre></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-04T00:30:02.307", "Id": "74862", "Score": "0", "body": "Mimicking style of STL containers : I was not exactly intending that you thought. I was following Google Style Guide and the naming convention for getter and setter functions (or other simple functions) was an exception to their rule, and I was following the STL style naming. But your suggestion is a welcome change. Thanks for the nice review, will incorporate most of it." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T11:19:56.457", "Id": "43050", "ParentId": "42999", "Score": "16" } }, { "body": "<p>There is an error in the code:</p>\n\n<pre><code>if (data_[rchild] &lt; data_[node] &amp;&amp; rexists &amp;&amp; !left_small)\n</code></pre>\n\n<p>You have to check <code>rexists</code> before <code>data_[rchild]</code>:</p>\n\n<pre><code>if (rexists &amp;&amp; !left_small &amp;&amp; data_[rchild] &lt; data_[node])\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-05-23T05:46:22.410", "Id": "91551", "ParentId": "42999", "Score": "2" } } ]
{ "AcceptedAnswerId": "43050", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T01:10:53.933", "Id": "42999", "Score": "15", "Tags": [ "c++", "stl", "heap" ], "Title": "Implementation of binary heap in C++" }
42999
<p>The following is an <code>TaskScheduler</code> that always run tasks in a thread it maintains. When created, a name of the thread was specified. Once you schedule the first task, until it is been <code>Dispose</code>ed, a thread will be created and wait for tasks to execute.</p> <p>The reason of this class is that sometimes there is a need to guarantee that some tasks must be always scheduled in a specific thread (not the UI thread though). For example, some 3 party dll may have resource leak if you keep creating new threads to call its functions.</p> <pre><code>using Task = System.Threading.Tasks.Task; using Thread = System.Threading.Thread; using Barrier = System.Threading.Barrier; using Monitor = System.Threading.Monitor; using IDisposable = System.IDisposable; using TaskEnum = System.Collections.Generic.IEnumerable&lt;System.Threading.Tasks.Task&gt;; using TaskQueue = System.Collections.Generic.Queue&lt;System.Threading.Tasks.Task&gt;; using Enumerable = System.Linq.Enumerable; using ObjectDisposedException = System.ObjectDisposedException; using _Imported_Extensions_; namespace _Imported_Extensions_ { public static class Extensions { public static bool Any(this TaskEnum te) { return Enumerable.Any(te); } public static TaskEnum ToList(this TaskEnum te) { return Enumerable.ToList(te); } } } namespace TaskUtils { public class SameThreadTaskScheduler : System.Threading.Tasks.TaskScheduler, IDisposable { #region publics public SameThreadTaskScheduler(string name) { scheduledTasks = new TaskQueue(); threadName = name; } public override int MaximumConcurrencyLevel { get { return 1; } } public void Dispose() { lock (scheduledTasks) { quit = true; Monitor.PulseAll(scheduledTasks); } } #endregion #region protected overrides protected override TaskEnum GetScheduledTasks() { lock (scheduledTasks) { return scheduledTasks.ToList(); } } protected override void QueueTask(Task task) { if (myThread == null) myThread = StartThread(threadName); if (!myThread.IsAlive) throw new ObjectDisposedException("My thread is not alive, so this object has been disposed!"); lock (scheduledTasks) { scheduledTasks.Enqueue(task); Monitor.PulseAll(scheduledTasks); } } protected override bool TryExecuteTaskInline(Task task, bool task_was_previously_queued) { return false; } #endregion private readonly TaskQueue scheduledTasks; private Thread myThread; private readonly string threadName; private bool quit; private Thread StartThread(string name) { var t = new Thread(MyThread) { Name = name }; using (var start = new Barrier(2)) { t.Start(start); ReachBarrier(start); } return t; } private void MyThread(object o) { Task tsk; lock (scheduledTasks) { //When reaches the barrier, we know it holds the lock. // //So there is no Pulse call can trigger until //this thread starts to wait for signals. // //It is important not to call StartThread within a lock. //Otherwise, deadlock! ReachBarrier(o as Barrier); tsk = WaitAndDequeueTask(); } for (; ; ) { if (tsk == null) break; TryExecuteTask(tsk); lock (scheduledTasks) { tsk = WaitAndDequeueTask(); } } } private Task WaitAndDequeueTask() { while (!scheduledTasks.Any() &amp;&amp; !quit) Monitor.Wait(scheduledTasks); return quit ? null : scheduledTasks.Dequeue(); } private static void ReachBarrier(Barrier b) { if (b != null) b.SignalAndWait(); } } } </code></pre> <p>I used an unusual <code>using</code> block and put all method extensions in use into a single class. The reason is that I want to specify exactly what I wanted from the outside of the code. It is fine to use traditional using block instead without change any class code, but anyway focus on the class!</p> <p>What I am concerning is its concurrency correctness. I want to know although this seems to be working, is it actually correct? Are there better way (simpler) to achieve this? Coding style advises are also welcome, thanks.</p> <p><strong>Specific Questions</strong></p> <p>Is it safe to use <code>Pulse</code> rather than <code>PulseAll</code> in this case?</p>
[]
[ { "body": "<p>Not exactly a review, but since you are asking for simpler way... The simpler way is to run your tasks via dispatcher. Just run it on background thread:</p>\n\n<pre><code>_thread = new Thread(() =&gt;\n {\n _dispatcher = Dispatcher.CurrentDispatcher;\n Dispatcher.Run();\n });\n_thread.Start();\n</code></pre>\n\n<p>And use <code>_dispatcher.BeginInvoke</code> and <code>_dispatcher.Invoke</code> to run your tasks on that thread.\nIt is a lot simpler than reinventing the wheel. The obvious downside is wpf dependency.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T12:39:18.897", "Id": "76919", "Score": "2", "body": "Sorry, I marked another answer, because yours is \"not exactly a review\". But still, +1ed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-04T09:45:17.457", "Id": "403724", "Score": "0", "body": "Thanks. This is a nice trick and answers the question. Note I wasn't able to run other tasks on that thread, even using Dispatcher.Yield. I don't know why, that's the reason I built another answer to that question, using Tasks which BTW solves the dependency on UI-oriented framework." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T06:52:29.470", "Id": "43027", "ParentId": "43000", "Score": "15" } }, { "body": "<pre><code>using Task = System.Threading.Tasks.Task;\nusing Thread = System.Threading.Thread;\nusing Barrier = System.Threading.Barrier;\nusing Monitor = System.Threading.Monitor;\nusing IDisposable = System.IDisposable;\n</code></pre>\n<p>You don't need to write all those <code>using</code>s one class at a time. In C#, the common approach is to add a <code>using</code> once for each namespace you need. This is considered a bad practice in C++ (maybe that's why you did it this way?), but that's only because in C++, namespaces are not structured properly (almost everything is directly in <code>std</code>) and because the naming conventions there (<code>list</code>, not <code>List</code>) make collisions more likely.</p>\n<pre><code>using TaskEnum = System.Collections.Generic.IEnumerable&lt;System.Threading.Tasks.Task&gt;;\nusing TaskQueue = System.Collections.Generic.Queue&lt;System.Threading.Tasks.Task&gt;;\n</code></pre>\n<p>This is also not necessary, just add the necessary namespace usings, and the write <code>IEnumerable&lt;Task&gt;</code> or <code>Queue&lt;Task&gt;</code>, that's not that long.</p>\n<hr />\n<pre><code>namespace _Imported_Extensions_\n</code></pre>\n<p><code>_Imported_Extensions_</code> is a weird name for a namespace. Why all the underscores? And the convention is to use PascalCase (e.g. <code>ImportedExtensions</code>) for namespaces too.</p>\n<p>And what does the name even mean? Why is it important to stress out that those extensions were imported? And from where?</p>\n<p>Also, it's not common to have multiple namespaces in the same file. If the class is used only in this file, put it in the same namespace as everything else in that file.</p>\n<hr />\n<pre><code>public static bool Any(this TaskEnum te)\npublic static TaskEnum ToList(this TaskEnum te)\n</code></pre>\n<p>Both of the extension methods are completely unnecessary. If you just added <code>using System.Linq;</code>, both would work by themselves.</p>\n<hr />\n<pre><code>if (myThread == null)\n myThread = StartThread(threadName);\n</code></pre>\n<p>This is not thread-safe. If two threads call this method at the same time, <code>StartThread()</code> will be called twice and two threads will be created.</p>\n<p>Also, why is the thread started here and not in the constructor?</p>\n<hr />\n<pre><code>if (!myThread.IsAlive)\n</code></pre>\n<p>I don't think this is the right check here. Checking <code>quit</code> would be better, because that means enqueuing stops working as soon as the scheduler is disposed.</p>\n<hr />\n<p>I don't like that your fields are in the middle of the class. If you put them at (or near) the top, they will be easier to find.</p>\n<hr />\n<p>I think the way you're using <code>Barrier</code> is clumsy. If you want a notification that the worker thread is ready, use something like <code>ManualResetEvent</code>.</p>\n<p>Also, you seem to be trying to protect against <code>Barrier</code> being <code>null</code>, but that can never happen here. So doing that just makes your code longer and more confusing.</p>\n<p>Even better option would be to use a queue that already supports blocking when no items are available: <a href=\"http://msdn.microsoft.com/en-us/library/dd267312\" rel=\"nofollow noreferrer\"><code>BlockingCollection</code></a>.</p>\n<hr />\n<blockquote>\n<p>Is it safe to use <code>Pulse</code> rather than <code>PulseAll</code> in this case?</p>\n</blockquote>\n<p>Yes, it is, since you're always going to have only one thread waiting.</p>\n<hr />\n<p>Also, if I wanted something like this, I would either use <a href=\"http://msdn.microsoft.com/en-us/library/system.threading.tasks.concurrentexclusiveschedulerpair.exclusivescheduler\" rel=\"nofollow noreferrer\"><code>ConcurrentExclusiveSchedulerPair.ExclusiveScheduler</code></a>, if the tasks didn't have to execute on the same thread, just being mutually exclusive.</p>\n<p>Or <a href=\"https://github.com/dotnet/samples/tree/main/csharp/parallel/ParallelExtensionsExtras\" rel=\"nofollow noreferrer\">some scheduler from ParallelExtensionsExtras</a>, if a single thread was a requirement.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-10T22:43:03.213", "Id": "76164", "Score": "0", "body": "No, my way of use \"using\" is from Java and Haskell. In those languages, people prefer precise symbol import." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-04T06:53:53.043", "Id": "112678", "Score": "0", "body": "+1 **Live example**. From all the good answers provided by everyone here I am now getting a better understanding of appropriate \n\nuse of this topic and IMHO other programmers will definitely benifit from the knowledge sharing here. Some of the implementations \n\nthat I had worked in the past could have been better implemented using this knowledge. \n_IMHO, better samples for minimize learning curve are real applications **with full source code** and good patterns_" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T09:13:09.697", "Id": "518299", "Score": "0", "body": "@svick Could you specify which scheduler from PEE would be suitable if a single thread is a requirement? They have too many responsibilities there.." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2014-03-10T17:44:09.680", "Id": "43957", "ParentId": "43000", "Score": "11" } }, { "body": "<p>I had a similar problem. Here is an easy way to make all your tasks run exclusively on one thread for all tasks. And you can also run the them Concurrently to using <code>Scheduler.ConcurrentScheduler</code>. </p>\n\n<pre><code>ConcurrentExclusiveSchedulerPair Scheduler = new ConcurrentExclusiveSchedulerPair();\n\nTask.Factory.StartNew(() =&gt;\n {\n DoSomthing();\n }, CancellationToken.None, TaskCreationOptions.DenyChildAttach, Scheduler.ExclusiveScheduler);\n</code></pre>\n\n<h3>Resources:</h3>\n\n<p><a href=\"https://blog.stephencleary.com/2012/08/async-and-scheduled-concurrency.html\" rel=\"noreferrer\">Blog post: <em>Async and Scheduled Concurrency</em></a></p>\n\n<p><a href=\"https://msdn.microsoft.com/en-us/library/system.threading.tasks.concurrentexclusiveschedulerpair(v=vs.110).aspx\" rel=\"noreferrer\"><em>ConcurrentExclusiveSchedulerPair Class</em> on MSDN</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-02T13:18:19.550", "Id": "516128", "Score": "0", "body": "Unfortunately this runs tasks synchronously, but on different threads.\nSee https://dotnetfiddle.net/6roLaj (.NET Core) and https://dotnetfiddle.net/TrSA7q (.NET FW).\nThat's not OP wanted I suggest." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-02-20T18:15:18.677", "Id": "187967", "ParentId": "43000", "Score": "7" } }, { "body": "<p>Building on user161231's code (thanks!), here is a complete answer that uses modern .NET framework objects. Sorry it's not strictly a code review (although for me a code review that removes code and favors using frameworks's primitives is a good code review), but it answers the same question.</p>\n\n<p>It demonstrates not only how to run tasks on a specific thread, but also how to schedule other tasks on this unique thread and how to stop that thread:</p>\n\n<pre><code>var scheduler = new ConcurrentExclusiveSchedulerPair();\n\n// create a stop request source\nvar stop = new CancellationTokenSource();\n\n// this will run on a specific thread\nvar task = Task.Factory.StartNew(MyAction,\n stop.Token,\n stop.Token,\n TaskCreationOptions.DenyChildAttach,\n scheduler.ExclusiveScheduler);\n\n... do something\n\n// this is how to schedule a task on the *same* thread.\n// a moral equivalent of BeginInvoke in UI-oriented scenarios like Winforms of WPF but w/o any dependencies on those frameworks)\nTask.Factory.StartNew(() =&gt;\n{\n ... do something that will run on the scheduler's thread\n\n}, CancellationToken.None, TaskCreationOptions.DenyChildAttach, scheduler.ExclusiveScheduler);\n\n... do something\n\n// this is how to request the thread to stop\nstop.Cancel();\n\n// the one-thread code\nstatic async void MyAction(object state)\n{\n var stop = (CancellationToken)state;\n\n // do something useful. all this could be in a loop, while, etc. ....\n\n // sometimes, regularly, check for the stop and quit if requested\n if (stop.IsCancellationRequested)\n return; // end of thread is here\n\n // do something useful ....\n\n // sometimes, regularly, let other scheduled tasks run.\n // they will run on *this* thread\n await Task.Yield();\n\n // do something useful, loop, etc. ....\n // end of thread is not here!\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-04T10:36:00.153", "Id": "403728", "Score": "0", "body": "You have presented an alternative solution, but haven't reviewed the code. Please [edit] to show what aspects of the question code prompted you to write this version, and in what ways it's an improvement over the original. It may be worth (re-)reading [answer]." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-04T11:20:19.650", "Id": "403740", "Score": "2", "body": "@TobySpeight - I have nothing to edit. The question is useful to many, and my answer is at least useful to me (and it seems at least one upvoter). There's no equivalent to this question on stackoverflow, to my knowledge, otherwise I'd have posted there. Also note two other answers for this are not code reviews at all." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-02T13:21:37.843", "Id": "516129", "Score": "0", "body": "Couldn't get this to run tasks on a dedicated single thread. It seems they are run on different threads. Would you share an example?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-04T09:39:59.603", "Id": "208991", "ParentId": "43000", "Score": "2" } }, { "body": "<p>Not a review, but there is a working solution with a custom TaskScheduler which seems a bit simplier: <a href=\"https://stackoverflow.com/a/30726903/2007631\">https://stackoverflow.com/a/30726903/2007631</a></p>\n<p>And here is a working example: <a href=\"https://dotnetfiddle.net/4qCiMH\" rel=\"nofollow noreferrer\">https://dotnetfiddle.net/4qCiMH</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-02T13:42:44.967", "Id": "261545", "ParentId": "43000", "Score": "0" } } ]
{ "AcceptedAnswerId": "43957", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T01:13:08.547", "Id": "43000", "Score": "22", "Tags": [ "c#", "multithreading", "thread-safety", "task-parallel-library" ], "Title": "A TaskScheduler that always run tasks in a specific thread" }
43000
<p>I build phone apps and I use JSON a lot in my APIs. The problem is sometimes I don't know how to format the JSON data.</p> <p>For example, an iOS <code>UITableView</code> takes <code>NSArray</code> as datasource.</p> <pre><code>{ "contact_id": [ "455", "464" ], "contact_name": [ "Administrator", "Main contact" ] } </code></pre> <p>For me it makes sense since I don't have to loop through anything, but I was told it is not safe to rely on the indices matching the position.</p> <p>I remember, while asking questions, people bringing to my attention to be careful not to separate records into different arrays, and instead I should return array of objects:</p> <pre><code>[ { "contact_id": "455", "contact_name": "Administrator" }, { "contact_id": "464", "contact_name": "Main contact" } ] </code></pre> <p>I would like to know the best practice to formatting JSON.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T03:12:52.187", "Id": "74179", "Score": "0", "body": "While I prefer the second approach, I don't know what is \"unsafe\" about the first. One reason to advise against the first is that you have to remember if you ever modify one you have to modify the other as well." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T03:14:58.397", "Id": "74180", "Score": "1", "body": "do you manipulate data on your server or the client application" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T03:23:16.293", "Id": "74183", "Score": "1", "body": "Well the first one seems to rely on some particular parsing. The second one is a common structure among what I can see most of the time. I have a question is conact_id and contact_name suppose to be an object or not ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-02T13:28:49.977", "Id": "98120", "Score": "1", "body": "This question appears to be off-topic because it is about data formatting, not coding." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-02T13:55:27.083", "Id": "98130", "Score": "0", "body": "This question appears to be off-topic because it is asking what the best practices are regarding X. Please see our [help/on-topic] for more information." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-07T06:58:51.293", "Id": "99101", "Score": "0", "body": "assuming objective-c as language and removed best-practice in accordance to [tag burnination](http://meta.codereview.stackexchange.com/a/2048/37660)" } ]
[ { "body": "<p>Keep related data together.</p>\n\n<ul>\n<li>Does your application need a list of contacts? Keep each contact intact with the second approach. Merging data to create and pass a single contact takes work and is error-prone. </li>\n<li>Does it need a list of contact IDs? Do the same or return just that list. With the latter approach you can easily produce a limited array. Going the other way is much harder (more code).</li>\n<li>Does it need a list of contact names in a drop-down that loads the full contact for one ID? Use the latter since you get everything up-front. </li>\n</ul>\n\n<p>The short answer is Keep related data together because it's generally easier to pull it apart than merge it back together. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T04:18:43.380", "Id": "43013", "ParentId": "43004", "Score": "4" } }, { "body": "<h1>Yes, it is not safe to rely on indices.</h1>\n<p>In your first example you completely rely on that the indices of <code>contact_id</code> and <code>contact_name</code> matches.</p>\n<p>So say you would extract the <code>contact_id</code> and <code>contact_name</code> for a single index to get the user like this:</p>\n<pre><code>var User = { &quot;Id&quot;: contact_id[0], &quot;Name&quot;: contact_name[0] }; \nLog.print(User);\n&gt;&gt; 455 Administrator\n</code></pre>\n<p>This may be fine and dandy for now, but imagine what will happen when an element is introduced in the wrong index? Say a new developer comes along and decides to insert a new user but s/he is not too careful about where he's introducing or he misinterprets how the JSON should be formatted it and the result is a JSON looking like</p>\n<pre><code>{\n &quot;contact_id&quot;: [\n &quot;455&quot;,\n &quot;456&quot;,\n &quot;464&quot;\n ],\n &quot;contact_name&quot;: [\n &quot;Administrator&quot;,\n &quot;Main contact&quot;,\n &quot;Sub Contact&quot;\n ]\n}\n</code></pre>\n<p>Here the new developer thought that the <code>contact_id</code> might just be ordered descendingly , and that <code>contact_name</code> should also be ordered descendingly but by its roles (because, once again, s/he misinterprets <code>contact_name</code> to be a list of roles even though the array is named <code>contact_name</code>).</p>\n<p>As such he has introduced the new user's id at index 1 and the new user's name at index 2 and suddenly you are left debugging why all of your user's name, id, etc is wrong.</p>\n<h2>So why is it wrong?</h2>\n<p>Because you should never trust that either yourself in the future, or someone else will adhere to your arbitrary rules that any given index over all of your arrays are associated.</p>\n<p>This is also the reason for why you should not match e.g a role permission on indices solely. Say you got an ordered list of roles</p>\n<pre><code>var roles = [\n &quot;Admin&quot;,\n &quot;LocalAdmin&quot;,\n &quot;ContentManager&quot;,\n &quot;User&quot;\n];\n</code></pre>\n<p>And in your permission script you check for <code>user.role == roles[0]</code>, and sometimes in the future - who is unaware that the permission check that you wrote works like that - decides to add a new user <code>&quot;SuperAdmin&quot;</code>, creating the following JSON</p>\n<pre><code>var roles = [\n &quot;SuperAdmin&quot;,\n &quot;Admin&quot;,\n &quot;LocalAdmin&quot;,\n &quot;ContentManager&quot;,\n &quot;User&quot;\n];\n</code></pre>\n<p>By the logic of matches by indices <code>user.role == roles[0]</code>, every admin has now become an SuperAdmin even though they shouldn't.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-12T21:48:25.667", "Id": "82347", "Score": "0", "body": "sorry for the delay, this is the answer that I was looking for." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T16:02:01.690", "Id": "43073", "ParentId": "43004", "Score": "3" } }, { "body": "<p>The second approach is the best way to go here. </p>\n\n<p>That's because if you think about it, your app needs data that is \"A list of contacts\". If my OOP concepts aren't rusty, contacts would equate to an object. That would be like <code>new Contact()</code>. A list would equate to an array. Therefore, you need an array of these contact objects. In C#, it would equate to <code>new List&lt;Contact&gt;()</code> - a list of contacts.</p>\n\n<p>Also, since you already know that the data is a list of contacts, the <code>contact_</code> is unnecessary.</p>\n\n<pre><code>[\n {\n \"id\": \"455\",\n \"name\": \"Administrator\"\n },\n {\n \"id\": \"464\",\n \"name\": \"Main contact\"\n }\n]\n</code></pre>\n\n<p>Another issue with the first approach you have is when you loop through the data, <em>whose length</em> are you going to use as basis? For instance you chose <code>contact_id</code> as basis:</p>\n\n<pre><code>var data = {...}\nfor(var i = 0; i &lt; data.contact_id.length;i++){...}\n</code></pre>\n\n<p>Now what if you decided to change <code>contact_id</code> to just <code>id</code>. You'd have to scavenge your code and replace <code>data.contact_id.length</code> to <code>data.id.length</code>. Or what if <code>contact_id</code> was taken out entirely? You'd break the loop. Whereas you had an array in the first place:</p>\n\n<pre><code>var data = [];\nfor(var i = 0; i &lt; data.length;i++){...}\n</code></pre>\n\n<p>Even if you took out or renamed object properties, that would not break the loop you will be using. Your loop is only concerned with the array. The objects will be handled by the code <em>in the loop</em> and not the loop itself. Saves you 5 mins debugging.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T18:24:36.967", "Id": "43083", "ParentId": "43004", "Score": "2" } }, { "body": "<p>Remember what JSON stands for, specifically the ON component. Object Notation. It's supposed to describe an object. The object being a contact, the ID and name of the Contact are elements of the same object.</p>\n\n<p>As an iOS developer, I would build a data model to represent the data returned from a JSON API, so I would seed it with the dictionary that is returned from each entry in the array of JSON objects.</p>\n\n<pre><code>[ { \n \"id\": 1,\n \"name\": \"Administrator\"\n },\n {\n \"id\": 2,\n \"name\": \"User\"\n }\n]\n</code></pre>\n\n<p>So if that is the content of the NSArray, you seed that like:</p>\n\n<pre><code>NSMutableArray* contacts = [NSMutableArray new];\n\nfor (NSDictionary* element in dataArray)\n{\n Contact* contact = [Contact contactWithDictionary:element];\n [contacts addObject:contact];\n}\n</code></pre>\n\n<p>Consumers of APIs should really always be building data models on the data that is returned from the API. That's my opinion.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T18:50:35.600", "Id": "43086", "ParentId": "43004", "Score": "2" } } ]
{ "AcceptedAnswerId": "43073", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T02:53:14.710", "Id": "43004", "Score": "4", "Tags": [ "objective-c", "json" ], "Title": "Array of Objects or Array of arrays?" }
43004
<p>I was asked this interview question recently. I was able to come up with this which runs in <span class="math-container">\$O(k \log n)\$</span>.</p> <blockquote> <p>Given k &lt;= n sorted arrays each of size n, there exists a data structure requiring <span class="math-container">\$O(kn)\$</span> preprocessing time and memory that answers iterated search queries in <span class="math-container">\$O(k + \log n)\$</span> time.</p> </blockquote> <p>I have k sorted <code>List</code>s, each of size <span class="math-container">\$n\$</span>. I currently have hard-coded 5 sorted <code>List</code>s each of size 3, but in general that can be a very high number.</p> <p>I would like to search for a single element in each of the <span class="math-container">\$k\$</span> <code>List</code>s. Obviously, I can binary search each array individually, which will result in <span class="math-container">\$O(k \log n)\$</span> where <span class="math-container">\$k\$</span> is number of sorted arrays.</p> <p>Can I do it in <span class="math-container">\$O(k + \log n)\$</span> where <span class="math-container">\$k\$</span> is the number of sorted arrays? I think there might be some better way of doing it as we're doing the same searches <span class="math-container">\$k\$</span> times as of now.</p> <pre><code>private List&lt;List&lt;Integer&gt;&gt; dataInput; public SearchItem(final List&lt;List&lt;Integer&gt;&gt; inputs) { dataInput = new ArrayList&lt;List&lt;Integer&gt;&gt;(); for (List&lt;Integer&gt; input : inputs) { dataInput.add(new ArrayList&lt;Integer&gt;(input)); } } public List&lt;Integer&gt; getItem(final Integer x) { List&lt;Integer&gt; outputs = new ArrayList&lt;Integer&gt;(); for (List&lt;Integer&gt; data : dataInput) { int i = Collections.binarySearch(data, x); // binary searching the item if (i &lt; 0) i = -(i + 1); outputs.add(i == data.size() ? null : data.get(i)); } return outputs; } public static void main(String[] args) { List&lt;List&lt;Integer&gt;&gt; lists = new ArrayList&lt;List&lt;Integer&gt;&gt;(); List&lt;Integer&gt; list1 = new ArrayList&lt;Integer&gt;(Arrays.asList(3, 4, 6)); List&lt;Integer&gt; list2 = new ArrayList&lt;Integer&gt;(Arrays.asList(1, 2, 3)); List&lt;Integer&gt; list3 = new ArrayList&lt;Integer&gt;(Arrays.asList(2, 3, 6)); List&lt;Integer&gt; list4 = new ArrayList&lt;Integer&gt;(Arrays.asList(1, 2, 3)); List&lt;Integer&gt; list5 = new ArrayList&lt;Integer&gt;(Arrays.asList(4, 8, 13)); lists.add(list1); lists.add(list2); lists.add(list3); lists.add(list4); lists.add(list5); SearchItem search = new SearchItem(lists); System.out.println(dataInput); List&lt;Integer&gt; dataOuput = search.getItem(5); System.out.println(dataOuput); } </code></pre> <p>Whatever output I am seeing with my above code approach should come with the new approach as well which should work in <span class="math-container">\$O(k + \log n)\$</span>. Is this possible to achieve? Can anyone provide an example of how this would work based on my example?</p>
[]
[ { "body": "<p><span class=\"math-container\">\\$O(k + \\log n)\\$</span> seems highly suspect to me. For large values of <span class=\"math-container\">\\$n\\$</span> this is equivalent to <span class=\"math-container\">\\$O(\\log n)\\$</span> while for small values it's equivalent to <span class=\"math-container\">\\$O(k)\\$</span>. That they specified <span class=\"math-container\">\\$O(kn)\\$</span> up-front processing leads me to consider the use of a hash table, but I don't see a structure that would provide the \"closest-neighbor\" capability required by the problem statement.</p>\n\n<p>Obviously, this doesn't answer your \"How can I do this?\" question, but I question that it's even possible given their requirements, assuming you captured them accurately.</p>\n\n<p>At this point, someone will likely provide a perfectly valid solution to blow my mind. :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T04:46:00.113", "Id": "74211", "Score": "1", "body": "Brace your head ... it can be done..." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2014-02-28T03:47:02.593", "Id": "43008", "ParentId": "43006", "Score": "2" } }, { "body": "<p>This is sooo off-topic for CR... but, since it is related to a previous answer, and since I want to see a blown mind ....:</p>\n\n<p>consider the following code:</p>\n\n<pre><code>class Value&lt;T&gt; {\n private final T value;\n private final int[] arraypointers;\n private final int arraycursor = 0;\n\n Value(T value, int maxindex) {\n this.value = value;\n this.arraypointers = new int[maxindex];\n }\n\n public void addIndex(int pointer) {\n arraypointers[arraycursor++] = pointer;\n }\n\n ... some other stuff.\n}\n</code></pre>\n\n<p>OK, the above class will be used as follows... consider the example data system, the value <code>4</code> appears in <code>list1</code> and <code>list5</code>.</p>\n\n<p>This would be stored as:</p>\n\n<pre><code>Value v = new Value(4, k);\nv.addIndex(1);\nv.addIndex(5);\n</code></pre>\n\n<p>Now, start with a <code>LinkedList</code>:</p>\n\n<pre><code>LinkedList&lt;Value&lt;Integer&gt;&gt; values = new LinkedList&lt;&gt;();\n</code></pre>\n\n<p>Then, iterator though each of your loops, and merge the values in to the linked list:</p>\n\n<pre><code>for (int datapointer = 0; datapointer &lt; datalists.size(); datapointer++) {\n ListIterator&lt;Value&lt;Integer&gt;&gt; valit : values.listIterator();\n List&lt;Integer&gt; = datalists.get(datapointer);\n for (Integer addval : data) {\n boolean found = false;\n while (valit.hasNext()) {\n if (addval.compareTo(valit.next().value) &gt;= 0) {\n found = true;\n Value&lt;Integer&gt; val = valit.previous();\n if (val.value.equals(addval) {\n // update existing value\n val.addIndex(datapointer);\n // leave the iterator point backwards to \n // allow for dup values in the data.\n } else {\n // add a new value\n Value&lt;Integer&gt; val = new Value(addval, k);\n val.addIndex(datapointer);\n valit.add(val);\n // leave the iterator pointing backwards.\n // but need to move it back one.\n valit.previous();\n }\n }\n }\n if (!found) {\n Value&lt;Integer&gt; val = new Value(addval, k);\n val.addIndex(datapointer);\n valit.add(val);\n valit.previous();\n }\n\n }\n}\n</code></pre>\n\n<p>then, convert the <code>LinkedList</code> in to an <code>ArrayList</code></p>\n\n<pre><code>List sortedvalues = new ArrayList&lt;Value&lt;Integer&gt;&gt;(values);\n</code></pre>\n\n<p>Right, here we now have a sorted list of <code>Values&lt;Integer&gt;</code>. Each Value has pointers back to the list(s) they came from.</p>\n\n<p>The space complexity for this is <span class=\"math-container\">\\$O(kn)\\$</span> and we got there by doing a complexity <span class=\"math-container\">\\$O(kn)\\$</span> nested loop (the inside while loop does not count because it is on an iterator that is outside the for loop, and it is part of the same complexity as the inner for loop)...</p>\n\n<p>OK, so that is the <span class=\"math-container\">\\$O(kn)\\$</span> preprocessing.</p>\n\n<p>The lookup is a case of doing a binary search on the ArrayList (<span class=\"math-container\">\\$O(\\log n)\\$</span>) and then iterating over the index pointers (<span class=\"math-container\">\\$O(k)\\$</span>).</p>\n\n<p>Thus, the search is <span class=\"math-container\">\\$O(k + log n)\\$</span>.</p>\n\n<p>Voila!</p>\n\n<hr>\n\n<h2>Working solution</h2>\n\n<p>Right, putting all the pieces together in a working solution:</p>\n\n<p><strong>Value.java</strong></p>\n\n<pre><code>import java.util.Arrays;\n\nclass Value&lt;T extends Comparable&lt;T&gt;&gt; implements Comparable&lt;Value&lt;T&gt;&gt; {\n\n private final T value;\n\n private final T[] indices;\n\n public Value(T value, T[] data) {\n super();\n this.value = value;\n this.indices = data;\n }\n\n\n public void setIndex(int index, T val) {\n if (indices[index] == null) {\n indices[index] = val;\n }\n }\n\n public T[] getIndices() {\n return Arrays.copyOf(indices, indices.length);\n }\n\n public int compareToValue(T o) {\n return value.compareTo(o);\n }\n\n @Override\n public int compareTo(Value&lt;T&gt; o) {\n return value.compareTo(o.value);\n }\n\n @Override\n public int hashCode() {\n return value.hashCode();\n }\n\n @Override\n public boolean equals(Object obj) {\n return obj instanceof Value &amp;&amp; value.equals(((Value&lt;?&gt;)obj).value);\n }\n\n @Override\n public String toString() {\n return String.format(\"%s -&gt; %s\", value, Arrays.toString(indices));\n }\n}\n</code></pre>\n\n<p><strong>MultiListIndex.java</strong></p>\n\n<pre><code>package listsearch;\n\nimport java.lang.reflect.Array;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.Iterator;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.ListIterator;\n\npublic class MultiListIndex&lt;T extends Comparable&lt;T&gt;&gt; {\n\n private final List&lt;Value&lt;T&gt;&gt; index;\n private final Class&lt;T&gt; clazz;\n private final int width;\n\n public MultiListIndex(Class&lt;T&gt; clazz, Collection&lt;List&lt;T&gt;&gt; data) {\n this.clazz = clazz;\n this.width = data.size();\n this.index = preprocess(new ArrayList&lt;&gt;(data));\n }\n\n private final List&lt;Value&lt;T&gt;&gt; preprocess(List&lt;List&lt;T&gt;&gt; data) {\n LinkedList&lt;Value&lt;T&gt;&gt; processed = new LinkedList&lt;&gt;();\n Value&lt;T&gt; target = null;\n for (int listid = 0; listid &lt; data.size(); listid++) {\n ListIterator&lt;Value&lt;T&gt;&gt; valit = processed.listIterator();\n Iterator&lt;T&gt; datait = data.get(listid).iterator();\n while (datait.hasNext()) {\n final T toadd = datait.next();\n boolean found = false;\n while (valit.hasNext()) {\n final int compare = (target = valit.next()).compareToValue(toadd);\n if (compare &gt;= 0) {\n // we have a match, or gone past.\n valit.previous();\n found = true;\n if (compare == 0) {\n target.setIndex(listid, toadd);\n } else {\n Value&lt;T&gt; newtarget = new Value&lt;&gt;(toadd, Arrays.copyOf(target.getIndices(), width));\n valit.add(newtarget);\n newtarget.setIndex(listid, toadd);\n if (newtarget != valit.previous()) {\n throw new IllegalStateException(\"Bad math!\");\n }\n }\n break;\n }\n target.setIndex(listid, toadd);\n }\n if (!found) {\n Value&lt;T&gt; newtarget = new Value&lt;&gt;(toadd, buildArray(clazz, width));\n valit.add(newtarget);\n newtarget.setIndex(listid, toadd);\n }\n }\n }\n return new ArrayList&lt;&gt;(processed);\n }\n\n\n @SuppressWarnings(\"unchecked\")\n private static final &lt;T&gt; T[] buildArray(Class&lt;T&gt; clazz, int size) {\n return (T[])Array.newInstance(clazz, size);\n }\n\n public List&lt;T&gt; searchValues(T value) {\n Value&lt;T&gt; key = new Value&lt;&gt;(value, null);\n int pos = Collections.binarySearch(index, key);\n if (pos &lt; 0) {\n pos = -pos - 1;\n }\n if (pos &gt;= index.size()) {\n return Arrays.asList(buildArray(clazz, width));\n }\n return Arrays.asList(Arrays.copyOf(index.get(pos).getIndices(), width));\n }\n\n\n}\n</code></pre>\n\n<p><strong>MultiListMain.java</strong></p>\n\n<pre><code>package listsearch;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class MultiListMain {\n\n public static void main(String[] args) {\n List&lt;List&lt;Integer&gt;&gt; lists = new ArrayList&lt;List&lt;Integer&gt;&gt;();\n\n List&lt;Integer&gt; list1 = new ArrayList&lt;Integer&gt;(Arrays.asList(3, 4, 6));\n List&lt;Integer&gt; list2 = new ArrayList&lt;Integer&gt;(Arrays.asList(1, 2, 3));\n List&lt;Integer&gt; list3 = new ArrayList&lt;Integer&gt;(Arrays.asList(2, 3, 6));\n List&lt;Integer&gt; list4 = new ArrayList&lt;Integer&gt;(Arrays.asList(1, 2, 3));\n List&lt;Integer&gt; list5 = new ArrayList&lt;Integer&gt;(Arrays.asList(4, 8, 13));\n\n lists.add(list1);\n lists.add(list2);\n lists.add(list3);\n lists.add(list4);\n lists.add(list5);\n\n MultiListIndex&lt;Integer&gt; search = new MultiListIndex&lt;Integer&gt;(\n Integer.class, lists);\n // System.out.println(dataInput);\n\n System.out.println(search.searchValues(0));\n System.out.println(search.searchValues(1));\n System.out.println(search.searchValues(2));\n System.out.println(search.searchValues(5));\n\n }\n\n}\n</code></pre>\n\n<p><strong>Output</strong></p>\n\n<blockquote>\n<pre><code>[3, 1, 2, 1, 4]\n[3, 1, 2, 1, 4]\n[3, 2, 2, 2, 4]\n[6, null, 6, null, 8]\n</code></pre>\n</blockquote>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T05:19:57.597", "Id": "74217", "Score": "0", "body": "Appreciated your help.. I am trying to plugin your suggestion in my example as I have in my question but how do I plugin this in my example? Any thoughts?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T05:21:30.190", "Id": "74218", "Score": "0", "body": "It's a tough one ... the code is really just there to guide you. The way you implement it is all yours though... There may be other ways to do it too, though." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T00:40:37.713", "Id": "74378", "Score": "0", "body": "LOL, I totally forgot the problem allowed the *O(kn)* setup. Yes, bravo!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T00:45:17.800", "Id": "74379", "Score": "0", "body": "@DavidHarkness - complexity is, well, complicated, but, I think my solution is actually O(kn) for the preprocess, and only O( log n ) for the search.... if you count array-copy, etc. as O(1) ... which it sort of is..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T00:58:59.717", "Id": "74382", "Score": "0", "body": "Yeah, I couldn't tell if the processed list contains *O(k)* or *O(n)* elements. If the latter and you're copying a list of *k* elements, the search is indeed *O(k + log n)* as required." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-10T05:45:57.297", "Id": "420086", "Score": "0", "body": "(In the introduction, `data` is missing from `List<Integer> = datalists.get(datapointer)`.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-10T07:09:23.120", "Id": "420090", "Score": "0", "body": "[Chapter 4 on Fractional Cascading](http://cglab.ca/~morin/teaching/5408/notes/fractional_cascading.pdf) seems to agree that preprocess() uses O(k²n) space - to go on and show how to reduce to O(kn)." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2014-02-28T04:45:40.877", "Id": "43014", "ParentId": "43006", "Score": "4" } }, { "body": "<p>Here is what I came across that could be a solution. </p>\n\n<p>O(k*n) for preproccessing means that you touch every element in every array. <strong>I will assume</strong> that the arrays do not overlap in stored values (it is not stated in the example). If you touch all the elements of all the arrays you can create intervals for every array and that can be done in O(k*n). The intrvals can be kept in a list of touples.</p>\n\n<p>After you have these <strong>k</strong> intervals you could sort them in O(k*log(k)). If <strong>k</strong> is about the same as <strong>n</strong> then O(k*n + k*logk) = O(n*n + n*logn) = O(n^2). The nlogn can be omitted in <strong>assymptotic</strong> math because <strong>assymptotically</strong> is smaller. If <strong>k</strong> is small then you would get using the same math to O(k*n) (k*logk is definitely asymptotically smaller so it can be omitted). So using these arguments you can say it was done in O(k*n) time. </p>\n\n<p>When searching you can get O(logk + logn). logk is to find the right interval using binary search and logn searching the array itself.</p>\n\n<p>If you dont use the sorting of interval then you need to search the intervals in O(k) time and then the array itself O(logn) = O(k + logn). If my reasoning is correct and I did not omit any important limitation you should have your answer for O(k + logn), or even faster O(logk + logn) ;) </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T12:10:12.427", "Id": "43132", "ParentId": "43006", "Score": "1" } } ]
{ "AcceptedAnswerId": "43014", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2014-02-28T03:23:48.890", "Id": "43006", "Score": "9", "Tags": [ "java", "algorithm", "interview-questions", "search" ], "Title": "Extracting elements from multiple sorted lists efficiently" }
43006
<p>I'm working on extending the functionality of a photo gallery by adding a thumbnail display, I have multiple if statements set up to adjust the position of the thumbnails. Obviously this is not ideal, I'm trying to put my head around how to use a for loop to iterate the width multiplier and curSlide position.</p> <p>Ideally I would like the curSlide to increment after every 5 slide and the thumbGalwidth*i to increment as well.</p> <pre><code>var thumbGalwidth = 795; if(currSlide &lt; 6) { jQuery('#view-all-container').css('margin-left', '-' + thumbGalwidth*0 + 'px'); } if(currSlide &gt;= 6) { jQuery('#view-all-container').css('margin-left', '-' + thumbGalwidth*1 + 'px'); } if (currSlide &gt;= 11) { jQuery('#view-all-container').css('margin-left', '-' + thumbGalwidth*2 + 'px'); } if (currSlide &gt;= 16) { jQuery('#view-all-container').css('margin-left', '-' + thumbGalwidth*3 + 'px'); } if (currSlide &gt;= 21) { jQuery('#view-all-container').css('margin-left', '-' + thumbGalwidth*4 + 'px'); } if (currSlide &gt;= 26) { jQuery('#view-all-container').css('margin-left', '-' + thumbGalwidth*5 + 'px'); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T03:51:14.567", "Id": "74192", "Score": "0", "body": "How does `curSlide` change over time in this code? It looks quite fixed, and I suspect you omitted the looping code calling this function. Please provide enough context to advise you intelligently." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T03:56:59.950", "Id": "74195", "Score": "0", "body": "Be wary with accepting answers so quickly. It could discourage future reviews from being written." } ]
[ { "body": "<p>Because you have nice, predictable ranges, you don't need a loop at all. Just do a little math.</p>\n\n<pre><code>var thumbGalwidth = 795;\n\nvar n = Math.floor(((currSlide || 1)-1) / 5);\n\njQuery('#view-all-container').css('margin-left', '-' + thumbGalwidth*n + 'px');\n</code></pre>\n\n<hr>\n\n<p>If the largest <code>n</code> should be <code>5</code>, then change the assignment to this:</p>\n\n<pre><code>var n = Math.min(5, Math.floor(((currSlide || 1)-1) / 5));\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T03:48:13.397", "Id": "43009", "ParentId": "43007", "Score": "5" } } ]
{ "AcceptedAnswerId": "43009", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T03:40:13.753", "Id": "43007", "Score": "5", "Tags": [ "javascript", "jquery" ], "Title": "Repositioning images in a gallery based on the current image" }
43007
<p>I've written a function that works fine, but being new to jQuery, I'd like some reviews on writing this more cleanly. Anything advice would help; just trying to learn!</p> <pre><code>function displayContent() { var $link1 = $('.row.nav li a.bio'); var $link2 = $('.row.nav li a.stylist'); var $link3 = $('.row.nav li a.contact'); var $content = $('#text-content') var $bio = $("#bio"); var $stylist = $("#stylist"); var $contact = $("#contact"); var $overlay = $('.content-overlay'); //link1 $link1.click(function (e) { e.stopPropagation(); $link2.removeClass('active'); $link3.removeClass('active'); $link1.addClass('active'); $contact.hide(); $stylist.hide(); $bio.fadeIn(700); $overlay.show(); }); //link2 $link2.click(function (e) { //same code here }); //link3 $link3.click(function (e) { //same code here }); //close overlay/hide content $('html').click(function (e) { //hide code }); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T04:06:06.680", "Id": "74196", "Score": "0", "body": "When you say `// same code here` does that mean that both of those handlers are identical?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T04:11:01.490", "Id": "74200", "Score": "0", "body": "Same code as the $link1, except now the 'active' is being applied to $link2, etc" } ]
[ { "body": "<p>Using <code>$(this)</code> is very helpful in situations where you have similar/same code. The way it works, is if say you have a class <code>.general</code> , which 50 different div's on the page all have that class. But lets say, if a user clicks on any one of those 50 div's , you want ONLY that div that was clicked on to have a border of 5px solid red. So instead of writing </p>\n\n<pre><code>$('.general').click(function() {\n $('.general').css({border: '5px solid red'});\n}); \n</code></pre>\n\n<p>which would give all 50 div's a border, you can write this</p>\n\n<pre><code>$('.general').click(function() {\n $(this).css({border: '5px solid red'});\n}); \n</code></pre>\n\n<p>and now only the div that was clicked on will have the border. Also, it will work more than once, so if you then clicked on 10 other div's with class general, they would all get the border red as well.</p>\n\n<hr>\n\n<p>This can be applied to your code like so : <em>(only included the relevant info)</em></p>\n\n<pre><code>function displayContent() {\n\n var $links = $('.row.nav li a.bio, .row.nav li a.stylist, .row.nav li a.contact');\n\n}\n\n $links.click(function (e) { // so you just need one click function instead of 3\n e.stopPropagation();\n $links.removeClass('active'); // removes the class active from all $links\n $(this).addClass('active'); // gives the class active to the one clicked on\n\n });\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T04:25:08.360", "Id": "74208", "Score": "1", "body": "Thanks for the explanation @LowerClassOverflowian! Much appreciated!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T04:10:46.333", "Id": "43011", "ParentId": "43010", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T04:00:03.897", "Id": "43010", "Score": "7", "Tags": [ "javascript", "jquery", "beginner" ], "Title": "Removeclass addclass multiple selectors optimization" }
43010
<p>I am using Netty embedded within Grails to process and display incoming SNMP messages. Since Netty 4 doesn't come with a built-in <code>ChannelExecutionHandler</code> I had to make my own and would like some feedback on it.</p> <pre><code>package org.ciscotalk.common.netty; import io.netty.buffer.ByteBuf; import io.netty.channel.*; import io.netty.channel.socket.DatagramPacket; import lombok.Getter; import lombok.Setter; import org.ciscotalk.common.netty.exec.ChannelDecoderEvent; import org.ciscotalk.common.snmp.SnmpMessage; import org.ciscotalk.snmp.SnmpService; import org.springframework.beans.factory.annotation.Autowired; import java.util.concurrent.*; /** * @author Diljot */ @ChannelHandler.Sharable public class ChannelExecutionHandler extends CombinedChannelDuplexHandler&lt;ChannelExecutionHandler.ChannelInboundExecutionHandler, ChannelExecutionHandler.ChannelOutboundExecutionHandler&gt; { @Autowired @Getter @Setter private SnmpService snmpService; private final ExecutorService executor = Executors.newCachedThreadPool(); private final BlockingDeque&lt;ByteBuf&gt; incoming = new LinkedBlockingDeque&lt;&gt;(); //TODO private static final BlockingDeque&lt;?&gt; outgoing = new LinkedBlockingDeque&lt;&gt;(); private final BlockingDeque&lt;Future&lt;?&gt;&gt; futures = new LinkedBlockingDeque&lt;&gt;(); public ChannelExecutionHandler() { init(new ChannelInboundExecutionHandler(), new ChannelOutboundExecutionHandler()); Executors.newSingleThreadExecutor().execute(producer); Executors.newSingleThreadExecutor().execute(consumer); } public final Runnable producer = new Runnable() { @Override public void run() { try { ChannelDecoderEvent&lt;?&gt; ev = nextEvent(incoming.take()); if (ev != null) { Future&lt;?&gt; f = executor.submit((Runnable) ev, ev); futures.put(f); } } catch (InterruptedException e) { e.printStackTrace(); } } }; public final Runnable consumer = new Runnable() { @Override public void run() { try { Future&lt;?&gt; f = futures.take(); if (f != null) { Object o = f.get(); snmpService.pushToQueue((SnmpMessage) o); } } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } } }; private &lt;T extends SnmpMessage&gt; ChannelDecoderEvent&lt;T&gt; nextEvent(ByteBuf buf) { return new ChannelDecoderEvent&lt;&gt;(buf); } public final class ChannelInboundExecutionHandler extends ChannelInboundHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf buf = ((DatagramPacket) msg).content(); buf.retain(); incoming.put(buf); } } public final class ChannelOutboundExecutionHandler extends ChannelOutboundHandlerAdapter { @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { ctx.write(msg, promise); } } } </code></pre> <hr> <pre><code>package org.ciscotalk.snmp import grails.transaction.Transactional import org.ciscotalk.common.snmp.SnmpMessage @Transactional class SnmpService&lt;T extends SnmpMessage&gt; { Queue&lt;T&gt; incoming = new LinkedList&lt;&gt;() def pushToQueue(T obj) { incoming.add(obj) } } </code></pre> <hr> <pre><code>package org.ciscotalk.common.snmp; /** * @author Diljot */ public interface SnmpMessage { } </code></pre> <hr> <pre><code>package org.ciscotalk.common.netty.exec; import io.netty.buffer.ByteBuf; import org.ciscotalk.common.snmp.SnmpMessage; import java.util.concurrent.Callable; /** * @author Diljot */ public class ChannelDecoderEvent&lt;T extends SnmpMessage&gt; implements Callable&lt;T&gt; { private final ByteBuf buf; public ChannelDecoderEvent(ByteBuf buf) { this.buf = buf; } @Override public T call() throws Exception { // handle decoding then return encoded SnmpMessage&lt;T&gt; return null; } } </code></pre> <p>The intended flow is:</p> <ol> <li><code>ChannelInboundExecutionHandler</code> receives incoming <code>UDP packet</code>, stores it as a <code>ByteBuf</code> in the <code>incoming queue</code>.</li> <li>The <code>producer</code> thread picks up the <code>ByteBuf</code> and decodes/processes the packet by submitting a <code>ChannelDecoderEvent</code></li> <li>The future is stored in the <code>futures</code> queue</li> <li>The <code>consumer</code> thread picks up the <code>Future&lt;?&gt;</code> and proceeds to invoke the <code>get()</code> function.</li> <li>Upon successful recovery it passes the processed <code>SnmpMessage&lt;T&gt;</code> to the Grails <code>SnmpService</code> which handles persisting the data and displaying it in the Grails webapp. (This hasn't been implemented yet but that's the plan)</li> </ol> <p>I would like some C&amp;C if this model works out, or if I should handle it differently.</p>
[]
[ { "body": "<p>So your code/concept looks functional to me. There are some comments though... and they are a bit scattered, forgive me....</p>\n\n<h2>Threads</h2>\n\n<p>You use the <code>Executors</code> class to create three ExecutorServices. Each of these services create threads that <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Executors.html#defaultThreadFactory%28%29\">are non-daemon threads</a>...</p>\n\n<p>This is a problem because you will need to manually shut down all threads before you can exit your program correctly.</p>\n\n<p>Using the default ThreadFactory is also a problem because the threads have horrible names. It is very convenient to name your threads so that, if there are problems, the stack-traces and java dumps are more easy to interpret.</p>\n\n<p>creating a class like:</p>\n\n<pre><code>import java.util.concurrent.ThreadFactory;\nimport java.util.concurrent.atomic.AtomicInteger;\n\n\n/**\n * Simple thread-safe ThreadFactory implementation that can be\n * customised to have a special name-base, and daemon setting.\n */\npublic class CustomizableThreadFactory implements ThreadFactory {\n\n private final AtomicInteger idgen = new AtomicInteger();\n private final String basename;\n private final boolean daemon;\n\n /**\n * Create a new ThreadFactory with the given base-name and daemon settings.\n * Each thread created from this factory will have a unique name (basename + \" - \" + id)\n * @param basename the basename to use for threads from this factory\n * @param daemon whether the threads are daemon threads, or not (see Thread.setDaemon(boolean) )\n */\n public CustomizableThreadFactory(final String basename, final boolean daemon) {\n this.basename = basename;\n this.daemon = daemon;\n }\n\n @Override\n public Thread newThread(final Runnable torun) {\n Thread thread = new Thread(torun, String.format(\"%s - %d\", basename, idgen.incrementAndGet()));\n thread.setDaemon(daemon);\n return thread;\n }\n\n}\n</code></pre>\n\n<p>You can use that class anywhere you use an ExecutorService, and the threads will be much nicer to use. Consider your constructor:</p>\n\n<blockquote>\n<pre><code>private final ExecutorService executor = Executors.newCachedThreadPool();\nprivate final BlockingDeque&lt;ByteBuf&gt; incoming = new LinkedBlockingDeque&lt;&gt;();\n//TODO private static final BlockingDeque&lt;?&gt; outgoing = new LinkedBlockingDeque&lt;&gt;();\nprivate final BlockingDeque&lt;Future&lt;?&gt;&gt; futures = new LinkedBlockingDeque&lt;&gt;();\n\npublic ChannelExecutionHandler() {\n init(new ChannelInboundExecutionHandler(), new ChannelOutboundExecutionHandler());\n Executors.newSingleThreadExecutor().execute(producer);\n Executors.newSingleThreadExecutor().execute(consumer);\n}\n</code></pre>\n</blockquote>\n\n<p>This code would be better as:</p>\n\n<pre><code>private final ExecutorService executor = Executors.newCachedThreadPool(\n new CustomizedThreadFactory(\"SNMP Decoder\" + true));\nprivate final BlockingDeque&lt;ByteBuf&gt; incoming = new LinkedBlockingDeque&lt;&gt;();\nprivate final BlockingDeque&lt;Future&lt;?&gt;&gt; futures = new LinkedBlockingDeque&lt;&gt;();\n\npublic ChannelExecutionHandler() {\n init(new ChannelInboundExecutionHandler(), new ChannelOutboundExecutionHandler());\n Executors.newSingleThreadExecutor(\n new CustomizedThreadFactory(\"SNMP Producer\", true)).execute(producer);\n Executors.newSingleThreadExecutor(\n new CustomizedThreadFactory(\"SNMP Consumer\", true)).execute(consumer);\n}\n</code></pre>\n\n<p>Alright, apart from the thread daemon status and names, the rest of the thread model looks OK.....</p>\n\n<p>You have a thread that queues the events in an ordered queue, then a bunch of threads that decode them in paralle, and a final thread that removes them in the same order as their insert order.</p>\n\n<p>From what I can tell, this is good.</p>\n\n<h2>Generics</h2>\n\n<p>You go part way to working with your generics, but then you get lazy, or there is an inconsistency in your code.</p>\n\n<p><strong>Inconsistency:</strong></p>\n\n<p>you have <code>Future&lt;?&gt; f = executor.submit((Runnable) ev, ev);</code> where <code>ev</code> is <code>ChannelDecoderEvent&lt;?&gt; ev = nextEvent(incoming.take());</code></p>\n\n<p>Now, ChannelDecoderEvent is:</p>\n\n<blockquote>\n<pre><code>public class ChannelDecoderEvent&lt;T extends SnmpMessage&gt; implements Callable&lt;T&gt; { ...\n</code></pre>\n</blockquote>\n\n<p>So, you are creating a future that will result in a ChannelDecoderEvent output <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html#submit%28java.lang.Runnable,%20T%29\">(that is what the ExecutorService.submit(...) does)</a>.</p>\n\n<p>But, when you pull values from the <code>futures</code> queue with:</p>\n\n<blockquote>\n<pre><code> Future&lt;?&gt; f = futures.take();\n if (f != null) {\n Object o = f.get();\n snmpService.pushToQueue((SnmpMessage) o);\n</code></pre>\n</blockquote>\n\n<p>you are casting the <code>o</code> value to be an <code>SnmpMessage</code>, but that <code>o</code> value is a <code>ChannelDecoderEvent</code>, and that is not an <code>SnmpMessage</code>, so you will get ClassCastException.</p>\n\n<p><strong>If you did it right</strong> ....</p>\n\n<p>Your generics should be worked correctly the whole way though.</p>\n\n<p>There is no need for <code>Future&lt;?&gt;</code>, it should be <code>Future&lt;SnmpMessage&gt;</code>, and instead of loading the executors as a <code>submit(Runnable r, T result);</code> you should be using the correct callable-nature of the <code>ChannelDecoderEvent</code>, and submitting as:</p>\n\n<pre><code>Future&lt;? extends SnmpMessage&gt; f = submit(ev);\n</code></pre>\n\n<p>Then, your future queue:</p>\n\n<blockquote>\n<pre><code>private final BlockingDeque&lt;Future&lt;?&gt;&gt; futures = new LinkedBlockingDeque&lt;&gt;();\n</code></pre>\n</blockquote>\n\n<p>should be:</p>\n\n<pre><code>private final BlockingDeque&lt;Future&lt;? extends SnmpMessage&gt;&gt; futures = new LinkedBlockingDeque&lt;&gt;();\n</code></pre>\n\n<p>Finally, your queue retrieval code becomes:</p>\n\n<pre><code> Future&lt;? extends SnmpMessage&gt; f = futures.take();\n if (f != null) {\n SNMPMessage msg = f.get();\n snmpService.pushToQueue(msg);\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-02T00:28:52.550", "Id": "74511", "Score": "0", "body": "Thank you rolfl for your review on my code, I have looked over your suggestions and agree with them all. I will be sure to implement the changes you suggested." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T16:21:01.037", "Id": "43146", "ParentId": "43015", "Score": "6" } }, { "body": "<p>+1 to <code>@rolfl</code>. Two minor notes:</p>\n\n<ol>\n<li><p>If your threads throws an exception they probably will be printed only to <code>System.out</code>. You might want to use an <code>UncaughtExceptionHandler</code> which logs them.</p></li>\n<li><p>Consider using <a href=\"http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/util/concurrent/ThreadFactoryBuilder.html\" rel=\"nofollow\"><code>ThreadFactoryBuilder</code></a> from <a href=\"https://code.google.com/p/guava-libraries/\" rel=\"nofollow\">Guava</a>, it has a great API.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-02T00:29:36.350", "Id": "74512", "Score": "0", "body": "Thanks for your comment palacsint, I'll look over the Guava API as you suggested. And this code is only part-way done that's why it's missing the error output as you suggested." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T17:28:51.597", "Id": "43154", "ParentId": "43015", "Score": "3" } } ]
{ "AcceptedAnswerId": "43146", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T04:55:09.333", "Id": "43015", "Score": "6", "Tags": [ "java", "multithreading", "networking", "concurrency" ], "Title": "Producer/Consumer implementation" }
43015
<p>The following Java code reads lines from an input text file and will output the entry that has the highest number in field-2 to an output file:</p> <p><strong>INPUT:</strong></p> <blockquote> <p>William J. Clinton 6 Q1124 <br> 42nd President of the United States 6 Q1124 <br> Bill Clinton,6,Q1124 <br> Bill Clinton,14,Q9890 <br> Bill Clinton,5,Q9880 <br> William Jefferson Clinton,6,Q1124</p> </blockquote> <p><strong>OUTPUT:</strong> <br></p> <blockquote> <p>William J. Clinton,Q1124 <br> 42nd President of the United States,Q1124 <br> Bill Clinton,Q9890 (this Q-ID selected because field-2 was highest number "14") <br> William Jefferson Clinton,Q1124</p> </blockquote> <p>Could you offer suggestions on making this more elegant?</p> <pre><code>/* * This class uses a method to combine duplicate Wiki keys into one and * selecting the Qid of the one with largest link count */ public static void main(String[] args) { if (args.length &lt; 2) { usage(); System.exit(0); } // try { // Create output file BufferedWriter out = Files.newBufferedWriter(Paths.get(args[1]), StandardCharsets.UTF_8); // read input file BufferedReader br = Files.newBufferedReader(Paths.get(args[0]), StandardCharsets.UTF_8); String key = ""; int links = 0; String qID = ""; String next, line = br.readLine(); for (boolean first = true, last = (line == null); !last; first = false, line = next) { last = ((next = br.readLine()) == null); String[] entry = line.split(","); if (first) { // only assign current values key = entry[0]; links = new Integer(entry[1]); qID = entry[2]; } else if (last) { //check if key is a duplicate if(key.equals(entry[0])){ //use the Qid from the highest links int temp = new Integer(entry[1]); if(links &lt; temp){ //write entry to output higher links out.write(key + "," + entry[2] + "\n"); }else{ //write entry to output using current out.write(key + "," + qID + "\n"); } }else{ //write last entry to output out.write(key + "," + qID + "\n"); out.write(entry[0] + "," + entry[2] + "\n"); } } else { //check if key is a duplicate if(key.equalsIgnoreCase(entry[0])){ //use the Qid from the highest links int temp = new Integer(entry[1]); if(links &lt; temp){ links = temp; qID = entry[2]; } }else{ //write entry to output out.write(key + "," + qID + "\n"); //reassign current values key = entry[0]; links = new Integer(entry[1]); qID = entry[2]; } } } // Close the output stream out.close(); } catch (Exception e) {// Catch exception if any System.err.println("Error: " + e.getMessage()); } } private static void usage() { System.err.println("Usage: CombineKeys InputFile OutputFile"); } </code></pre>
[]
[ { "body": "<p>I'm far from a Java expert, but a few things jumped out at me</p>\n\n<hr>\n\n<p>You forgot to close the reader (<code>br</code>).</p>\n\n<hr>\n\n<p>Do not close the streams inside of the try. What happens if an exception gets thrown before the close commands are reached? You need a <code>finally</code> block. Or, better yet, if you're using Java 7 or above, use a try-with-resources block.</p>\n\n<hr>\n\n<p>If you're only error handling is to just print out the message, I'd be tempted to go ahead and let the exception bubble up and kill the program. Unless you're just trying to go for a more simple error, in which case hiding the stack trace could be nice.</p>\n\n<hr>\n\n<p>I would just let <code>key</code> be <code>null</code> the first time around and check for that instead of using <code>first</code>. </p>\n\n<hr>\n\n<p>I might try to restructure the <code>for</code> conditions. They're very confusing in the current form. Perhaps loop as long as you successfully read a line, and then handle the <code>last</code> logic outside of the <code>for</code> loop. That way you don't have to have so much going on inside of the loop.</p>\n\n<hr>\n\n<p>On a minor note, you should try to create the reader before the writer. That way you don't create an output file if you can't open the input one.</p>\n\n<hr>\n\n<p>The repetition in the <code>last</code> and <code>else</code> blocks should be refactored out into a common case. Based on that they do the exact same thing, I'm not actually sure why <code>last</code> get's special treatment.</p>\n\n<hr>\n\n<p>I would use <code>Integer.parseInt</code> instead of using unboxing on <code>new Integer(str)</code>.</p>\n\n<hr>\n\n<p><code>temp</code> is a bad variable name. Name it something descriptive of what it actually is.</p>\n\n<hr>\n\n<p>Don't bother commenting really obvious things (\"Catch exception if any\" for example).</p>\n\n<hr>\n\n<p>Sometimes you use spaces like <code>if (...)</code> and sometimes you don't. Pick one and stick with it (by which I really mean always use spaces :p).</p>\n\n<hr>\n\n<p>All in all, my Java is a bit rusty, so take this with a grain of salt, but, I would do something like this:</p>\n\n<pre><code>public static void main(String[] args) {\n if (args.length &lt; 2) {\n System.err.println(\"Usage: CombineKeys InputFile OutputFile\");\n System.exit(1);\n }\n\n BufferedWriter out = null;\n BufferedReader br = null;\n\n try {\n out = Files.newBufferedWriter(Paths.get(args[1]), StandardCharsets.UTF_8);\n\n br = Files.newBufferedReader(Paths.get(args[0]), StandardCharsets.UTF_8);\n\n String key = null;\n int links = 0;\n String qID = null;\n\n while ((line = br.readLine()) != null) {\n String[] entry = line.split(\",\");\n\n if (entry[0].equalsIgnoreCase(key)) {\n int tmpLinks = Integer.parseInt(entry[1]);\n if (links &lt; tmpLinks){\n links = tmpLinks;\n qID = entry[2];\n }\n } else {\n if (key != null) {\n out.write(key + \",\" + qID + \"\\n\");\n }\n key = entry[0];\n links = Integer.parseInt(entry[1]);\n qID = entry[2];\n }\n }\n if (key != null) {\n out.write(key + \",\" + qID + \"\\n\");\n }\n } catch (Exception e) {\n System.err.println(\"Error: \" + e.getMessage());\n } finally {\n if (br != null) {\n br.close();\n }\n if (out != null) {\n out.close();\n }\n }\n}\n</code></pre>\n\n<p>I don't really like the repetition of the outputting, but I can't figure out a way around that. Also, due to the nesting level, I would probably pull the actual processing into a new method that takes in the two already opened streams.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T05:49:59.447", "Id": "43019", "ParentId": "43017", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T05:24:31.323", "Id": "43017", "Score": "5", "Tags": [ "java" ], "Title": "Read line and combine duplicate entries based on one of the fields" }
43017
<p>Header file:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;assert.h&gt; typedef struct linked_list linked_list; typedef struct cons cons; void append(cons *cons, int value); void linked_list_append(linked_list *ll, int value); int size(linked_list *ll); void insert_after(cons *c, int value, int index, int current); void linked_list_insert_after(linked_list *ll, int value, int index); void delete(cons *c, int index, int current); void linked_list_delete(linked_list *ll, int index); linked_list *new_linked_list(void); void linked_list_destroy(linked_list *ll); void destroy(cons *c); int get(cons *c, int index, int current); int linked_list_get(linked_list *ll, int index); void cons_print(cons *c); void linked_list_print(linked_list *ll); </code></pre> <p>Actual code:</p> <pre><code>#include "ll.h" struct cons { int value; cons *next; }; struct linked_list { int size; cons *list; }; linked_list *new_linked_list(void) { linked_list *ll = malloc(sizeof(linked_list)); assert(ll); ll-&gt;size = 0; ll-&gt;list = NULL; return ll; } int linked_list_get(linked_list *ll, int index) { assert(ll); assert(index &gt;= 0); assert(index &lt;= (ll-&gt;size - 1)); return get(ll-&gt;list, index, 0); } int get(cons *c, int index, int current) { if (index == current) { return c-&gt;value; } else { return get(c-&gt;next, index, ++current); } } void linked_list_append(linked_list *ll, int value) { assert(ll); (ll-&gt;size)++; if (ll-&gt;list) { append(ll-&gt;list, value); } else { cons *new = malloc(sizeof(cons)); new-&gt;value = value; new-&gt;next = NULL; ll-&gt;list = new; } } void append(cons *c, int value) { if (c-&gt;next) { append(c-&gt;next, value); } else { cons *new = malloc(sizeof(cons)); new-&gt;value = value; new-&gt;next = NULL; c-&gt;next = new; } } void linked_list_insert_after(linked_list *ll, int value, int index) { assert(ll); assert(index &gt;= 0); assert(index &lt;= (ll-&gt;size - 1)); ll-&gt;size++; insert_after(ll-&gt;list, value, index, 0); } void insert_after(cons *c, int value, int index, int current) { if (index == current) { cons *new = malloc(sizeof(cons)); new-&gt;value = value; new-&gt;next = c-&gt;next; c-&gt;next = new; } else { insert_after(c-&gt;next, value, index, ++current); } } int linked_list_size(linked_list *ll) { if (ll) { return ll-&gt;size; } else { return -1; } } void linked_list_delete(linked_list *ll, int index) { assert(ll); assert(index &gt;= 0); assert(index &lt;= (ll-&gt;size - 1)); ll-&gt;size--; delete(ll-&gt;list, index, 0); } void delete(cons *c, int index, int current) { if (index == current) { cons *temp = c; *c = *(c-&gt;next); free(temp); } else { delete(c-&gt;next, index, ++current); } } void linked_list_destroy(linked_list *ll) { if (ll) { destroy(ll-&gt;list); free(ll); } } void destroy(cons *c) { if (c) { destroy(c-&gt;next); free(c); } } void linked_list_print(linked_list *ll) { assert(ll); cons_print(ll-&gt;list); } void cons_print(cons *c) { if (c) { printf("%d ", c-&gt;value); cons_print(c-&gt;next); } else { printf("\n"); } } int main(void) { linked_list *new = new_linked_list(); linked_list_print(new); linked_list_append(new, 2); linked_list_print(new); // 2 linked_list_append(new, 3); linked_list_print(new); // 2 3 linked_list_append(new, 4); linked_list_print(new); // 2 3 4 linked_list_insert_after(new, 15, 1); linked_list_print(new); // 2 3 15 4 linked_list_delete(new, 1); linked_list_print(new); // 2 15 4 printf("get 0: %d\n", linked_list_get(new, 0)); printf("get 2: %d\n", linked_list_get(new, 2)); printf("get 1: %d\n", linked_list_get(new, 1)); linked_list_destroy(new); return 0; } </code></pre> <ol> <li><p>I'm trying to split up my code into a code file and a header file, but it doesn't feel right. I'm not actually hiding any of the implementation details from the client if they can see the helper methods. What's the correct way to do this?</p></li> <li><p>My <code>delete</code> function works, but I don't really understand it. Previously the meat of it was</p> <pre><code>if (index == current) { cons *temp = c; c = temp-&gt;next; free(temp); } </code></pre> <p>but this didn't work. Why?</p></li> <li><p>I've tried to incorporate style / memory advice I've gotten in my previous submissions <a href="https://codereview.stackexchange.com/questions/42834/int-stack-implementation">stack</a> and <a href="https://codereview.stackexchange.com/questions/42931/binary-search-tree-implementation">binary search tree</a>. I don't think there are any memory leaks, but I'd like some double checking.</p></li> </ol> <p>Any and all criticism is welcome here. </p>
[]
[ { "body": "<p>Several things that stick out to me at a glance:</p>\n\n<ul>\n<li><p>What is <code>cons</code>? Don't you mean <code>Node</code>? At first I thought it was just a short form of constructor, but it appears to be corresponding to a node.</p></li>\n<li><p>I'd strongly recommend using a different variable name other than <code>new</code>. Although this is C and not C++, this could still cause confusion, both to the reader and to the compiler (also notice the syntax-highlighting in the posted code). It'd be even more problematic if this happened to be compiled with a C++ compiler. You could just rename it to something like <code>newList</code>.</p></li>\n<li><p>You should rename <code>delete()</code> to something else not corresponding to the equivalent C++ keyword. Also, I'm not sure what exactly this function is for, even from looking at the name. You already appear to have two functions that destroy nodes, so I'm not sure if this one is needed. If it is needed, then give it a more accurate name.</p></li>\n<li><p>In <code>linked_list_destroy()</code>, you should have a <code>while</code> loop, not an <code>if</code> statement. The loop should manually <code>free()</code> each node, one at a time. You also don't need <code>destroy()</code>. Just have the one function that performs the aforementioned procedure.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T16:26:25.130", "Id": "74315", "Score": "0", "body": "`cons` is the Racket equivalent of Lisp's `car`, which I have some experience in." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T17:10:13.673", "Id": "74325", "Score": "0", "body": "@dysruption: Okay. Make sure that is clarified in the code, if it requires explanation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T02:49:48.210", "Id": "74403", "Score": "0", "body": "Why is the `while` loop better than the recursive strategy? Sure, you use fewer functions, but I think it's clearer code. Does the general C consensus contradict me on this?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T03:11:32.910", "Id": "74404", "Score": "1", "body": "@dysruption: That's generally how it's done, and it's also quite clear. Even if you did stay with recursion, [it could still be done with just one function](http://breakinterview.com/write-a-function-to-delete-a-linked-list/)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-05-04T07:27:27.160", "Id": "161680", "Score": "0", "body": "[`cons`](https://en.wikipedia.org/wiki/Cons) is common jargon in functional programming languages. For instance, in Haskell the `(:)` function which prepends an element to a list is pronounced \"cons\" (the function appends to a list is \"snoc\")." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T05:59:29.030", "Id": "43021", "ParentId": "43018", "Score": "3" } }, { "body": "<blockquote>\n <p>I'm not actually hiding any of the implementation details from the client if they can see the helper methods. What's the correct way to do this?</p>\n</blockquote>\n\n<p>Define the helper <strike>methods</strike> functions in the C file:</p>\n\n<ul>\n<li>Define them before (higher/earlier in file) than the public functions, so that the public functions have seen them before they're compiled</li>\n<li>Define them lower/later in the C file, but put their declarations at the top of the file</li>\n</ul>\n\n<p>And, define them as <code>static</code>: that way they're not visible outside the C file (the linker doesn't create public symbols for them, therefore not only client code hasn't seen them in the header file, but also the linker won't permit client code to link to them.</p>\n\n<p>For example remove <code>append</code> from the header, and write the code like this:</p>\n\n<pre><code>// helper for linked_list_append\nstatic void append(cons *c, int value) {\n if (c-&gt;next) {\n append(c-&gt;next, value);\n } else {\n cons *new = malloc(sizeof(cons));\n new-&gt;value = value;\n new-&gt;next = NULL;\n c-&gt;next = new;\n }\n}\n\nvoid linked_list_append(linked_list *ll, int value) {\n assert(ll);\n (ll-&gt;size)++;\n if (ll-&gt;list) {\n append(ll-&gt;list, value);\n } else {\n cons *new = malloc(sizeof(cons));\n new-&gt;value = value;\n new-&gt;next = NULL;\n ll-&gt;list = new;\n }\n}\n</code></pre>\n\n<blockquote>\n <p>My delete function works, but I don't really understand it.</p>\n</blockquote>\n\n<p>I don't really understand it either. It says,</p>\n\n<pre><code>void delete(cons *c, int index, int current) {\n if (index == current) {\n cons *temp = c;\n *c = *(c-&gt;next);\n free(temp);\n } else {\n delete(c-&gt;next, index, ++current);\n }\n}\n</code></pre>\n\n<p>... which means ...</p>\n\n<ul>\n<li>If we have found the node we want to delete</li>\n<li>copy the contents of the next node onto this node</li>\n<li>free this node</li>\n</ul>\n\n<p>I suspect that it seems to work only because you access memory after it has been freed, which is illegal but which may not be visible unless/until other software is doing more malloc/free which cases the freed memory to be overwritten.</p>\n\n<p>Try the following and see whether it still works:</p>\n\n<pre><code>cons *temp = c;\n*c = *(c-&gt;next);\n// it shouldn't matter what's in the memory being freed\n// because we're not allowed to use it again after feeing it\nmemset(temp, 0 sizeof(cons));\nfree(temp);\n</code></pre>\n\n<p>The problem/solution with deleting a node from a singly-linked list is:</p>\n\n<ul>\n<li>You must search the list to find the node to be deleted</li>\n<li>Before to delete the node, you must adjust the pointers so that the previous node points to the next node</li>\n</ul>\n\n<p>Something like this (untested code ahead):</p>\n\n<pre><code>void linked_list_delete(linked_list *ll, int index) {\n assert(ll);\n assert(index &gt;= 0);\n assert(index &lt;= (ll-&gt;size - 1));\n ll-&gt;size--;\n cons *found;\n if (index == 0)\n {\n // delete first node on the list\n // list must point to the next node\n found = ll-&gt;list;\n ll-&gt;list = found-&gt;next;\n }\n else\n {\n for (int i = 0, cons* prev = ll-&gt;list; ; ++i, prev = prev-&gt;next)\n {\n if (i+1 == index)\n {\n // next node is the one we want to delete\n found = prev-&gt;next;\n // adjust pointers to point to the one beyond it\n // so we don't break the chain when we remove found\n prev-&gt;next = found-&gt;next;\n break;\n }\n }\n }\n free(found);\n}\n</code></pre>\n\n<p>It's a bit hard to do this with recursion because to delete the current node you need to be able to adjust the previous node.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T03:13:50.680", "Id": "74405", "Score": "0", "body": "I think I fixed delete and cleaned up the code rather well. How does [this](http://pastebin.com/Z3Us0wcr) look ?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T09:29:31.537", "Id": "43040", "ParentId": "43018", "Score": "4" } }, { "body": "<p>You could consider consolidating your code by using pointers-to-pointers. Here's some untested but heavily commented code showing the idea.</p>\n\n<pre><code>void linked_list_append(linked_list *ll, int value) {\n /* Acquire a pointer to the pointer to the beginning of the list. 'it' stands for\n * 'iterator' because it's used for iterating the list. */\n cons **it = &amp;ll-&gt;list;\n\n /* Walk the list, making 'it' point to every 'next' pointer in the list until\n * we find a 'next' pointer which is null (denoting the end of the list).\n */\n while ( *it ) it = &amp;it-&gt;next;\n\n /* Make the null 'next' pointer point to a new 'cons' element. */\n *it = malloc(sizeof(cons));\n (*it)-&gt;value = value;\n (*it)-&gt;next = NULL;\n\n /* Bump the size of the list by one. */\n ++ll-&gt;size;\n}\n</code></pre>\n\n<p>It may be a good idea to get a pen and paper and draw something involving boxes and arrows to see how this works.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T16:24:56.937", "Id": "74314", "Score": "0", "body": "But my ll is a pointer to a pointer, in effect, no? It holds a pointer to the first cons of the list at all times, and that cons can hold a next cons, etc." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T16:36:51.443", "Id": "74319", "Score": "0", "body": "@dysruption No, a pointer to a pointer is something which has two `*` characters in it's type. e.g. `int **`. The type of `ll` is `linked_list *`. It's a pointer to a struct." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T01:33:12.103", "Id": "74393", "Score": "0", "body": "I'm confused. My code that you site only occurs if the current `ll->list` is `NULL`. If it's not, it calls `append`, which walks the list and appends to the end." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-02T23:05:02.663", "Id": "74643", "Score": "0", "body": "@dysruption Oops, you're right - I'll adjust my answer. Thanks for pointing that out!" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T09:44:45.017", "Id": "43042", "ParentId": "43018", "Score": "2" } } ]
{ "AcceptedAnswerId": "43040", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T05:34:57.200", "Id": "43018", "Score": "4", "Tags": [ "c", "linked-list", "memory-management", "interface" ], "Title": "Singly linked list implementation in C" }
43018
<p>I have the following code for the <em>Rock, Paper, Scissor</em> game. The code works fine in Python 2.7. Are there other more concise, more readable, or more pythonic ways of solving this problem in Python? </p> <pre><code>player1 = raw_input ("?") player2 = raw_input ("?") if (player1 == 'rock' and player2 == 'scissors'): print "Player 1 wins." elif (player1 == 'rock' and player2 == 'rock'): print "Tie" elif (player1 == 'scissors' and player2 == 'paper'): print "Player 1 wins." elif (player2 == 'scissors' and player2 == 'scissors'): print "Tie" elif (player1 == 'paper' and player2 == 'paper'): print "Tie" elif (player1 == 'paper' and player2 == 'scissors'): print "Player 2 wins." elif (player1 == 'rock'and player2 == 'paper'): print "Player 2 wins." elif (player1 == 'paper' and player2 == 'rock'): print "Player 2 wins." elif (player1 == 'scissors' and player2 == 'rock'): print "Player 2 wins." else: print "This is not a valid object selection." </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T12:28:52.853", "Id": "74276", "Score": "0", "body": "What’s wrong with it? It seems to work as expected for me." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T13:03:07.233", "Id": "74280", "Score": "3", "body": "`beats = {'rock': 'scissors', 'paper': 'rock', 'scissors': 'paper'}` might be a more useful construct in your case." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T21:20:24.727", "Id": "74492", "Score": "0", "body": "alexwlchan- It worked for you? What version of Python are you using?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-03T09:50:31.480", "Id": "74695", "Score": "0", "body": "@user3335834: v2.7.5, the default version that ships with OS X." } ]
[ { "body": "<p>Here are some suggestions:</p>\n\n<ul>\n<li><p>We have three <code>if</code> statements that end in <code>\"Tie\"</code>. We could take all three conditions at once (<code>(player1 == 'scissors' and player2 == 'scissors') or ...</code>), or we could notice that we want the two players to have picked the same thing. So immediately we can simplify these three statements:</p>\n\n\n\n<pre><code>if (player1 == player2):\n print \"Tie\"\n</code></pre>\n\n<p>That's a lot shorter and simpler, and it doesn't depend on what choices are available. This would work just as well in a game with five or fifty options.</p></li>\n<li><p>There are still six <code>if</code> statements left, for the cases where the two players pick different things. As suggested by <a href=\"https://codereview.stackexchange.com/questions/43024/use-if-else-elif-conditionals-to-write-a-basic-rock-paper-scissors-game#comment74280_43024\">Joel in the comments</a>, a dictionary explaining the hierarchy between the different choices might be useful.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>beats = {\n 'scissors': 'rock',\n 'rock': 'paper',\n 'paper': 'scissors',\n}\n</code></pre>\n\n<p>Note that I've done it the other way round to Joel: I think <code>'rock' = beats['scissors']</code> looks more natural, but I don’t think it makes too much of a difference.</p>\n\n<p>Now we have a very natural way to describe the cases when the players don't pick the same thing:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>if (player1 == player2):\n print \"Tie\"\nelif (player1 == beats[player2]):\n print \"Player 1 wins.\"\nelif (player2 == beats[player1]):\n print \"Player 2 wins.\"\n</code></pre></li>\n<li><p>Where once there were nine <code>if</code> statements, now there are just three, and this can be made to work for any variant on the game. By swapping out <code>beats</code>, we could play Rock-Paper-Scissors-Lizard-Spock, Bear-Hunter-Ninja, Bacon-Lettuce-Tomato, or anything else we wanted.</p>\n\n<p>This is a good idea for programming in general: we've separated the game logic from the specific choices. Keeping them separate makes our program easier to write and to debug.</p></li>\n<li><p>I like to wrap self-contained blocks of code (like this game logic) into their own functions.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def play_game(player1, player2, beats):\n \"\"\"Returns the result of the game with player1 vs player2.\"\"\"\n if (player1 == player2):\n return \"Tie\"\n elif (player1 == beats[player2]):\n return \"Player 1 wins.\"\n elif (player2 == beats[player1]):\n return \"Player 2 wins.\"\n</code></pre></li>\n<li><p>Now the top and bottom matter. This gets the players’s moves. By separating this from the game logic, we can work on this without worrying about whether we've broken the game.</p>\n\n<p>To get the player's move, you've used:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>player1 = raw_input(\"?\")\nplayer2 = raw_input(\"?\")\n</code></pre>\n\n<p>This is the right way to do it, but the <code>\"?\"</code> is unnecessarily ambiguous. You should be clear what you want. To quote from <a href=\"http://legacy.python.org/dev/peps/pep-0020/\" rel=\"nofollow noreferrer\">The Zen of Python</a>:</p>\n\n<blockquote>\n <p>Explicit is better than implicit.</p>\n</blockquote>\n\n<p>So let’s write a full question here, so that it's clear what the choices mean:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>player1 = raw_input(\"What is player 1's move? \")\nplayer2 = raw_input(\"What is player 2's move? \")\n</code></pre></li>\n<li><p>To validate the input, you add an <code>else</code> block at the end of the code:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>else:\n print \"This is not a valid object selection.\"\n</code></pre>\n\n<p>You'd be better off validating the input when you receive it. Right now, the players have no way of telling which of them entered the wrong thing.</p>\n\n<p>Here's one way you might do that:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>player1 = raw_input(\"What is player 1's move? \")\n\nwhile player1 not in ['rock', 'paper', 'scissors']:\n player1 = raw_input(\"That is not a valid object selection. Please try again. \")\n</code></pre>\n\n<p>Here we continue asking until we get something we like. But we can be more helpful. For example, you could tell the player what choices are available (you could even print this before the players make their initial choices).</p>\n\n<p>While we're looking at this, we can use <code>beats.keys()</code> to get the list of possible choices, rather than typing them out every time. Here's an example:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>print \"The choices are \" + str(beats.keys())\n\nplayer1 = raw_input(\"What is player 1's move? \")\nwhile player1 not in beats.keys():\n player1 = raw_input(\"I didn't get that. Please choose from \" + str(beats.keys()))\n</code></pre>\n\n<p>As an additional point, you might want to do some sort of “fuzzy” matching on the input. The program needs to get the string <code>\"rock\"</code> precisely, but it’s pretty clear what somebody who types <code>\"Rock\"</code> or <code>\"rock\\n\"</code> means. String methods like <code>lower()</code> and <code>strip()</code> might be useful here.</p></li>\n<li><p>Finally, consider putting this code inside a special section <code>if __name__ == '__main__'</code>.</p>\n\n<p>Any code in this section only gets used if the file is run directly (e.g., if somebody types <code>$ python rockpaper.py</code> at the command line). On the other hand, if you use <code>import rockpaper</code> in another script, it gets ignored. Right now, anybody who <code>import</code>'s this script starts playing rock-paper-scissors (which they may not want).</p>\n\n<p>There's more information on this around the web or on Stack Overflow.</p></li>\n</ul>\n\n<p>So this is the sort of thing we might be left with:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def play_game(player1, player2, beats):\n \"\"\"Returns the result of the game with player1 vs player2.\"\"\"\n if (player1 == player2):\n return \"Tie\"\n elif (player1 == beats[player2]):\n return \"Player 1 wins.\"\n elif (player2 == beats[player1]):\n return \"Player 2 wins.\"\n\nif __name__ == '__main__':\n beats = {\n 'scissors': 'rock',\n 'rock': 'paper',\n 'paper': 'scissors',\n }\n\n print \"The choices are \" + str(beats.keys())\n\n player1 = raw_input(\"What is player 1's move? \")\n while player1 not in beats.keys():\n player1 = raw_input(\"I didn't get that. Please choose from \" + str(beats.keys()))\n\n player2 = raw_input(\"What is player 2's move? \")\n while player2 not in beats.keys():\n player2 = raw_input(\"I didn't get that. Please choose from \" + str(beats.keys()))\n\n print play_game(player1, player2, beats)\n</code></pre>\n\n<p>It looks more complicated than a stack of conditionals, but this is a lot more maintainable and portable than before.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-03T11:41:16.157", "Id": "43294", "ParentId": "43024", "Score": "7" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T06:10:19.927", "Id": "43024", "Score": "3", "Tags": [ "python", "game", "rock-paper-scissors" ], "Title": "Use if/else/elif conditionals to write a basic Rock Paper Scissors game" }
43024
<p>Review this code.</p> <pre><code>mode = "PARALLE" try: if mode == "PARALLEL": # some code - this will not raise ValueError elif mode == "SERIES": # some code else: raise ValueError("Error: Invalid mode") except ValueError, Argument: print Argument phase = "inverte" try: if phase == "inverted": # some code elif phase == "non_inverted": # some code else: raise ValueError("Error: Invalid phase") except ValueError, Argument: print Argument </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T06:44:05.200", "Id": "74225", "Score": "0", "body": "Do you expect `# some code` to raise `ValueError` sometimes?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T06:54:13.993", "Id": "74226", "Score": "0", "body": "@JanneKarila no #some_code it will not raise ValueError, only if and else will raise" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T08:55:36.847", "Id": "74245", "Score": "3", "body": "There's not much to review here. Can you provide the actual code and an explanation on what you are trying to achieve ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T08:58:18.887", "Id": "74246", "Score": "0", "body": "@Josay I just want to catch a ValueError in a module raised from another module" } ]
[ { "body": "<h2>Enums and typos</h2>\n\n<pre><code>mode = \"PARALLE\"\n</code></pre>\n\n<p>Typo! To avoid this, you should use a variable: <code>PARALLEL = 1</code> or <code>PARALLEL = 'PARALLEL'</code> and <code>mode = PARALLEL</code>. Any typo will then be catched by Python when running the program. The uppercase is just a convention to say it's a constant. Unfortunately Python enums will only be usable in Python 3.4 which is will only be available in three weeks. And Python 3 is incompatible with Python 2, so it may not be practical to switch.</p>\n\n<h2>Exceptions</h2>\n\n<pre><code>try:\n\n if mode == \"PARALLEL\":\n\n # some code - this will not raise ValueError\n\n elif mode == \"SERIES\":\n\n # some code \n\n else:\n\n raise ValueError(\"Error: Invalid mode\")\n\nexcept ValueError, Argument:\n</code></pre>\n\n<p>In Python, by convention we have CONSTANTS, variables, and Classes. Since your argument is only a variable, you should name it <code>argument</code> and not <code>Argument</code>. Actually, <code>e</code> for exception is the convention, you could stick with it (<code>except ValueError, e:</code>).</p>\n\n<pre><code> print Argument\n</code></pre>\n\n<h2>Keep it simple</h2>\n\n<p>What do you want to do when the mode is invalid? Who is going to see the error message? Is it acceptable to crash the application to make the error noticeable? Or do you want to try recovering in another function which called this code?</p>\n\n<ul>\n<li><p>If you only want to print the message, then you should keep it simple:</p>\n\n<pre><code>if mode == 'PARALLEL':\n # some code - no ValueError\nelif mode == 'SERIES':\n # some other code - no ValueError\nelse:\n print 'Error: Invalid mode'\n</code></pre>\n\n<p>You could also print the message to standard error (<code>print &gt;&gt; sys.stderr, 'Error: Invalid mode'</code> in Python 2).</p></li>\n<li><p>If you want the error to be noticed and corrected (eg. if you are the only user of your program), then fail fast by raising the exception and never catching it.</p></li>\n<li>If, however, you want to do something better, then the exception would allow you to catch the error elsewhere.</li>\n</ul>\n\n<p>(The same comments apply to the second phase).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T09:28:28.187", "Id": "43039", "ParentId": "43026", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T06:19:01.753", "Id": "43026", "Score": "-1", "Tags": [ "python", "python-2.x", "error-handling" ], "Title": "Use of multiple value errors in Python" }
43026
<p>Call from my index.php to function <code>get_data($curr_date)</code> goes from here</p> <pre><code>case "events" : $curr_date = $_POST['current_date']; if ( $eid = get_data($curr_date) ) { $result = array( "success"=&gt;true, "eid"=&gt;$eid); $json_output = json_encode( $result ); echo $json_output; } else echo FAIL; break; enter code here </code></pre> <p>This is my function which returns the result</p> <pre><code>function get_data($curr_date) { $events_list = mysql_query( "SELECT eid, display_date, word_of_the_day, word_of_the_day_meaning, thought_of_the_day, crazyFact_of_the_day, joke_of_the_day FROM eventsoftheday WHERE display_date = '$curr_date' "); // get mysql result cursor if( mysql_num_rows( $events_list ) &gt; 0 ) // check if the query returned any records { $mysql_record = mysql_fetch_array( $events_list ); // parse mysql result cursor $events = array(); $events['e_id'] = $mysql_record['eid']; $events['edisplay_date'] = $mysql_record['display_date']; $events['eword_of_the_day'] = $mysql_record['word_of_the_day']; $events['eword_of_the_day_meaning'] = $mysql_record['word_of_the_day_meaning']; $events['ethought_of_the_day'] = $mysql_record['thought_of_the_day']; $events['ecrazyFact_of_the_day'] = $mysql_record['crazyFact_of_the_day']; $events['ejoke_of_the_day'] = $mysql_record['joke_of_the_day']; return $events; // return events } else return false; } </code></pre>
[]
[ { "body": "<p>Maybe it's better to return error in JSON (if FAIL constant isn't JSON yet)</p>\n\n<pre><code>echo json_encode(array('result' =&gt; false));\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>echo FAIL;\n</code></pre>\n\n<p>or return HTTP error code</p>\n\n<pre><code>header('HTTP/1.1 500 Internal Server Error');\n</code></pre>\n\n<p>And we can simplifify function get_data like this:</p>\n\n<pre><code>if(mysql_num_rows( $events_list )) // check if the query returned any records\n{\n $mysql_record = mysql_fetch_array( $events_list ); // parse mysql result cursor\n return array(\n 'e_id' =&gt; $mysql_record['eid'],\n 'edisplay_date' =&gt; $mysql_record['display_date'],\n 'eword_of_the_day' =&gt; $mysql_record['word_of_the_day'],\n 'eword_of_the_day_meaning' =&gt; $mysql_record['word_of_the_day_meaning'],\n 'ethought_of_the_day' =&gt; $mysql_record['thought_of_the_day'],\n 'ecrazyFact_of_the_day' =&gt; $mysql_record['crazyFact_of_the_day'],\n 'ejoke_of_the_day' =&gt; $mysql_record['joke_of_the_day'],\n );\n} else return false;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-05T03:35:18.593", "Id": "75148", "Score": "0", "body": "thank u sir but .. my issue got solved using above method" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T09:40:29.623", "Id": "43041", "ParentId": "43028", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T07:07:49.453", "Id": "43028", "Score": "2", "Tags": [ "php", "json" ], "Title": "Return JSON array through PHP" }
43028
<p>I have a Ruby code segment which I need to DRY up. Can it be done without meta programming?</p> <pre><code>def disable_attribute statement1 @response = Client::Service.disable_attribute( param1: param1value, param2: param2value ) statement2 end def enable_attribute statement1 @response = Client::Service.enable_attribute( param1: param1value, param2: param2value ) statement2 end </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T09:26:06.720", "Id": "74247", "Score": "0", "body": "those methods have no arguments for the attribute that's being updated?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T13:03:44.970", "Id": "74281", "Score": "0", "body": "\"Without metaprogramming\"? This is per definition meta as it is about the method name, which is outside the problem domain." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-09-18T00:12:31.627", "Id": "265529", "Score": "0", "body": "Note that this question no longer meets Code Review's current standards, as there are too many vague placeholders for a meaningful review." } ]
[ { "body": "<p>How about:</p>\n\n<pre><code>def toggle_attribute\n statement1\n @response = yield(\n param1: param1value,\n param2: param2value\n )\n statement2\nend\n\ndef disable_attribute\n toggle_attribute { |params| Client::Service.disable_attribute(params) }\nend\n\ndef enable_attribute\n toggle_attribute { |params| Client::Service.enable_attribute(params) }\nend\n</code></pre>\n\n<p>If you want to be more succinct, you could:</p>\n\n<pre><code>def toggle_attribute(method_name)\n statement1\n @response = Client::Service.send(method_name,\n param1: param1value,\n param2: param2value\n )\n statement2\nend\n\ndef disable_attribute\n toggle_attribute(:disable_attribute)\nend\n\ndef enable_attribute\n toggle_attribute(:enable_attribute)\nend\n</code></pre>\n\n<p>And if you want to really impress your friends, you could write:</p>\n\n<pre><code>def toggle_attribute(method_name)\n statement1\n @response = Client::Service.send(method_name,\n param1: param1value,\n param2: param2value\n )\n statement2\nend\n\ndef method_missing(method_name, *args)\n %i[disable_attribute enable_attribute].include?(method_name) ? \n toggle_attribute(method_name) : super\nend\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T19:11:54.487", "Id": "74480", "Score": "1", "body": "Nice answer, Uri. I'd definitely vote for the second option." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-03T09:05:06.843", "Id": "74693", "Score": "0", "body": "@Jonah: `method_missing` is a basic example of metaprogramming ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-03T18:30:44.800", "Id": "74789", "Score": "0", "body": "That was the 3rd option, I voted 2nd" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-19T01:05:03.590", "Id": "77723", "Score": "0", "body": "Great answer! I don't think I'd use the term `toggle` in the method name, though, because the method doesn't toggle. Perhaps `set` or `update`." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T09:12:41.593", "Id": "43036", "ParentId": "43031", "Score": "7" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T07:45:09.293", "Id": "43031", "Score": "4", "Tags": [ "ruby" ], "Title": "Ruby methods to enable and disable attributes" }
43031
<p>I wrote this function as part of interview practice. This method removes a character from a given string.</p> <p>I was wondering how I could make this code more efficient when it comes to runtime/space. I think my code is O(n) and I'm not sure if I can increase the efficiency. However, perhaps using things such as <code>StringBuffer</code> or <code>StringBuilder</code> would increase it a bit? I'm not sure as I'm still a bit new to Java.</p> <pre><code>public static String takeOut(String str, char c) { int len = str.length(); String newstr = ""; for (int i = 0; i &lt; len; i++) { if (str.charAt(i) != c) { newstr = newstr + str.charAt(i); } } return newstr; } </code></pre>
[]
[ { "body": "<p>Learn from existing implementations, they usually have solutions to corner cases, common pitfalls and performance bottlenecks. For example, Apache Commons Lang <a href=\"http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html\"><code>StringUtils</code></a> also has a <a href=\"http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#remove%28java.lang.String,%20char%29\"><code>remove</code></a> function. It's <a href=\"http://svn.apache.org/viewvc/commons/proper/lang/trunk/src/main/java/org/apache/commons/lang3/StringUtils.java?view=markup#l4359\">implementation</a> is quite simple and similar to yours:</p>\n\n<pre><code>public static String remove(final String str, final char remove) {\n if (isEmpty(str) || str.indexOf(remove) == INDEX_NOT_FOUND) {\n return str;\n }\n final char[] chars = str.toCharArray();\n int pos = 0;\n for (int i = 0; i &lt; chars.length; i++) {\n if (chars[i] != remove) {\n chars[pos++] = chars[i];\n }\n }\n return new String(chars, 0, pos);\n}\n</code></pre>\n\n<p>Anyway, there are some differences:</p>\n\n<ol>\n<li><p>It uses <code>char</code> array. <code>String</code>s are immutable, the following concatenation creates a new <code>String</code> object:</p>\n\n<pre><code>newstr = newstr + str.charAt(i);\n</code></pre>\n\n<p>I guess it's slower than changing a value in an array.</p>\n\n<blockquote>\n <p>Using the string concatenation operator\n repeatedly to concatenate <em>n</em> strings requires time quadratic in <em>n</em>.</p>\n</blockquote>\n\n<p>Source: <em>Effective Java, 2nd edition</em>, <em>Item 51: Beware the performance of string concatenation</em></p></li>\n<li><p>At the first line it checks whether the <code>String</code> contains the removed character at all. If it doesn't contain it <code>remove</code> saves the creation the char array. It might help but it depends on your input.</p></li>\n<li><p>The code in the question calls <code>String.charAt()</code> in the comparison which checks the given index:</p>\n\n<pre><code>public char charAt(int index) {\n if ((index &lt; 0) || (index &gt;= value.length)) {\n throw new StringIndexOutOfBoundsException(index);\n }\n return value[index];\n}\n</code></pre>\n\n<p>The <code>StringUtils</code> implementation skips this test since it knows that the index is valid.</p></li>\n</ol>\n\n<p>(See also: <em>Effective Java, 2nd edition</em>, <em>Item 47: Know and use the libraries</em>)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T11:43:01.157", "Id": "74271", "Score": "3", "body": "1 additional micro optimization would be to cache the result of the `indexOf` call and use it as the starting value in he for loop" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T14:25:54.317", "Id": "74293", "Score": "0", "body": "@ratchetfreak I don't get why indexOf is there at all? If the char is not found, looping through the char array should find that out just as fast as indexOf would right? indexOf can't be any faster than looping through the char array right?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T14:31:33.857", "Id": "74295", "Score": "0", "body": "@Cruncher: `String.toCharArray()` copies the whole `String` to a new array. I guess it could be slow (but it should be measured)." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T08:39:51.557", "Id": "43034", "ParentId": "43032", "Score": "13" } }, { "body": "<p>First indeed your code has a complexity of O(n) (n the number of characters of the String), it would precisely depend on the implementation of the method String.charAt(index), but we could most likely consider it has direct access.</p>\n\n<p>O(n) is the lowest one can do. Indeed, think as the following: how could you remove all instances of a character of the String if you do not look at all the characters of this String. So this is hardly possible to do better.</p>\n\n<p>There is a <a href=\"https://stackoverflow.com/questions/10078912/java-string-concatenation-best-practices-performance\">question on SO about performance of String concatenation in Java</a>. For your question I would say then the StringBuilder might be a better option. I would also consider creating an array of char from scratch, but I don't know how the String constructor from an array behaves in terms of performance.</p>\n\n<p>In the end, if the goal is just to remove a character from a String (out of an interview question), usually call String.replaceAll(myChar, \"\");</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T16:09:20.513", "Id": "74310", "Score": "1", "body": "Isn't this code `O(n^2)`? The concatenation operation is already `O(newstring.length())` and this can happen `n` times for a total cost of `O(n^2)`. (Assuming a naive compiler that doesn't silently replace `String` with `StringBuilder`)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T16:16:51.837", "Id": "74311", "Score": "0", "body": "@CodesInChaos the code is O(n^2) you are correct because of the way I am concatenating the String objects" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T16:18:40.157", "Id": "74312", "Score": "0", "body": "OK so clearly using an array of characters would be faster (I suppose with direct access)." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T08:44:12.473", "Id": "43035", "ParentId": "43032", "Score": "5" } }, { "body": "<p>I would add the following:</p>\n\n<ul>\n<li><p>unit test</p>\n\n<p>Code some unit tests and it has to become an habit for you. If you publish some code then also add the unit tests. First, you can check yourself the correctness of your code and second it will help us to refactor your code (producing a better solution). </p></li>\n<li><p>good names</p>\n\n<p>Please use good names. I know, even the names used by Apache are not good. No 'c', no 'str'. A name that is self descriptive. No comments needed. I know that not everybody will agree because the code seems a little bit more 'heavy', but what a pleasure to read!</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T10:40:31.743", "Id": "74260", "Score": "0", "body": "What could you use instead of `str` and `c` in this library function?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T10:46:08.313", "Id": "74261", "Score": "0", "body": "I it my own responsibility but I prefer a lot more to read stringToBeProcessed and characterToBeRemoved... But I know that some people will disagree..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T10:51:26.600", "Id": "74264", "Score": "0", "body": "Btw because you will write lots of small methods (good method names) that do almost nothing and avoid code duplication, the self descriptive names will not be a big problem..." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T10:34:46.697", "Id": "43046", "ParentId": "43032", "Score": "5" } } ]
{ "AcceptedAnswerId": "43034", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T07:54:44.230", "Id": "43032", "Score": "8", "Tags": [ "java", "beginner", "performance", "strings", "memory-management" ], "Title": "Increase performance of removing character from String" }
43032
<p>This is an algorithm I'm trying to optimize. I was trying to use openMP without any success.</p> <p>I know the code is long but most of it is params init.</p> <p>Please try to explain why I need to change any line of code. I want to learn. I also wish to understand if using openMP is the best way for matrix based algorithms.</p> <pre><code>void CAlgo::runAlgo() { neighborhood int nbr_TBL_RES[Algo_NBR_SZ][Algo_NBR_SZ] ; int TBL [Algo_NUM_CANDIDATE] ; int expIn [Algo_NUM_CANDIDATE] ; int W [Algo_NUM_CANDIDATE] ; unsigned int WShift1 [Algo_NUM_CANDIDATE] ; unsigned int WShift2 [Algo_NUM_CANDIDATE] ; bool WSubFlag [Algo_NUM_CANDIDATE] ; int meanP ; unsigned int meanPShift1 ; unsigned int meanPShift2 ; bool meanPSubFlag ; unsigned int TBLShift1 ; unsigned int TBLShift2 ; bool TBLSubFlag ; int sigmaP ; int eta ; unsigned int etaShift1 ; unsigned int etaShift2 ; bool etaSubFlag ; unsigned int rSqrShift1 ; unsigned int rSqrShift2 ; bool rSqrSubFlag ; int RxSqr ; int RySqr ; unsigned int rPwrShift1 ; unsigned int rPwrShift2 ; bool rPwrSubFlag ; int alpha0 ; int WSum ; int PAvrg ; unsigned int alphaShift1 ; unsigned int alphaShift2 ; bool alphaSubFlag ; unsigned int ind; int Rx,Ry ; int wMax[4] ; int dP ; int Pout ; int i0 = Algo_NBR_SZ/2 - Algo_PATCH_SZ/2 + Algo_FILT_PIXEL_dY; int i1 = Algo_NBR_SZ/2 + Algo_PATCH_SZ/2 - Algo_FILT_PIXEL_dY; int j0 = Algo_NBR_SZ/2 - Algo_PATCH_SZ/2 + Algo_FILT_PIXEL_dX; int j1 = Algo_NBR_SZ/2 + Algo_PATCH_SZ/2 - Algo_FILT_PIXEL_dX; //int k,l; // debug data int** TBL00 = NULL; int** TBL01 = NULL; int** TBL02 = NULL; int** TBL03 = NULL; int** TBL04 = NULL; int** TBL05 = NULL; int** TBL06 = NULL; int** TBL07 = NULL; int** TBL08 = NULL; int** TBL09 = NULL; int** TBL10 = NULL; int** TBL11 = NULL; int** TBL12 = NULL; int** TBL13 = NULL; int** TBL14 = NULL; int** TBL15 = NULL; int** W00 = NULL; int** W01 = NULL; int** W02 = NULL; int** W03 = NULL; int** W04 = NULL; int** W05 = NULL; int** W06 = NULL; int** W07 = NULL; int** W08 = NULL; int** W09 = NULL; int** W10 = NULL; int** W11 = NULL; int** W12 = NULL; int** W13 = NULL; int** W14 = NULL; int** W15 = NULL; int** EXP_IN00 = NULL; int** EXP_IN01 = NULL; int** EXP_IN02 = NULL; int** EXP_IN03 = NULL; int** EXP_IN04 = NULL; int** EXP_IN05 = NULL; int** EXP_IN06 = NULL; int** EXP_IN07 = NULL; int** EXP_IN08 = NULL; int** EXP_IN09 = NULL; int** EXP_IN10 = NULL; int** EXP_IN11 = NULL; int** EXP_IN12 = NULL; int** EXP_IN13 = NULL; int** EXP_IN14 = NULL; int** EXP_IN15 = NULL; // allocate memory for storing debug data if (m_Debug) { TBL00 = new int*[m_Height]; TBL01 = new int*[m_Height]; TBL02 = new int*[m_Height]; TBL03 = new int*[m_Height]; TBL04 = new int*[m_Height]; TBL05 = new int*[m_Height]; TBL06 = new int*[m_Height]; TBL07 = new int*[m_Height]; TBL08 = new int*[m_Height]; TBL09 = new int*[m_Height]; TBL10 = new int*[m_Height]; TBL11 = new int*[m_Height]; TBL12 = new int*[m_Height]; TBL13 = new int*[m_Height]; TBL14 = new int*[m_Height]; TBL15 = new int*[m_Height]; W00 = new int*[m_Height]; W01 = new int*[m_Height]; W02 = new int*[m_Height]; W03 = new int*[m_Height]; W04 = new int*[m_Height]; W05 = new int*[m_Height]; W06 = new int*[m_Height]; W07 = new int*[m_Height]; W08 = new int*[m_Height]; W09 = new int*[m_Height]; W10 = new int*[m_Height]; W11 = new int*[m_Height]; W12 = new int*[m_Height]; W13 = new int*[m_Height]; W14 = new int*[m_Height]; W15 = new int*[m_Height]; EXP_IN00 = new int*[m_Height]; EXP_IN01 = new int*[m_Height]; EXP_IN02 = new int*[m_Height]; EXP_IN03 = new int*[m_Height]; EXP_IN04 = new int*[m_Height]; EXP_IN05 = new int*[m_Height]; EXP_IN06 = new int*[m_Height]; EXP_IN07 = new int*[m_Height]; EXP_IN08 = new int*[m_Height]; EXP_IN09 = new int*[m_Height]; EXP_IN10 = new int*[m_Height]; EXP_IN11 = new int*[m_Height]; EXP_IN12 = new int*[m_Height]; EXP_IN13 = new int*[m_Height]; EXP_IN14 = new int*[m_Height]; EXP_IN15 = new int*[m_Height]; for (int i=0; i &lt; m_Height; i++) { TBL00[i] = new int[m_Width]; TBL01[i] = new int[m_Width]; TBL02[i] = new int[m_Width]; TBL03[i] = new int[m_Width]; TBL04[i] = new int[m_Width]; TBL05[i] = new int[m_Width]; TBL06[i] = new int[m_Width]; TBL07[i] = new int[m_Width]; TBL08[i] = new int[m_Width]; TBL09[i] = new int[m_Width]; TBL10[i] = new int[m_Width]; TBL11[i] = new int[m_Width]; TBL12[i] = new int[m_Width]; TBL13[i] = new int[m_Width]; TBL14[i] = new int[m_Width]; TBL15[i] = new int[m_Width]; W00[i] = new int[m_Width]; W01[i] = new int[m_Width]; W02[i] = new int[m_Width]; W03[i] = new int[m_Width]; W04[i] = new int[m_Width]; W05[i] = new int[m_Width]; W06[i] = new int[m_Width]; W07[i] = new int[m_Width]; W08[i] = new int[m_Width]; W09[i] = new int[m_Width]; W10[i] = new int[m_Width]; W11[i] = new int[m_Width]; W12[i] = new int[m_Width]; W13[i] = new int[m_Width]; W14[i] = new int[m_Width]; W15[i] = new int[m_Width]; EXP_IN00[i] = new int[m_Width]; EXP_IN01[i] = new int[m_Width]; EXP_IN02[i] = new int[m_Width]; EXP_IN03[i] = new int[m_Width]; EXP_IN04[i] = new int[m_Width]; EXP_IN05[i] = new int[m_Width]; EXP_IN06[i] = new int[m_Width]; EXP_IN07[i] = new int[m_Width]; EXP_IN08[i] = new int[m_Width]; EXP_IN09[i] = new int[m_Width]; EXP_IN10[i] = new int[m_Width]; EXP_IN11[i] = new int[m_Width]; EXP_IN12[i] = new int[m_Width]; EXP_IN13[i] = new int[m_Width]; EXP_IN14[i] = new int[m_Width]; EXP_IN15[i] = new int[m_Width]; } } Ry = m_RyInitial; int row,col; #pragma omp parallel for schedule(static) default(none) \ firstprivate(Pout,nbr_TBL_RES,TBL,row,col,Ry,Rx,i0,i1,j0,j1,\ meanP,meanPShift1,meanPShift2,meanPSubFlag,TBLShift1,TBLShift2,TBLSubFlag,sigmaP,eta,etaShift1,etaShift2,etaSubFlag,rSqrShift1,rSqrShift2,\ rSqrSubFlag,RxSqr,RySqr,rPwrShift1,rPwrShift2,rPwrSubFlag,alpha0,WSum,PAvrg,alphaShift1,alphaShift2,alphaSubFlag,ind,\ expIn,W,WShift1,WShift2,WSubFlag,wMax,dP,TBL00,TBL01,TBL02,TBL03,TBL04,TBL05,TBL06,TBL07,TBL08,TBL09,TBL10,TBL11,\ TBL12,TBL13,TBL14,TBL15,W00,W01,W02,W03,W04,W05,W06,W07,W08,W09,W10,W11,W12,W13,W14,W15,EXP_IN00,EXP_IN01,EXP_IN02,EXP_IN03,\ EXP_IN04,EXP_IN05,EXP_IN06,EXP_IN07,EXP_IN08,EXP_IN09,EXP_IN10,EXP_IN11,EXP_IN12,EXP_IN13,EXP_IN14,EXP_IN15) */ for(row = 0; row &lt; m_Height; ++row) { int nbr[Algo_NBR_SZ][Algo_NBR_SZ] ; // neighborhood int k,l; //int **ptrPtrNbrK = (int**)nbr; //int* ptrNbrK = 0; Rx = m_RxInitial; for(col = 0; col &lt; m_Width ; ++col) { // prepare neighborhood /*k = 0; for (int i=-i0;i&lt;i1; ++i) { l = 0; for (int j=-j0;j&lt;j1; ++j) { if ((row+i)&lt;0 || (row+i)&gt;=m_Height ||(col+j)&lt;0 || (col+j)&gt;=m_Width) { nbr[k][l] = 0; } else { nbr[k][l] = m_Pin-&gt;m_R[row+i][col+j]; } l++; } k++; }*/ // prepare neighborhood k = 0; int* ptrNbrK = nbr[0]; for (int i=-i0;i&lt;i1; ++i) { int row_plus_i = row+i; int* m_Pin_m_R_row_plus_i=m_Pin-&gt;m_R[row_plus_i]; l = 0; for (int j=-j0;j&lt;j1; ++j) { int col_plus_j = col+j; if ((row_plus_i)&lt;0 || (row_plus_i)&gt;=m_Height ||(col_plus_j)&lt;0 || (col_plus_j)&gt;=m_Width) { //nbr[k][l] = 0; ptrNbrK[l] =0; } else { ///nbr[k][l] = m_Pin-&gt;m_R[row_plus_i][col_plus_j]; ptrNbrK[l]= m_Pin_m_R_row_plus_i[col_plus_j]; } l++; } //k++; ptrNbrK = nbr[++k]; //ptrNbrK++; } shiftToRequiredPrecision(nbr, nbr_TBL_RES); computeTBLs(nbr_TBL_RES, TBL); calculatePatchStatistics(nbr_TBL_RES, meanP, meanPShift1, meanPShift2, meanPSubFlag, sigmaP, TBLShift1, TBLShift2, TBLSubFlag); eta = calculateDetailIndex(sigmaP, meanPShift1, meanPShift2, meanPSubFlag, ind); SettingSigmaN(eta, Rx, Ry, RxSqr, RySqr, etaShift1, etaShift2, etaSubFlag, rSqrShift1, rSqrShift2, rSqrSubFlag, rPwrShift1, rPwrShift2, rPwrSubFlag); for (int i=0; i&lt;Algo_NUM_CANDIDATE; ++i) { if (m_CandEnable[i]) { expIn[i] = CalculateWeights(TBL[i], etaShift1, etaShift2, etaSubFlag, rSqrShift1, rSqrShift2, rSqrSubFlag, TBLShift1, TBLShift2, TBLSubFlag, W[i], WShift1[i], WShift2[i], WSubFlag[i]); } else { W[i] = 0; WShift1[i] = 0; WShift2[i] = 0; WSubFlag[i] = 0; expIn[i] = 0; } } // adjust candidates group (B,C,D) weight values for (int i = Algo_FIRST_CANDIDATE_B; i&lt;Algo_NUM_CANDIDATE_B+Algo_FIRST_CANDIDATE_B; ++i) { W[i] = CommonFunctions::ShiftSubMultiplier(W[i], m_BCandSubFlag[ind], m_BCandShift1[ind], m_BCandShift2[ind]); } for (int i = Algo_FIRST_CANDIDATE_C; i&lt;Algo_NUM_CANDIDATE_C+Algo_FIRST_CANDIDATE_C; ++i) { W[i] = CommonFunctions::ShiftSubMultiplier(W[i], m_CCandSubFlag[ind], m_CCandShift1[ind], m_CCandShift2[ind]); } for (int i = Algo_FIRST_CANDIDATE_D; i&lt;Algo_NUM_CANDIDATE_D+Algo_FIRST_CANDIDATE_D; ++i) { W[i] = CommonFunctions::ShiftSubMultiplier(W[i], m_DCandSubFlag[ind], m_DCandShift1[ind], m_DCandShift2[ind]); } WSum = ComputingWeightSum(W); alpha0 = MatchQualityIndex(W, wMax, ind); PAvrg = ComputeAveragePixel(WShift1, WShift2, WSubFlag, nbr, WSum, ind); BlendingCoefficient(alpha0, alphaSubFlag, alphaShift1, alphaShift2, ind); #if 0 if ((row&gt;226)&amp;&amp;(col&gt;410)) int p_in = m_Pin-&gt;m_R[row][col]; #endif Pout = m_Pin-&gt;m_R[row][col]; dP = 0; if (WSum&gt;m_wSumMinTh || wMax[0]&gt;m_wMaxMinTh) { Pout = SynthesizeOutputPixel(m_Pin-&gt;m_R[row][col], PAvrg, alphaSubFlag, alphaShift1, alphaShift2, rPwrSubFlag, rPwrShift1, rPwrShift2, dP ); } Rx++; m_Pout -&gt;m_R[row][col] = Pout; m_PoutDiff -&gt;m_R[row][col] = m_Pin-&gt;m_R[row][col] - Pout; //m_PoutDiff -&gt;m_R[row][col] = abs(m_Pin-&gt;m_R[row][col] - PAvrg); m_PoutAlpha0-&gt;m_R[row][col] = alpha0; m_MapMeanP -&gt;m_R[row][col] = meanP; m_MapAlpha0 -&gt;m_R[row][col] = alpha0; m_MapAlpha -&gt;m_R[row][col] = CommonFunctions::ShiftSubMultiplier((1&lt;&lt;Algo_NL_LUT_ARR_MAX_SHIFT), alphaSubFlag, alphaShift1, alphaShift2); m_MapSTD -&gt;m_R[row][col] = eta; m_MapInd -&gt;m_R[row][col] = ind; //m_MapInd -&gt;m_R[row][col] = rSqr; //m_MapInd -&gt;m_R[row][col] = dP; if (m_Debug) { TBL00[row][col] = TBL[0]; TBL01[row][col] = TBL[1]; TBL02[row][col] = TBL[2]; TBL03[row][col] = TBL[3]; TBL04[row][col] = TBL[4]; TBL05[row][col] = TBL[5]; TBL06[row][col] = TBL[6]; TBL07[row][col] = TBL[7]; TBL08[row][col] = TBL[8]; TBL09[row][col] = TBL[9]; TBL10[row][col] = TBL[10]; TBL11[row][col] = TBL[11]; TBL12[row][col] = TBL[12]; TBL13[row][col] = TBL[13]; TBL14[row][col] = TBL[14]; TBL15[row][col] = TBL[15]; W00[row][col] = W[0]; W01[row][col] = W[1]; W02[row][col] = W[2]; W03[row][col] = W[3]; W04[row][col] = W[4]; W05[row][col] = W[5]; W06[row][col] = W[6]; W07[row][col] = W[7]; W08[row][col] = W[8]; W09[row][col] = W[9]; W10[row][col] = W[10]; W11[row][col] = W[11]; W12[row][col] = W[12]; W13[row][col] = W[13]; W14[row][col] = W[14]; W15[row][col] = W[15]; EXP_IN00[row][col] = expIn[0] ; EXP_IN01[row][col] = expIn[1] ; EXP_IN02[row][col] = expIn[2] ; EXP_IN03[row][col] = expIn[3] ; EXP_IN04[row][col] = expIn[4] ; EXP_IN05[row][col] = expIn[5] ; EXP_IN06[row][col] = expIn[6] ; EXP_IN07[row][col] = expIn[7] ; EXP_IN08[row][col] = expIn[8] ; EXP_IN09[row][col] = expIn[9] ; EXP_IN10[row][col] = expIn[10]; EXP_IN11[row][col] = expIn[11]; EXP_IN12[row][col] = expIn[12] ; EXP_IN13[row][col] = expIn[13] ; EXP_IN14[row][col] = expIn[14] ; EXP_IN15[row][col] = expIn[15] ; } } Ry++; } // write debug data to bin file if (m_Debug) { writeDebugDataToBinFile("TBL", TBL00, TBL01, TBL02, TBL03, TBL04, TBL05, TBL06, TBL07, TBL08, TBL09, TBL10, TBL11, TBL12, TBL13, TBL14, TBL15); writeDebugDataToBinFile("W", W00, W01, W02, W03, W04, W05, W06, W07, W08, W09, W10, W11, W12, W13, W14, W15 ); writeDebugDataToBinFile("EXP_IN", EXP_IN00, EXP_IN01, EXP_IN02, EXP_IN03, EXP_IN04, EXP_IN05, EXP_IN06, EXP_IN07, EXP_IN08, EXP_IN09, EXP_IN10, EXP_IN11, EXP_IN12, EXP_IN13, EXP_IN14, EXP_IN15); // free memory for debug data for (int i=0; i &lt; m_Height; i++) { delete TBL00[i]; delete TBL01[i]; delete TBL02[i]; delete TBL03[i]; delete TBL04[i]; delete TBL05[i]; delete TBL06[i]; delete TBL07[i]; delete TBL08[i]; delete TBL09[i]; delete TBL10[i]; delete TBL11[i]; delete TBL12[i]; delete TBL13[i]; delete TBL14[i]; delete TBL15[i]; delete W00[i]; delete W01[i]; delete W02[i]; delete W03[i]; delete W04[i]; delete W05[i]; delete W06[i]; delete W07[i]; delete W08[i]; delete W09[i]; delete W10[i]; delete W11[i]; delete W12[i]; delete W13[i]; delete W14[i]; delete W15[i]; delete EXP_IN00[i]; delete EXP_IN01[i]; delete EXP_IN02[i]; delete EXP_IN03[i]; delete EXP_IN04[i]; delete EXP_IN05[i]; delete EXP_IN06[i]; delete EXP_IN07[i]; delete EXP_IN08[i]; delete EXP_IN09[i]; delete EXP_IN10[i]; delete EXP_IN11[i]; delete EXP_IN12[i]; delete EXP_IN13[i]; delete EXP_IN14[i]; delete EXP_IN15[i]; } delete TBL00; delete TBL01; delete TBL02; delete TBL03; delete TBL04; delete TBL05; delete TBL06; delete TBL07; delete TBL08; delete TBL09; delete TBL10; delete TBL11; delete TBL12; delete TBL13; delete TBL14; delete TBL15; delete W00; delete W01; delete W02; delete W03; delete W04; delete W05; delete W06; delete W07; delete W08; delete W09; delete W10; delete W11; delete W12; delete W13; delete W14; delete W15; delete EXP_IN00; delete EXP_IN01; delete EXP_IN02; delete EXP_IN03; delete EXP_IN04; delete EXP_IN05; delete EXP_IN06; delete EXP_IN07; delete EXP_IN08; delete EXP_IN09; delete EXP_IN10; delete EXP_IN11; delete EXP_IN12; delete EXP_IN13; delete EXP_IN14; delete EXP_IN15; } } </code></pre>
[]
[ { "body": "<p>I would have placed this as a comment, but it's too long.</p>\n\n<p>Here are some observations to make the code shorter and manageable:</p>\n\n<blockquote>\n <p>I know the code is long but most of it is params init</p>\n</blockquote>\n\n<p>The code is not only long, but also repetitive in some cases. These repetitions should be grouped by type and purpose (i.e. add some structures/classes to it, encapsulating data with the same purpose). That means, instead of having:</p>\n\n<pre><code>int** TBL00 = NULL;\nint** TBL01 = NULL;\n...\nint** TBL15 = NULL;\n</code></pre>\n\n<p>You should probably have:</p>\n\n<pre><code>struct tables {\n typedef int** table;\n table tables[16];\n\n tables(); // implement to allocate and initialize tables[0] .. tables[15]\n ~tables(); // implement to deallocate data\n};\n\n\ntables tbl; // use tbl.tables[0] to tbl.tables[15] instead\n</code></pre>\n\n<p>Also, check your use of allocations.</p>\n\n<p>Example for EXP_IN00 (all appearances):</p>\n\n<pre><code>int** EXP_IN00 = NULL;\n... \nEXP_IN00 = new int*[m_Height];\n... \nfor (int i=0; i &lt; m_Height; i++) \n...\n EXP_IN00[i] = new int[m_Width];\n...\nEXP_IN00[row][col] = expIn[0] ;\n...\nfor (int i=0; i &lt; m_Height; i++) \n...\n delete EXP_IN00[i]; // invalid\n...\ndelete EXP_IN00; // invalid\n</code></pre>\n\n<p>Because you are allocating arrays, you should use <code>delete[]</code> <em>variable</em> instead of <code>delete</code> <em>variable</em>. Otherwise, the results are undefined.</p>\n\n<p>You should also place all arrays inside RAII wrappers. Then, you can get rid of all the deletes.</p>\n\n<p><strong>Edit</strong>: A few notes about the performance:</p>\n\n<p>The performance of this function can be split in two parts: time taken by the allocations, and time taken by the computations.</p>\n\n<p>For the allocations, if you can, consider using static allocation (where possible), extracting the data into common types where you can optimize the allocation separately (see my tables example above), and allocating the buffers separately, as members of <code>CAlgo</code> (I assume here that CAlgo is a class, not a namespace).</p>\n\n<p>For the computations, I am not familiar with the API itself. You will have to measure each, pick the worst offender, and post the code, asking people for concrete advice on making it faster.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T12:25:50.137", "Id": "43054", "ParentId": "43033", "Score": "6" } }, { "body": "<p>The code you wrote is quite nasty. These are some suggestions:</p>\n\n<ul>\n<li>Do not use manual dynamic memory unless you really need it and you're skilled with: use smart pointers*. Performance impact is very small; considering their safety, they worth it, though.<br>\nRemember always that <code>new</code> could throw a <code>bad_alloc</code>, which should be caught and eventually handled.</li>\n<li>Do not use C-style arrays: <code>std::vector</code> is much better. You're using C++. Use STL. If you believe its overhead is too big, use <code>std::array</code> which is kind of faster than <code>std::vector</code>, but it has less features, since it's basically a safe wrapper for C-style arrays.</li>\n<li>Do not use <code>NULL</code>: we have got <code>nullptr</code>*, which is way better than an integer.</li>\n<li><em>Reduce</em> variables number, you're using tons of them. (some are probably even useless).</li>\n<li>Use <code>std::thread</code>*, which can even give you a native handler if you need to take over, always unless you need something only OpenMP can give you.</li>\n</ul>\n\n<p><sub>* Features available since C++11</sub></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T13:31:00.540", "Id": "43059", "ParentId": "43033", "Score": "5" } } ]
{ "AcceptedAnswerId": "43054", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T08:11:12.253", "Id": "43033", "Score": "1", "Tags": [ "c++", "optimization", "matrix" ], "Title": "Performance with C++ algorithm" }
43033
<p>I made a PHP mailer script does the basic validation of fields, return errors, else submit if all is good. But it also has a honeypot field that is not required to be filled in (I'm assuming by hiding it using CSS a spambot will fill in the field anyway). If the field is not empty, it opens a text file and writes/appends the attempt on it, and it also sends an email alert of the attempt.</p> <pre><code>&lt;?php //print_r($_POST); $error['name'] =""; $error['company']=""; $error['email'] =""; $error['subject'] =""; $error['message'] =""; $error['website'] =""; $success = ""; $thistime = time(); $current_date = date('m/d/Y/T ==&gt; H:i:s'); if(isset($_POST['_save'])) { $name = stripslashes($_POST['name']); $email = stripslashes($_POST['email']); $company = stripslashes($_POST['company']); $message = stripslashes($_POST['message']); $subject = stripslashes($_POST['subject']); $website = stripslashes($_POST['website']); if (empty($name) || empty($email) || empty($subject) || empty($message) || !empty($website)) { if (empty($name)) $error['name'] = "Please enter your Full Name"; if (empty($email)) $error['email'] = "Please enter a valid Email Address"; if (empty($company)) $error['company'] = "Please enter Your Company Name"; if (empty($subject)) $error['subject'] = "Please Write a Subject"; if (empty($message)) $error['message'] = "Please write a message, inquiries or other concerns above"; if (!empty($website)) // this is the honeypot $error['subject'] = "Opps looks like you're a spambot. You just filled in a not required field.; $myFile = "botlog.txt"; $fh = fopen($myFile, 'a') or die("can't open file"); $stringData = "bot trapped" . " " . "-" . " " . $website . " " . "- " . " " . $current_date . "\r\n"; fwrite($fh, $stringData); fclose($fh); $donot="donotreply@example.com"; $headers="From: {$email}\r\nReply-To: {$donot}"; //create headers mail('opps@example.com',$headers,$stringData); } else { //if not empty stripslashes($headers); $headers="From: {$email}\r\nReply-To: {$email}"; //create headers $content="Name: ".$name."\r\n\r\nCompany: " .$company."\r\n\r\nSubject: ".$subject."\r\n\r\nMessage: ".$message; mail('opps@example.com',$subject,$content,$headers); //mails it $success = "Thank you! You're email has been sent."; #done; } } ?&gt; </code></pre> <p>Am I doing it right? Does this open any vulnerabilities? I'm open to any suggestions and improvements.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T16:52:03.223", "Id": "74322", "Score": "0", "body": "You have some mismatched double quotes. Please recheck your code?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T11:58:47.683", "Id": "74426", "Score": "1", "body": "Your comment to @amon's answer says that you've deleted some \"unnecessary\" code to keep the fragment relatively short for your post. Especially since the deletion seems to have introduced some bugs, how do you know that the code you deleted doesn't contain security flaws? If you want to review code for security, you need to review *all* the code. When you delete code because \"that part couldn't possibly contain a security issue\" -- how do you know? If you were perfect at identifying security issues, you wouldn't be asking here!" } ]
[ { "body": "<p>There are no security vulnerabilities per se present, as far as I can see (however, <a href=\"https://codereview.stackexchange.com/a/43091/21609\">200_success did find one rather important one</a>). But if you're security-conscious, you would probably want to practice <em>defensive programming</em>, which implies careful input validation and eschewing potentially buggy constructs.</p>\n\n<p>One of the potentially buggy constructs in many languages is using an <code>if</code> with a single statement: Instead of </p>\n\n<pre><code>if (!empty($website)) // this is the honeypot\n $error['subject'] = \"Opps looks like you're a spambot. You \n just filled in a not required field.;\n $myFile = \"botlog.txt\";\n $fh = fopen($myFile, 'a') or die(\"can't open file\");\n $stringData = \"bot trapped\" . \" \" . \"-\" . \" \" . $website . \" \" . \"-\n \" . \" \" . $current_date . \"\\r\\n\";\n fwrite($fh, $stringData);\n fclose($fh);\n $donot=\"donotreply@whatever.com\";\n $headers=\"From: {$email}\\r\\nReply-To: {$donot}\"; //create headers\n mail('opps@gmail.com',$headers,$stringData);\n</code></pre>\n\n<p>use the (mostly) equivalent:</p>\n\n<pre><code>// this is the honeypot\nif (!empty($website)) {\n $error['website'] = \"Opps looks like you're a spambot. You just filled in a not required field.\";\n}\n$myFile = \"botlog.txt\";\n$fh = fopen($myFile, 'a') or die(\"can't open file\");\n$stringData = \"bot trapped - $website - \\n\"\n . \"$current_date\\r\\n\";\nfwrite($fh, $stringData);\nfclose($fh);\n$return_address = \"donotreply@whatever.com\";\n$headers = \"From: {$email}\\r\\n\"\n . \"Reply-To: {$return_address}\";\nmail('opps@gmail.com', $headers, $stringData);\n</code></pre>\n\n<p>Oh! This means that we log <em>any</em> error as a “trapped bot”. Is this what you intended? Surely not.</p>\n\n<p>Some other things I improved:</p>\n\n<ul>\n<li><p>Don't contain literal newlines in your strings. Each string literal should not span multiple lines. If you need a newline inside a string, use the escaped version. If a string is too long for one line, then use one string literal per line and concatenate them.</p></li>\n<li><p>Do not use excessive concatenation without any use (i.e. <code>\"bot trapped\" . \" \" . \"-\" . \" \" . $website . \" \" . \"- \" . \" \" . $current_date . \"\\r\\n\"</code>). Joining those literals makes your source code more readable.</p></li>\n<li><p>You logged an website error as <code>$error['subject']</code>, not as <code>$error['website']</code>. This indicates you've never tested your code to see how it handles various kinds of errors.</p></li>\n<li><p>You forgot the closing quote for the string literal <code>\"Opps looks like ... field.;</code>. Did this code ever run?</p></li>\n</ul>\n\n<p>And now regarding your anti-bot measures: A hidden honey-pot field is <em>not</em> a good solution:</p>\n\n<ul>\n<li>A sufficiently advanced bot may very well be able to detect that it's hidden via CSS (e.g. <code>style=\"display:none\"</code> is as obvious as it gets).</li>\n<li>A normal user might be using a browser with limited support for CSS, and may subsequently see the honeypot field and decide to fill it out. Examples where this is likely is a visually impaired visitor using assistive technologies, or someone using a command-line browser like <code>lynx</code> for some reason.</li>\n</ul>\n\n<p>Instead, use a proper captcha, either from an external provider (e.g. <a href=\"http://www.google.com/recaptcha\" rel=\"nofollow noreferrer\">recaptcha</a>), or use a very simple task for the challenge (e.g. “Check the radio button with the value three: o 1+3 o 4-1 o 6”).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T10:34:09.137", "Id": "74258", "Score": "0", "body": "Well said #amon. You have a keen eye. Yes I have tested it and it runs. I made an error as I deleted some unnecessary stuff like images and I deleted the end of statement as well. I didn't want to put those on here as they lengthen the codes. Sorry about that. $error['subject'] still displays the error though. So it worked. Very good pointers. Actually I like replies like yours as they take every detail into account. That's what makes it more interesting as I begin to trace the errors I did as a newbie to php. Still learning and it's been fun. Thanks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T10:38:56.063", "Id": "74259", "Score": "0", "body": "This is actually a test project trying to using honeypots. I will however use recaptcha. But my question is this. Do honeypot traps really work? Some of them say that captchas don't work anymore as there are more advanced scripts that get away with it. Furthermore, what can we do about the actual humans working in China's sweatshops sending spam for cents? I know that may have to be in a different discussion or forum altogether but.. just saying." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T10:50:34.753", "Id": "74263", "Score": "0", "body": "@wolverene Food for thought: Who are you defending against? Captchas are intended as an automated Turing test, and are used to defend against bots. If you want to defend against spam, a spam filter which processes the message contents would be more useful. Also: what failures are acceptable? Is it an success when you've intercepted 50% of bots? 90%? Would your defenses still work if I write a bot specifically for your site? (Unfortunately, such questions about security are off topic on this site. You may have more luck on [security.se])" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T14:53:05.980", "Id": "74451", "Score": "0", "body": "Point taken. All thoughts digested. I appreciate all the info. Thanks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T14:59:50.583", "Id": "74454", "Score": "0", "body": "Will go fix up some things from all the opinions and see." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T10:21:11.123", "Id": "43045", "ParentId": "43037", "Score": "17" } }, { "body": "<p>The <a href=\"http://hu1.php.net/manual/en/function.mail.php\">mail function has a return value</a> which the code could handle:</p>\n\n<blockquote>\n <p>Returns <code>TRUE</code> if the mail was successfully accepted for delivery, <code>FALSE</code> otherwise. </p>\n</blockquote>\n\n<p>So, when it returns <code>FALSE</code> the following success message definitely is not right:</p>\n\n<pre><code> mail('opps@gmail.com',$subject,$content,$headers); //mails it\n $success = \"Thank you! You're email has been sent.\";\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T15:03:12.970", "Id": "74456", "Score": "1", "body": "Yes, I have jumbled up too much having it make no sense at all. I'm trying to clean up the code as I go. Thank you." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T10:41:25.320", "Id": "43047", "ParentId": "43037", "Score": "8" } }, { "body": "<p>One thing you will also need to worry about is <a href=\"http://en.wikipedia.org/wiki/Cross-site_request_forgery\" rel=\"nofollow\">CSRF attacks</a></p>\n\n<p>The most basic implementation to protect against that is to generate a random token everytime the form is loaded, save that into <code>$_SESSION</code>, put that token into a hidden field in the form, then checking that the form submission has that token and matches the one saved in <code>$_SESSION</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T14:56:22.350", "Id": "74452", "Score": "0", "body": "hmmm. this honeypot thing is opening a can of worms. thanks." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T15:13:48.990", "Id": "43066", "ParentId": "43037", "Score": "1" } }, { "body": "<p>Your mailer is vulnerable to a <a href=\"http://www.securephpwiki.com/index.php/Email_Injection\">header-splitting attack</a>! (Also known as a CRLF-injection attack.)</p>\n\n<p>Basically, if one of the fields contains a <kbd>CR</kbd><kbd>LF</kbd>, the attacker can insert any arbitrary header into the generated message. For example, if the <code>email</code> parameter is</p>\n\n<pre><code>victim1@example.com%0d%0aCc:%20victim2@example.net\n</code></pre>\n\n<p>… then you will compose a message with headers</p>\n\n<pre><code>From: victim1@example.com\nCc: victim2@example.net\nReply-To: victim1@example.com\nCc: victim2@example.net\n</code></pre>\n\n<p>PHP's <code>mail()</code> function will \"helpfully\" add <code>victim2@example.net</code> as a spam recipient. The spam will look like it came from <code>victim1@example.com</code>.</p>\n\n<p>The simplest mitigation, I believe, is to pass all of the header fields through\n<a href=\"http://php.net/mb_encode_mimeheader\"><code>mb_encode_mimeheader()</code></a> first.</p>\n\n<hr>\n\n<blockquote>\n <h3>General warning regarding string concatenation and interpolation</h3>\n \n <p><strong>Any time you compose a string that will be interpreted by another computer system,</strong> be it an e-mail message, HTML page, or SQL query, <strong>assume that you are vulnerable to some kind of injection attack.</strong> Every single one of these \"human-friendly\" languages (as opposed to binary formats such as JPEG images) will have delimiters of special significance. Header-splitting, HTML/JavaScript injection, and SQL injection attacks all have the same root cause: careless string concatenation or interpolation.</p>\n \n <p>Therefore, before concatenating or interpolating strings, stop and think: <em>\"What is the appropriate escaping mechanism that I should be using?\"</em> Better yet, ask: <em>\"Is there a higher-level library that will let me accomplish the task without low-level string manipulation?\"</em></p>\n</blockquote>\n\n<hr>\n\n<blockquote>\n <h3>RFC time!</h3>\n \n <p>I'm diving into a deeper technical discussion about why <code>mb_encode_mimeheader()</code> is my choice for escaping. If you get confused by this technical discussion, you can safely ignore this explanation and just filter all the input through <code>mb_encode_mimeheader()</code>.</p>\n \n <p>There are actually two relevant standards for e-mail headers. Mail Transfer Agents (MTAs) care about <a href=\"https://www.ietf.org/rfc/rfc2822.txt\">RFC 2822</a>. Mail User Agents (MUAs) care about <a href=\"https://www.ietf.org/rfc/rfc2047.txt\">RFC 2047</a>.</p>\n \n <p>MTAs are completely oblivious to MIME encoding. As long as they see the headers they need (e.g. \"From\", \"To\", \"Return-Path\"), and the headers contain a safe subset of ASCII, they are happy.</p>\n \n <p>MUAs, on the other hand, are more sophisticated, in that they have to handle non-ASCII text for the benefit of non-English users. For example, a \"Subject\" header could contain arbitrary text, such as \"¡Hóla!\". Such a Subject line should be encoded using</p>\n\n<pre><code>mb_encode_mimeheader(\"¡Hóla!\", \"UTF-8\", \"Q\");\n</code></pre>\n \n <p>as</p>\n\n<pre><code>=?UTF-8?Q?=C2=A1H=C3=B3la!?=\n</code></pre>\n \n <p>That is, by the way, the way to ensure that the <code>$subject</code> parameter is RFC 2047-compliant, as specified in the <a href=\"http://php.net/mail\"><code>mail()</code></a> documentation.</p>\n \n <p>What about headers that are relevant to both MTAs and MUAs, such as the \"From\" header? One might want to generate a header that looks to the user like</p>\n\n<pre><code>From: \"François Müller\" &lt;francois.mueller@example.com&gt;\n</code></pre>\n \n <p>Over the wire, such a header must be encoded, since it contains non-ASCII characters. One acceptable encoding would be</p>\n\n<pre><code>From: \"=?UTF-8?Q?Fran=C3=A7ois=20M=C3=BCller?=\" &lt;francois.mueller@example.com&gt;\n</code></pre>\n \n <p>Such an encoding satisfies both RFC 2822 (since the MTA sees an opaque ASCII string between the double-quotes) and RFC 2047 (since the MUA should know how to decode the MIME-encoded string for display). To achieve such a result, you would need PHP code such as</p>\n\n<pre><code>$from_header = sprintf('From: \"%s\" &lt;%s&gt;',\n mb_encode_mimeheader(\"François Müller\", \"UTF-8\", \"Q\"),\n \"francois.mueller@example.com\");\n</code></pre>\n \n <p>If you write your code as</p>\n\n<pre><code>$email = '\"François Müller\" &lt;francois.mueller@example.com&gt;';\n$from_header = mb_encode_mimeheader(\"From: $email\", \"UTF-8\", \"Q\");\n</code></pre>\n \n <p>… you'll get</p>\n\n<pre><code>From: =?UTF-8?Q?=22Fran=C3=A7ois=20M=C3=BCller=22=20=3Cfrancois=2Emueller?=\n =?UTF-8?Q?=40example=2Ecom=3E?=\n</code></pre>\n \n <p>… which is wrong, since the MTA sees one opaque ASCII string that does not look like a valid e-mail address. However, the main point is that such code, though simplistic, is <em>not vulnerable</em> to header injection. As long as the <code>$email</code> variable contains simple ASCII text, it will work. For example,</p>\n\n<pre><code>$email = '&lt;francois.mueller@example.com&gt;';\n$from_header = mb_encode_mimeheader(\"From: $email\", \"UTF-8\", \"Q\");\n</code></pre>\n \n <p>… passes the text through unchanged, producing</p>\n\n<pre><code>From: &lt;francois.mueller@example.com&gt;\n</code></pre>\n</blockquote>\n\n<hr>\n\n<blockquote>\n <h3>PHP-bashing time!</h3>\n \n <p>As is often the case with PHP, the <code>mail()</code> function is poorly designed, such that it is easy to fall into this trap. Expecting programmers to know the RFCs and take the time to encode all of the headers properly is pure madness! If <code>mail()</code> were designed such that it accepted an associative array of (header name → header value) pairs, then it could automatically apply mitigation against header-splitting attacks.</p>\n</blockquote>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T15:02:19.593", "Id": "74455", "Score": "1", "body": "jeepers, it gets to be more interesting than ever. But very keen. I don't even understand most of them but looking up more info on them would prove to be fruitful. Much appreciated." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T21:01:37.247", "Id": "74489", "Score": "2", "body": "I know, it's not an obvious bug, but it is extremely important to fix it. Think over the advice, and feel free to ask for clarification. I encourage you to post a follow-up question with your revised code to make sure you got it right." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T19:21:00.973", "Id": "43091", "ParentId": "43037", "Score": "19" } }, { "body": "<p>This call to <code>stripslashes()</code> makes no sense:</p>\n\n<pre><code>stripslashes($headers); # ← Calling stripslashes() on an\n # undefined variable\n$headers=\"From: {$email}\\r\\nReply-To: {$email}\"; # ← Why bother, if you're going to\n # assign to $headers immediately\n # afterwards anyway?\n</code></pre>\n\n<p>Either you misunderstand what <code>stripslashes()</code> is for, or you're being careless.</p>\n\n<p>I'm dissatisfied with all these calls to <code>stripslashes()</code> as well:</p>\n\n<pre><code>$name = stripslashes($_POST['name']);\n$email = stripslashes($_POST['email']);\n$company = stripslashes($_POST['company']);\n$message = stripslashes($_POST['message']);\n$subject = stripslashes($_POST['subject']);\n$website = stripslashes($_POST['website']);\n</code></pre>\n\n<p>The <code>magic_quotes_gpc</code> debacle is a fundamental problem with PHP, and therefore deserves to be dealt with systemically rather than on an <em>ad hoc</em> basis. If you think that you might run this code on a server with magic quotes enabled, take <a href=\"http://www.php.net/manual/en/security.magicquotes.disabling.php#91585\" rel=\"nofollow\">this suggestion</a> to include a preamble code block that conditionally calls <code>stripslashes()</code>:</p>\n\n<pre><code>if (get_magic_quotes_gpc()) {\n function stripslashes_gpc(&amp;$value)\n {\n $value = stripslashes($value);\n }\n array_walk_recursive($_GET, 'stripslashes_gpc');\n array_walk_recursive($_POST, 'stripslashes_gpc');\n array_walk_recursive($_COOKIE, 'stripslashes_gpc');\n array_walk_recursive($_REQUEST, 'stripslashes_gpc');\n}\n</code></pre>\n\n<p>Calling <code>stripslashes()</code> unconditionally, as you have done, is bad practice. If your server has magic quotes disabled (as is recommended these days), then you'll mangle your input, removing backslashes that should be there. If your server has magic quotes enabled (which is considered an obsolescent practice), then reconfiguring your server to conform to modern recommendations will break your code. Either way, you lose! <strong>Keep in mind that <a href=\"http://www.php.net/manual/en/info.configuration.php#ini.magic-quotes-gpc\" rel=\"nofollow\">magic quotes are deprecated as of PHP 5.3 and removed altogether as of PHP 5.4.</a></strong></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T14:58:12.280", "Id": "74453", "Score": "0", "body": "Yes, I am being careless as a newbie. Glad I shared this on here to get all the opinions from experts. Will try all the suggestions to fit. Thanks." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T02:39:08.353", "Id": "43113", "ParentId": "43037", "Score": "4" } }, { "body": "<p>You set Reply-To: to \"donot@whatever.com\". whatever.com is registered to a company called Dreamissary in Montebello, California. Is that you? If not, you have no business to be redirecting email to them. A user who replies to the mail, not realising that their reply will be sent to a third party may well breach confidentiality of whatever information was sent in the message so this is a security issue. It's also obnoxious to direct junk mail at a third party. You should use an invalid address at your own domain for this purpose.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T14:49:16.557", "Id": "74450", "Score": "0", "body": "Opps, sorry that is purely coincidental. I didn't realize there was such a company. I will edit the preview code accordingly." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T15:16:45.023", "Id": "74457", "Score": "3", "body": "@wolverene That one's registered, too. :-) The correct domain to use here is \"example.com\" (per [RFC2606](https://tools.ietf.org/html/rfc2606)), and then use an address at your actual domain in the production code." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T12:07:23.263", "Id": "43131", "ParentId": "43037", "Score": "3" } } ]
{ "AcceptedAnswerId": "43045", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T09:14:43.987", "Id": "43037", "Score": "26", "Tags": [ "php", "beginner", "security", "email" ], "Title": "Are there any open vulnerabilities in this mailer script?" }
43037
<pre><code>import java.util.*; import java.io.*; public class Player { Scanner read; PrintWriter write; private String playerid; private int playerscore; int x = 0; ArrayList&lt;String&gt; n = new ArrayList&lt;String&gt;(); ArrayList&lt;Integer&gt; s = new ArrayList&lt;Integer&gt;(); List&lt;Player&gt; players = new ArrayList &lt;Player&gt;(); public Player (String name, int score) { playerid = name; playerscore = score; } static class ScoreComparator implements Comparator &lt;Player&gt; { public int compare(Player lf1, Player lf2) { int scoreA = lf1.getScore (); int scoreB = lf2.getScore (); if (scoreA == scoreB) { return 0; } else if (scoreA &gt; scoreB) { return 1; } else { return -1; } } } public String getName() { return playerid; } public int getScore() { return playerscore; } public String toString () { return playerid+"\t "+playerscore; } public void loadScores() { try { read = new Scanner (new FileReader ("lbout.txt")); while (read.hasNext ()) { n.add (read.next ()); s.add(read.nextInt ()); } System.out.println(n); System.out.println(s); } catch (FileNotFoundException fnfe) { System.out.println(fnfe+": FILE NOT FOUND!"); } catch (InputMismatchException ime) { System.out.println(ime+": INVALID DATA!"); } catch (Exception e) { System.out.println(e); } } public void evaluateScores() { try { loadScores (); n.add (playerid); s.add(playerscore); // sortScores(); int u; int max = 5; for (u = 0; u &lt; n.size (); ++u) { players.add(new Player (n.get (u),s.get (u))); } Collections.sort (players, Collections.reverseOrder (new Player.ScoreComparator())); for (int j = 0; j &lt; max; ++j) { System.out.println("\t "+players.get(j)); } ArrayList &lt;Player&gt; arr = new ArrayList&lt;Player&gt;(); for (int y = 0; y &lt; players.size (); ++y) { arr.add(players.get(y)); //I tried to pass the players as an argument to the GUI class but I get an error saying there's a conflict between util and awt so I copied it to an ArrayList } System.out.println("Print arr:" +arr); write = new PrintWriter ("lbout.txt"); for (int z = 0; z &lt; n.size (); ++z) { write.print(n.get(z)+" "); write.println (s.get(z)); } write.close (); //displayScores(); } catch (InputMismatchException ime) { System.out.println(ime+": INVALID DATA!"); } catch (Exception e) { System.out.println(e); } } } </code></pre> <p>As you can see, my code (aside from the fact that it isn't highly efficient but I'm not worrying about that at the moment, newbie here) only takes two parameters: one for the <strong><em>winner's</em></strong> name, the other the <strong><em>winner's</em></strong> score. What I'm trying to do is add not only the winner's name and score, but also the loser's, or in other words both of the players' info, but I'm not sure how I will proceed.</p> <p>So far:</p> <pre><code>public class PlayerTry { private String playeridA; private String playeridB; private int playerscoreA; private int playerscoreB; public PlayerTry (String name1, String name2, int score1, int score2) { playeridA = name1; playeridB = name2; playerscoreA = score1; playerscoreB = score2; } //Actually PlayerTry is a separate class and it's some sort of my draft space in case I mess up so at least I don't mess up my original code as well. } </code></pre> <p>Then they will be added to the <code>n</code> and <code>s</code> list with the other loaded info from the txt file.</p> <p>I'm not sure about the <code>getName()</code>, <code>getScore()</code>. Should I create separate <code>getName()</code> and <code>getScore()</code> methods for each of the passed players' info?</p> <p>Hints/suggestions would be appreciated!</p> <hr> <p>EDIT: My program no longer implements the Comparable interface by the way, since I would only be needing for the players' scores to be sorted out, order of names are disregarded.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T10:16:14.700", "Id": "74252", "Score": "2", "body": "This is technically working code (I assume - haven't tried it) but you are still asking \"How to add both player's score\". This should be in StackOverflow since your program doesn't work the way you want." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T10:25:40.967", "Id": "74255", "Score": "0", "body": "There are some improvements to be done I will end my review soon and paste code. Please keep that question in that forum." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T10:29:02.647", "Id": "74256", "Score": "0", "body": "@Max i asked this first on stackoverflow but i was redirected here. It does work but it's OOP so yeah some parts aren't present" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T20:19:15.283", "Id": "74348", "Score": "0", "body": "@lira79915220 Please post the link to the SO question, I can take a look at it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-03T13:42:07.160", "Id": "74725", "Score": "0", "body": "@SimonAndréForsberg http://stackoverflow.com/questions/22090967/high-score-list-adding-info-from-two-players" } ]
[ { "body": "<p>This is my code review. I added new class ScoringEngine please look on it. There can be made more but you have to specify what you want to achieve. I added some comments in classes.</p>\n\n<pre><code>public class Player // implements Comparable&lt;Player&gt; there is no need to implement that interface because you use different comparator implemented in GameEngine class\n{\n private String playerid;\n private int playerscore;\n\n int x = 0;\n List&lt;String&gt; n = new ArrayList&lt;String&gt;();\n List&lt;Integer&gt; s = new ArrayList&lt;Integer&gt;();\n List&lt;Player&gt; players = new ArrayList &lt;Player&gt;();\n\n public Player (String name, int score)\n {\n playerid = name;\n playerscore = score;\n\n\n }\n public String getName()\n {\n return playerid;\n }\n\n public int getScore()\n {\n return playerscore;\n }\n\n public String toString ()\n {\n return playerid+\"\\t \"+playerscore;\n }\n\n\n\n /* public int compareTo(Player lf)\n {\n return getName ().compareTo (lf.getName ());\n }\n */\n\n}\n</code></pre>\n\n<p>ScoringEngine</p>\n\n<pre><code>public class ScoringEngine {\n //for general attention is that you can save and read your scores from different files.\n private Scanner read;\n private PrintWriter write;\n final String scoresFileName = \"lbout.txt\";\n public void evaluateScores()\n {\n try\n {\n List&lt;Player&gt; playerScores = loadScores();\n\n Collections.sort(playerScores, Collections.reverseOrder(new PlayerComparator()));\n\n for (Player player : playerScores)\n {\n System.out.println(\"\\t \"+player.getName()+ \" \" + player.getScore());\n }\n\n\n/* this can be removed I think\n\n ArrayList&lt;Player&gt; arr = new ArrayList&lt;Player&gt;();\n for (int y = 0; y &lt; players.size (); ++y)\n {\n arr.add(players.get(y));\n //I tried to pass the players as an argument to the GUI class but I get an error saying there's a conflict between util and awt so I copied it to an ArrayList\n }\n*/\n //filenames were the same so I replaced it with one value\n write = new PrintWriter(scoresFileName);\n\n for (Player player:playerScores)\n {\n write.print(player.getName()+\" \");\n final String lineSeparatorKey = \"line.separator\"; //nice trick to keep code indepentent from platform\n write.println (player.getScore() + System.getProperty(lineSeparatorKey));\n }\n //displayScores();\n }\n\n catch (InputMismatchException ime)\n {\n System.out.println(ime+\": INVALID DATA!\");\n }\n catch (Exception e)\n {\n System.out.println(e);\n }\n finally{ // remember to close all file descriptors or streams\n write.close();\n }\n }\n\n public List&lt;Player&gt; loadScores()\n {\n List&lt;Player&gt; scores = new ArrayList&lt;Player&gt;();\n FileReader source = null;\n\n try\n {\n\n source= new FileReader(scoresFileName);\n read = new Scanner(source);\n\n while (read.hasNext ())\n {\n Player player = new Player(read.next(),read.nextInt()); // this might throw exception because read.hasNext()\n // check weather only one reading can be made not two -&gt;read.next() and read.nextInt()... |\n // To repair it change format of stored data in your file with scores to keep data for one player in one line...\n }\n return scores;\n }\n catch (FileNotFoundException fnfe)\n {\n System.out.println(fnfe+\": FILE NOT FOUND!\");\n }\n catch (InputMismatchException ime)\n {\n System.out.println(ime+\": INVALID DATA!\");\n }\n catch (Exception e)\n {\n System.out.println(e);\n } finally{ //remember to close all streams and file descriptors\n assert source != null;\n try {\n read.close();\n source.close();\n } catch (IOException e) {\n System.out.println(\"PROBLEM WITH CLOSING FILE!\");\n }\n }\n return scores;\n }\n\n\n private class PlayerComparator implements Comparator&lt;Player&gt;\n {\n public int compare(Player lf1, Player lf2)\n {\n int scoreA = lf1.getScore ();\n int scoreB = lf2.getScore ();\n\n if (scoreA == scoreB)\n {\n return 0;\n }\n\n else if (scoreA &gt; scoreB)\n {\n return 1;\n }\n else\n {\n return -1;\n }\n }\n }\n\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T11:13:13.253", "Id": "74267", "Score": "1", "body": "Normally I find it easier to follow an answer if the comments aren't within the code. But welcome to Code Review, nice to have you here." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T11:19:40.847", "Id": "74268", "Score": "0", "body": "Sorry :) but it is readable. I was trying to do it simple." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T11:22:07.340", "Id": "74269", "Score": "0", "body": "Thanks for this! However I'm not sure if this is really the right place where I should be asking since I asked first on StackOverflow but I was told to ask it here. I was asking for hints/suggestions since my present code only takes info from a single player, the winner, but what I'm trying to achieve is take info from two players. If I'm doing things the wrong way do me a favor and point it out, newbie here, thanks!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T10:50:28.607", "Id": "43049", "ParentId": "43043", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T10:04:41.577", "Id": "43043", "Score": "2", "Tags": [ "java" ], "Title": "High score list - adding info from two players" }
43043
<p>I have built the following code to download stock data from Yahoo Finance. The plan is to then use the built-in <code>pandas</code> functions to calculate metrics from this data that will then be used as features for classification. I also try to calculate whether or not the asset performed better, worse, or equal to the median asset during the next month. I then want to shift this piece of information back to the month the metrics where calculated for. Then from this create a dataset that can be used in a classification algorithm to see if the metrics have any predictive power for whether or not the stock will outperform the median stock for the next month.</p> <p>I'm new to Python and I feel my code is clunky and inefficient, so I was wondering if anyone could see any obviously better/smoother ways to do this.</p> <p>My second issue is that I'm not sure if the "time" of the different metrics are preserved through my transformations. It's obvious that for a single sample in the future training set, the metrics all are calculated using the same n-datapoints back in time, and that the recording of whether or not the stock is a winner or loser actually is for that particular stock, one month ahead.</p> <pre><code>import pandas as pd import pandas.io.data as web names = ['AAPL','GOOG','MSFT'] # Functions def get_px(stock, start, end): return web.get_data_yahoo(stock, start, end)['Close'] def getWinners(stock, medRet, retsM): return retsM[stock].shift(-1) &gt;= medRet.shift(-1) def getStd(stock, rets, period): return pd.rolling_std(rets[stock],period).asfreq('BM').fillna(method='pad') pxlol = {n: get_px(n,'1/1/2006','1/1/2014') for n in names} px = pd.DataFrame(data={n: get_px(n,'1/1/2006','1/1/2014') for n in names}) px = px.asfreq('B').fillna(method = 'pad') rets = px.pct_change() # Start retsM = px.asfreq('BM').fillna(method = 'pad').pct_change() medRet = retsM.median(axis = 1) # Generating initial feature dataframes winners = pd.DataFrame({n: getWinners(n,medRet,retsM) for n in names}) stds = pd.DataFrame({n: getStd(n,rets,20) for n in names}) # Concatentating feature dataframes retsM = pd.concat(retsM[n] for n in names) winners = pd.concat(winners[n] for n in names) stds = pd.concat(stds[n] for n in names) # Main DataFrame mainDict = {'Returns':retsM, 'Std.Devs':stds, 'Winners':winners} frame = pd.DataFrame(mainDict) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T12:52:33.003", "Id": "74278", "Score": "0", "body": "I'm not all that familiar with the `pandas` package, but I believe `getWinners` should be more aptly named `getWinnersAndLosers` since it doesn't just filter out the losers." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-03T12:14:28.467", "Id": "74711", "Score": "0", "body": "That is true, the function has is poorly named, but that is not what I need help with." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T11:49:16.627", "Id": "43052", "Score": "1", "Tags": [ "python", "beginner", "pandas" ], "Title": "Generate features for future ML analysis of asset returns" }
43052
<p>I've refactored the string calculator kata as much as I could and tried to maintain single responsibility. Is there anything I could factor differently? The specs can be reviewed <a href="http://osherove.com/tdd-kata-1/" rel="nofollow">here</a>.</p> <pre><code>module StringCalculator def self.add(string) string.end_with?("\n") ? fail('ends in newline') : solve(string) end def self.solve(string) verify(string) custom = delimiter(string) numerics = string.gsub(/\n/, custom).split(custom).map(&amp;:to_i) numerics.reject { |n| n &gt; 1000 }.reduce(0, :+) end def self.delimiter(string) string[0, 2] == '//' ? string[2, 1] : ',' end def self.verify(string) find = string.scan(/-\d+/) fail("negatives not allowed: #{find.join(', ')}") if find.any? end private_class_method :verify, :delimiter, :solve end </code></pre> <p>More importantly, I've thought of a case that involves the delimiter of a string that begins with <code>//</code> to be a number (which is considered invalid). I've made a quick way of solving that issue like so. Any suggestions on that?</p> <p><strong>Invalid case:</strong></p> <pre><code>def self.delimiter(string) string[0, 2] == '//' ? check(string) || string[2, 1] : ',' end def self.check(string) fail("invalid delimiter: #{string[2, 1]}") if string[2, 1] =~ /[0-9]/ end </code></pre>
[]
[ { "body": "<p>I think your code is pretty good. The main opportunity for improved clarity I saw was to consolidate your validation code into one place. In your code, validations are sprinkled across various methods, so that you are mixing the responsibility of \"validation\" and \"work\". </p>\n\n<p>Here's a refactoring (not tested) which puts all the validation in one place, and gets it out of the way up front. That way, the actual \"work\" you are doing becomes simpler to express, because you know your inputs are clean and meet all your assumptions at that point.</p>\n\n<p>Also, note that you don't need to specify 0 as the first argument of <code>reduce</code>.</p>\n\n<pre><code>module StringCalculator\n\n def self.add(string)\n verify(string)\n delim = delimiter(string)\n numerics = string.gsub(/\\n/, delim).split(delim).map(&amp;:to_i)\n numerics.reject { |n| n &gt; 1000 }.reduce(:+)\n end\n\n #######################\n ## Verification Code\n #######################\n\n def self.verify(string)\n verify_doesnt_end_with_newline(string)\n verify_no_negatives(string)\n verify_custom_delim(string) if has_custom_delim?(string)\n end\n\n\n def self.verify_doesnt_end_with_newline(string)\n fail('ends in newline') if string.end_with?(\"\\n\")\n end\n\n def self.verify_no_negatives(string)\n find = string.scan(/-\\d+/)\n fail(\"negatives not allowed: #{find.join(', ')}\") if find.any?\n end\n\n def self.verify_custom_delim(string)\n custom_delim = get_custom_delim(string)\n fail(\"invalid delimiter: #{custom_delim}\") if custom_delim =~ /[0-9]/\n end\n\n #######################\n ## Delimiter Utilities\n #######################\n\n def self.delimiter(string)\n return ',' unless has_custom_delim?(string)\n get_custom_delim(string)\n end\n\n def self.has_custom_delim?(string)\n string[0, 2] == '//'\n end\n\n def self.get_custom_delim(string)\n string[2, 1]\n end\n\n private_class_method :verify, :verify_doesnt_end_with_newline, :verify_no_negatives, :verify_custom_delim, :delimiter, :has_custom_delim?, :get_custom_delim\nend\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T23:37:53.893", "Id": "74508", "Score": "1", "body": "Thanks for the feedback! The reason I have 0 as an initial value is because the spec says to return 0 for an empty string. Originally, I checked to see if the string was empty, with a early return. Then I realized that I didn't need to check, I could return 0 if there were no numbers to add within reduce. Good points on the validations as well. I'll consider these ideas!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T19:00:34.687", "Id": "43159", "ParentId": "43057", "Score": "1" } } ]
{ "AcceptedAnswerId": "43159", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T13:21:57.290", "Id": "43057", "Score": "2", "Tags": [ "ruby", "calculator" ], "Title": "Refactoring a String Calculator" }
43057
<p>I'm trying to reduce the complexity of some methods, and I'm not exactly sure what approach to take. I'm currently building a PHP wrapper for a REST API, and the main problematic class is here:</p> <p><a href="https://github.com/petrepatrasc/blizzard-starcraft-api/blob/master/Service/ApiService.php">https://github.com/petrepatrasc/blizzard-starcraft-api/blob/master/Service/ApiService.php</a></p> <p>In short, since data retrieved from the API is not always consistent, I have to do this:</p> <pre><code>$portrait = new Portrait(); $portrait-&gt;setXCoordinate(isset($apiData['portrait']['x']) ? $apiData['portrait']['x'] : null) -&gt;setYCoordinate(isset($apiData['portrait']['y']) ? $apiData['portrait']['y'] : null) -&gt;setWidth(isset($apiData['portrait']['w']) ? $apiData['portrait']['w'] : null) -&gt;setHeight(isset($apiData['portrait']['h']) ? $apiData['portrait']['h'] : null) -&gt;setOffset(isset($apiData['portrait']['offset']) ? $apiData['portrait']['offset'] : null) -&gt;setUrl(isset($apiData['portrait']['url']) ? $apiData['portrait']['url'] : null); return $portrait; </code></pre> <p>What would be a better way of handling the problem, so that the method complexity goes down? I suppose that I can try and catch an "undefined index exception", but I kind of wanted to see if there's something a bit more elegant that I can use.</p>
[]
[ { "body": "<p>You could remove some duplication with a <code>getPortraitValue</code> function:</p>\n\n<pre><code>function getPortraitValue($apiData, $key) {\n $portrait = $apiData['portrait'];\n if (isset($portrait[$key])) {\n return $portrait[$key];\n }\n return null;\n}\n\n$portrait = new Portrait();\n$portrait-&gt;setXCoordinate(getPortraitValue($apiData, 'x')\n -&gt;setYCoordinate(getPortraitValue($apiData, 'y'))\n -&gt;setWidth(getPortraitValue($apiData, 'w'))\n -&gt;setHeight(getPortraitValue($apiData, 'h'))\n -&gt;setOffset(getPortraitValue($apiData, 'offset')\n -&gt;setUrl(getPortraitValue($apiData, 'url');\nreturn $portrait;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T13:51:03.347", "Id": "74290", "Score": "1", "body": "Yep, was thinking the same thing at one point, but this solution is essentially just a wrapper for the inline if. I say this because it is in fact a tad incorrect - if $apiData['portrait'][$key] does not exist, you'll still get a \"Undefined index\" exception, so instead you have to do: if (isset($apiData['portrait'][$key])) return $apiData['portrait'][$key];" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T14:05:16.083", "Id": "74291", "Score": "0", "body": "@PetrePătraşc: Thank you, I've fixed that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T14:07:44.117", "Id": "74292", "Score": "0", "body": "I'll try running some code analysis on that and checking if the lack of ternary does bring it down." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T14:29:25.507", "Id": "74294", "Score": "0", "body": "Yep, you were right! Method has been improved! https://scrutinizer-ci.com/g/petrepatrasc/blizzard-starcraft-api/inspections/5855cf86-6839-4e4a-a1c2-3123e6acff72\n\nAccepting your answer, as it is the right solution." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T14:32:27.703", "Id": "74296", "Score": "0", "body": "@PetrePătraşc: Good to hear that, thanks :)" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T13:34:28.500", "Id": "43060", "ParentId": "43058", "Score": "4" } } ]
{ "AcceptedAnswerId": "43060", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T13:24:48.243", "Id": "43058", "Score": "5", "Tags": [ "php", "optimization", "api", "complexity" ], "Title": "Reducing complexity of method" }
43058
<p>I have some PHP code I'm working on which contains 2 queries and I need to set extra conditions for 2 out of 3 view options and one less query for 1 out of 3 view options.</p> <p>Basically, I'm rendering a history list of shows with three options ALL | PRO | UPCOMING. The ALL option should include both queries and have no extra conditions. The PRO option should have an extra condition with both queries. The UPCOMING option should have an extra condition but only one query.</p> <p>I've never built an <code>if else</code> statement with queries before, but I'm sure there is an easier way to make the code shorter.</p> <p>This PHP is also within an API that get pulled to the front end. Is there a way to render buttons on the front end to change the query from ALL to PRO or UPCOMING?</p> <pre><code> function get_shows($playid) { // There are two tables, so we will need to merge the results $results = array(); $count = ($this-&gt;input-&gt;get('count')) ? $this-&gt;input-&gt;get('count') : $this-&gt;max_results; $offset = ($this-&gt;input-&gt;get('offset')) ? $this-&gt;input-&gt;get('offset') : 0; $view = 'all'; // ALL if ($view == 'all') { $extra_condition = ""; //If ALL no extra condition needs to be set $query = $this-&gt;db-&gt;query("SELECT distinct customer.customerid as customerid, organization, vcity, vstate, vcountry, firstdate, lastdate FROM customer, orders, venue WHERE orders.ordersid=venue.ordersid AND orders.playid=? AND orders.active=1 AND customer.customerid=orders.customerid AND shipped != 0 AND defunct != 1 AND orders.lastdate != 0 AND (ordertype != 'misc' AND ordertype != 'reading') AND hidepic!=1 AND hideprod!=1 AND num_perf&gt;0 ORDER BY firstdate desc LIMIT $offset,$count", $playid); foreach ($query-&gt;result() as $row) { $results[] = array ( 'id' =&gt; $row-&gt;customerid, 'src' =&gt; 'customerid', 'organization' =&gt; $row-&gt;organization, 'city' =&gt; $row-&gt;vcity, 'state' =&gt; $row-&gt;vstate, 'country' =&gt; $row-&gt;vcountry, 'firstdate' =&gt; call_user_func($fmt_date, $row-&gt;firstdate), 'lastdate' =&gt; call_user_func($fmt_date, $row-&gt;lastdate) ); } // Legacy data from oldprods $query = $this-&gt;db-&gt;query("SELECT oldprodsid, organization, city, state, country, firstdate, lastdate FROM oldprods where playid=? ORDER BY firstdate desc LIMIT $offset,$count",$playid); foreach ($query-&gt;result() as $row) { $results[] = array ( 'id' =&gt; $row-&gt;oldprodsid, 'src' =&gt; 'oldprods', 'organization' =&gt; $row-&gt;organization, 'city' =&gt; $row-&gt;city, 'state' =&gt; $row-&gt;state, 'country' =&gt; $row-&gt;country, 'firstdate' =&gt; call_user_func($fmt_date, $row-&gt;firstdate), 'lastdate' =&gt; call_user_func($fmt_date, $row-&gt;lastdate) ); } // IF UPCOMING }else if ($view == 'upcoming') { $extra_condition = "AND lastdate &gt;= DATE_SUB(CURRENT_DATE,INTERVAL 0 DAY)"; //This line of code designates this as UPCOMING but omit the Legacy Query $query = $this-&gt;db-&gt;query("SELECT distinct customer.customerid as customerid, organization, vcity, vstate, vcountry, firstdate, lastdate FROM customer, orders, venue WHERE orders.ordersid=venue.ordersid AND orders.playid=? AND orders.active=1 AND customer.customerid=orders.customerid AND shipped != 0 AND defunct != 1 AND orders.lastdate != 0 AND (ordertype != 'misc' AND ordertype != 'reading') AND hidepic!=1 AND hideprod!=1 AND num_perf&gt;0 $extra_condition ORDER BY firstdate desc LIMIT $offset,$count", $playid); foreach ($query-&gt;result() as $row) { $results[] = array ( 'id' =&gt; $row-&gt;customerid, 'src' =&gt; 'customerid', 'organization' =&gt; $row-&gt;organization, 'city' =&gt; $row-&gt;vcity, 'state' =&gt; $row-&gt;vstate, 'country' =&gt; $row-&gt;vcountry, 'firstdate' =&gt; call_user_func($fmt_date, $row-&gt;firstdate), 'lastdate' =&gt; call_user_func($fmt_date, $row-&gt;lastdate) ); } // IF PRO }else if ($view == 'pro') { $extra_condition = "AND (ordertype = 'pro')"; //This line of code designates this as PRO along with the Legacy Query $query = $this-&gt;db-&gt;query("SELECT distinct customer.customerid as customerid, organization, vcity, vstate, vcountry, firstdate, lastdate FROM customer, orders, venue WHERE orders.ordersid=venue.ordersid AND orders.playid=? AND orders.active=1 AND customer.customerid=orders.customerid AND shipped != 0 AND defunct != 1 AND orders.lastdate != 0 AND (ordertype != 'misc' AND ordertype != 'reading') AND hidepic!=1 AND hideprod!=1 AND num_perf&gt;0 $extra_condition ORDER BY firstdate desc LIMIT $offset,$count", $playid); foreach ($query-&gt;result() as $row) { $results[] = array ( 'id' =&gt; $row-&gt;customerid, 'src' =&gt; 'customerid', 'organization' =&gt; $row-&gt;organization, 'city' =&gt; $row-&gt;vcity, 'state' =&gt; $row-&gt;vstate, 'country' =&gt; $row-&gt;vcountry, 'firstdate' =&gt; call_user_func($fmt_date, $row-&gt;firstdate), 'lastdate' =&gt; call_user_func($fmt_date, $row-&gt;lastdate) ); } // Legacy data from oldprods $query = $this-&gt;db-&gt;query("SELECT oldprodsid, organization, city, state, country, firstdate, lastdate FROM oldprods where playid=? ORDER BY firstdate desc LIMIT $offset,$count",$playid); foreach ($query-&gt;result() as $row) { $results[] = array ( 'id' =&gt; $row-&gt;oldprodsid, 'src' =&gt; 'oldprods', 'organization' =&gt; $row-&gt;organization, 'city' =&gt; $row-&gt;city, 'state' =&gt; $row-&gt;state, 'country' =&gt; $row-&gt;country, 'firstdate' =&gt; call_user_func($fmt_date, $row-&gt;firstdate), 'lastdate' =&gt; call_user_func($fmt_date, $row-&gt;lastdate) ); } } return array_slice($results, 0, $count); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T14:34:53.687", "Id": "74298", "Score": "0", "body": "Welcome to Code Review! Are you asking code to be written ? Here at Code Review, we are reviewing working and complete code. If you need help to code something this is not the good site." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T15:06:38.800", "Id": "74300", "Score": "0", "body": "I had working code but it's very long since the only way I could get things partially working was to have multiple duplicate queries. I have posted the original code above." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T15:21:28.257", "Id": "74302", "Score": "1", "body": "Thanks for the edit, the more important part of a review here is having a code that is working. That your code is long and not optimal is nothing to worry, Code Review is here to help you get to something better and hope to help you learn in the process." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-03T14:02:08.113", "Id": "74733", "Score": "0", "body": "@spencer7593 Spencer this is great and works perfectly. Reason I had set the $view='all' was to test the functionality of each view on the front end. This code works great but ideally I need to create buttons on the front end that would change the different views. If this was all part of the existing page it would be easy as I could link the page back to itself something like:\n`<a href=\"prodhistory.php?playid=$playid&view=pro\">PRO</a>`\nBut since this is in the API I can't do that. I'm wondering if there is a way to do it through javascript though via an onclick or onchange?" } ]
[ { "body": "<p>(What's curious is that you are setting <code>$view = 'all'</code>, and then immediately testing if it's set to <code>'upcoming'</code> or <code>'pro'</code>, I don't see any where else that <code>$view</code> is being assigned a value.)</p>\n\n<p>But, with that issue aside, it took me a bit to figure out that there are huge chunks of code that is replicated. (I actually copied chunks out and saved them as separate files, so I could run compares... and the blocks are IDENTICAL except for the <code>$extra_condition</code>, and the legacy query doesn't get run for <code>'upcoming'</code>, only for <code>'all'</code> and <code>'pro'</code>.</p>\n\n<p>I've minimally refactored your code to remove the replicated code. There's probably other changes that can be made, but in terms of a reader figuring out what this code does, removing the redundant code is the first priority.</p>\n\n<p>It would be MUCH easier on the reader if the identical query blocks weren't repeated. In the case of the <code>'all'</code> view, we can think of <code>$extra_condition</code> as really just an empty string. (The way it's coded below, you'll still get the line break and a bunch of spaces; I might format the query little differently, and include the additions to the WHERE clause a little differently, but I didn't want to change anything that didn't need to be changed.)</p>\n\n<p>Let's break the code into three sections:</p>\n\n<ul>\n<li>setting $extra_condition</li>\n<li>running the query block</li>\n<li>running the legacy query block</li>\n</ul>\n\n<p>To set <code>$extra_condition</code>, we test whether <code>$view</code> is set to <code>'all'</code>, <code>'upcoming'</code>, or <code>'pro'</code>, and assign the appropriate value. That makes it much easier to see what's going on, when it's set in one place, rather than being spread so far apart in the code.</p>\n\n<p>Then, we'll run the query block. (We don't need to repeat that same code block three times; the code is identical in each case. We just need to check (again) whether <code>$view</code> is set to the one of the three values.</p>\n\n<p>Next, there's a legacy query block that needs to run for two of the <code>$view</code> values. We have this block only once, rather than having two copies of the same code.</p>\n\n<p>The only real difference (and it's not really that different at all) in what gets executed is that the SQL text (query string) for the \"<code>all</code>\" case is getting an extra empty line. That's because we're including an empty <code>$extra_condition</code>. That extra line is just because of the way that it's getting incorporated into the SQL text. (We could just as easily include a dummy condition like <code>' AND 1=1 '</code>.)</p>\n\n<p>I wasn't able to post an answer on StackOverflow yesterday because your question got closed before I could post an answer. </p>\n\n<pre><code>&lt;?php\nfunction get_show_($playid)\n{\n\n // There are two tables, so we will need to merge the results for ALL and PRO\n $results = array();\n\n $count = ($this-&gt;input-&gt;get('count')) ? $this-&gt;input-&gt;get('count') : $this-&gt;max_results;\n $offset = ($this-&gt;input-&gt;get('offset')) ? $this-&gt;input-&gt;get('offset') : 0;\n $view = 'all';\n\n// SET ADDITIONS TO WHERE CLAUSE FOR QUERY BLOCK\n\n if ($view == 'all') {\n $extra_condition = \"\"; //no additions to the WHERE clause\n }else if ($view == 'upcoming') {\n $extra_condition = \"AND lastdate &gt;= DATE_SUB(CURRENT_DATE,INTERVAL 0 DAY)\"; //This line of code designates this as UPCOMING but omit the Legacy Query\n }else if ($view == 'pro') {\n $extra_condition = \"AND (ordertype = 'pro')\"; //This line of code designates this as PRO along with the Legacy Query\n }\n\n\n// RUN QUERY BLOCK\n\n if (($view == 'all') OR ($view == 'upcoming') OR ($view == 'pro')) {\n $query = $this-&gt;db-&gt;query(\"SELECT distinct customer.customerid as customerid, organization, vcity, vstate, vcountry, firstdate, lastdate\n FROM customer, orders, venue\n WHERE orders.ordersid=venue.ordersid\n AND orders.playid=? AND orders.active=1\n AND customer.customerid=orders.customerid\n AND shipped != 0\n AND defunct != 1\n AND orders.lastdate != 0\n AND (ordertype != 'misc'\n AND ordertype != 'reading')\n AND hidepic!=1\n AND hideprod!=1\n AND num_perf&gt;0\n $extra_condition\n ORDER BY firstdate desc\n LIMIT $offset,$count\", $playid);\n foreach ($query-&gt;result() as $row)\n {\n $results[] = array\n (\n 'id' =&gt; $row-&gt;customerid,\n 'src' =&gt; 'customerid',\n 'organization' =&gt; $row-&gt;organization,\n 'city' =&gt; $row-&gt;vcity,\n 'state' =&gt; $row-&gt;vstate,\n 'country' =&gt; $row-&gt;vcountry,\n 'firstdate' =&gt; call_user_func($fmt_date, $row-&gt;firstdate),\n 'lastdate' =&gt; call_user_func($fmt_date, $row-&gt;lastdate)\n );\n }\n }\n\n// RUN LEGACY QUERY BLOCK\n\n if ( ($view == 'all') OR ($view == 'pro') ) {\n\n // Legacy data from oldprods\n $query = $this-&gt;db-&gt;query(\"SELECT oldprodsid, organization, city, state, country, firstdate, lastdate\n FROM oldprods where playid=?\n ORDER BY firstdate desc\n LIMIT $offset,$count\",$playid);\n foreach ($query-&gt;result() as $row)\n {\n $results[] = array\n (\n 'id' =&gt; $row-&gt;oldprodsid,\n 'src' =&gt; 'oldprods',\n 'organization' =&gt; $row-&gt;organization,\n 'city' =&gt; $row-&gt;city,\n 'state' =&gt; $row-&gt;state,\n 'country' =&gt; $row-&gt;country,\n 'firstdate' =&gt; call_user_func($fmt_date, $row-&gt;firstdate),\n 'lastdate' =&gt; call_user_func($fmt_date, $row-&gt;lastdate)\n );\n }\n\n }\n return array_slice($results, 0, $count);\n}\n</code></pre>\n\n<p>That's just a lot less code for a reader to wade through. And, if requirements change, and we need to a add a column to the queries, we only have two queries to change, rather than five.</p>\n\n<p>There's a few other minor formatting changes I would make, but for this go around, I changed as few lines as possible. I removed a lot of redundant code, and just relocated and repeated just a few easy conditional tests.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T07:44:26.673", "Id": "43121", "ParentId": "43063", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T14:05:50.960", "Id": "43063", "Score": "2", "Tags": [ "php", "mysql" ], "Title": "Rendering a history list of shows with different options" }
43063
<p>Things that I'm not sure about:</p> <ol> <li>Whether this works in all use cases - alongside routing and within templates etc</li> <li>Am I polluting the scope with all these variables? This seems to be the easiest way to do unit tests - or should I be passing the vars into the function? Some ( documentHeight, USerScrolledTop, userScrolledBottom) are also generic to all - should they be contained / updated separately?</li> <li>Should I implement a scroll throttle?</li> <li>Logic assumes elements are written in order in the HTML (last directive hit will be overwritting the current <code>activeSpy</code> value)</li> <li>Is the broadcast/listen logic satisfactory, or should I specifically broadcast the <code>id</code> rather than the generic <code>spied</code>, removing the need for <code>if( scope.scrollspyListen === args.activeSpy )</code></li> <li>Things I don't know I should be unsure about</li> </ol> <p>Love to get some feedback on this module. Feel free to <a href="https://github.com/patrickmarabeas/ng-ScrollSpy.js" rel="nofollow">fork and whatnot over on GitHub</a> as well. <a href="http://patrickmarabeas.github.io/ng-ScrollSpy.js/" rel="nofollow">Demo</a>.</p> <hr> <pre><code>&lt;nav&gt; &lt;span class="item" data-scrollspy-listen="newyork"&gt;New York&lt;/span&gt; &lt;span class="item" data-scrollspy-listen="london"&gt;London&lt;/span&gt; &lt;span class="item" data-scrollspy-listen="sydney"&gt;Sydney&lt;/span&gt; &lt;/nav&gt; &lt;section id="newyork" data-scrollspy-broadcast&gt;&lt;/section&gt; &lt;section id="london" data-scrollspy-broadcast&gt;&lt;/section&gt; &lt;section id="sydney" data-scrollspy-broadcast&gt;&lt;/section&gt; </code></pre> <hr> <pre><code>'use strict'; angular.module( 'ngScrollSpy', [] ) .directive( 'scrollspyBroadcast', [ '$rootScope', function( $rootScope ) { return { restrict: 'A', scope: {}, link: function( scope, element, attrs ) { scope.activate = function() { scope.documentHeight = Math.max( document.body.scrollHeight, document.body.offsetHeight, document.documentElement.clientHeight, document.documentElement.scrollHeight, document.documentElement.offsetHeight ); //distance down the page the top of the window is currently at scope.userScrolledTop = ( window.pageYOffset !== undefined ) ? window.pageYOffset : ( document.documentElement || document.body.parentNode || document.body ).scrollTop; //distance down the page the bottom of the window is currently at scope.userScrolledBottom = scope.userScrolledTop + window.innerHeight; scope.elementOffsetTop = element[0].offsetTop; scope.elementOffsetBottom = scope.elementOffsetTop + Math.max( element[0].scrollHeight, element[0].offsetHeight ); scope.triggerOffset = 150; //determine if element needs to be triggered by the top or bottom of the window if( ( scope.elementOffsetTop - scope.triggerOffset ) &lt; ( scope.documentHeight - window.innerHeight ) ) { if( scope.elementOffsetTop &lt;= ( scope.userScrolledTop + scope.triggerOffset ) ) { $rootScope.$broadcast( 'spied', { 'activeSpy': attrs.id }); } } else { if( scope.userScrolledBottom &gt; ( scope.elementOffsetBottom - scope.triggerOffset ) ) { $rootScope.$broadcast( 'spied', { 'activeSpy': attrs.id }); } } }; angular.element( document ).ready( function() { scope.activate(); }); angular.element( window ).bind( 'scroll', function() { scope.activate(); }); } } }]) .directive( 'scrollspyListen', [ '$rootScope', function( $rootScope ) { return { restrict: 'A', scope: { scrollspyListen: '@', enabled: '@' }, replace: true, transclude: true, template: function( element, attrs ) { var tag = element[0].nodeName; return '&lt;'+tag+' data-ng-transclude data-ng-class="{active: enabled}"&gt;&lt;/'+tag+'&gt;'; }, link: function( scope, element, attrs ) { $rootScope.$on('spied', function(event, args){ scope.enabled = false; if( scope.scrollspyListen === args.activeSpy ) { scope.enabled = true; } if( !scope.$$phase ) scope.$digest(); }); } } }]); </code></pre>
[]
[ { "body": "<p>Nice work!<br/>\nI presume the complicated way of getting the right element measurements is to cater for many browsers, won't comment on that.</p>\n\n<ul>\n<li><p>I would add some comments on the nature of the 'magic number' \n<code>scope.triggerOffset = 150;</code> or, better, encapsulate it away as <code>.constant</code> or offer as configurable option, to make your directive more re-usable.</p></li>\n<li><p>I find the use of <code>ng-class</code> directive with <code>transclusion</code> inside another directive a bit too complicated. If I understand it right, you don't really need to change the DOM, so don't need a template. All you do is assigning a <code>class</code>, which can be done directly inside your <code>link</code> function.</p></li>\n<li><p>This is actually an Anti-Pattern, see <a href=\"https://github.com/angular/angular.js/wiki/Anti-Patterns\" rel=\"nofollow noreferrer\">here</a>:</p>\n\n<p><code>if( !scope.$$phase ) scope.$digest();</code></p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-22T14:02:04.173", "Id": "83936", "Score": "0", "body": "Thanks, there are many more Angular submissions you can review ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-22T15:15:41.163", "Id": "83961", "Score": "0", "body": "Thanks for the points, Haven't had the time of late to push some changes I've been meaning to implement. I'll have to revisit `!scope.$$phase` and see what was going on there. Hopefully I'll get to posting a newer version in the next few days. I would be interested in whether http://codereview.stackexchange.com/q/42254/36695 is a good config implementation - it was what I was planning on replicating for this module as well..." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2014-04-22T13:48:55.363", "Id": "47882", "ParentId": "43064", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T14:37:11.437", "Id": "43064", "Score": "6", "Tags": [ "javascript", "angular.js", "modules" ], "Title": "Improvements to an Angular ScrollSpy module" }
43064
<p>For several months I'm working with JavaScript and <code>THREE.JS</code> library. Firstly I dislike the prototype-based programming because I have to work a lot of with class-oriented languages, where any class is represented as the type and there is a strict separation between declaration and behavior of program design.</p> <p>But, I understood that prototype-based way is fine for JavaScript, just because it's normally for this way of web-development.</p> <p>So I want to show you my source code. I'm doing a project for my work and have a positive resolution to show you the following sources:</p> <p><a href="http://jsfiddle.net/naFLN/" rel="nofollow">http://jsfiddle.net/naFLN/</a></p> <p>PS: If you have criticism about my code, please explain to me what I'm doing wrong.</p> <pre><code>/* * License: Proprietary commercial software * GC3D, Geocentre consulting 3D, 2013-2014(c) * Developer: Oleg Orlov A * http://geocenter-consulting.ru */ 'use strict'; var GC3D = { Version: '1.0.2' }; GC3D.Enums = { renderer: { id: 0, type: THREE.WebGLRenderer }, camera: { id: 1, type: THREE.PerspectiveCamera, fov: 45, aspect: window.innerWidth / window.innerHeight, near: 1, far: 10000 }, scene: { id: 2, type: THREE.Scene } }; GC3D.Camera = function( settings ) { this.camera = new THREE.PerspectiveCamera( settings.fov, settings.aspect, settings.near, settings.far ); }; GC3D.Camera.prototype.get = function() { return this.camera; }; GC3D.Light = function( color, intensity, distance ) { this.light = new THREE.PointLight( color, intensity, distance ); }; GC3D.Light.prototype.get = function() { return this.light; }; GC3D.Cube = function( properties ) { this.geometry = new THREE.BoxGeometry( properties.width, properties.height, properties.depth, properties.widthSegments, properties.heightSegments, properties.depthSegments ); this.material = new THREE.MeshBasicMaterial({ color: properties.color, wireframe: properties.wireframe }); this.mesh = new THREE.Mesh( this.geometry, this.material ); this.mesh.position.set( properties.position.x, properties.position.y, properties.position.z ); }; GC3D.Cube.prototype.get = function() { return this.mesh; }; GC3D.Cube.prototype.setPosition = function( newPosition ) { this.mesh.position.set( newPosition.x, newPosition.y, newPosition.z ); }; GC3D.Cube.prototype.setPositionAxisValue = function( axis, value ) { switch( axis ) { case 'x': this.mesh.position.x = value; break; case 'y': this.mesh.position.y = value; break; case 'z': this.mesh.position.z = value; break; default: return -1; } }; GC3D.Cube.prototype.movePosition = function( newPosition ) { if ( newPosition.x.direction === '+' ) this.mesh.position.x += newPosition.x; else if ( newPosition.x.direction === '-' ) this.mesh.position.x -= newPosition.x; if ( newPosition.y.direction === '+' ) this.mesh.position.y += newPosition.y; else if ( newPosition.y.direction === '-' ) this.mesh.position.y -= newPosition.y; if ( newPosition.z.direction === '+' ) this.mesh.position.z += newPosition.z; else if ( newPosition.z.direction === '-' ) this.mesh.position.z -= newPosition.z; }; GC3D.Cube.prototype.movePositionAxisValue = function( axis, direction, value ) { switch( [ axis, direction].join( "" ) ) { case 'x+': this.mesh.position.x += value; break; case 'y+': this.mesh.position.y += value; break; case 'z+': this.mesh.position.z += value; break; case 'x-': this.mesh.position.x -= value; break; case 'y-': this.mesh.position.y -= value; break; case 'z-': this.mesh.position.z -= value; break; default: return -1; } }; GC3D.Utils = function() { this.renderer = undefined; this.scene = undefined; this.camera = undefined; }; GC3D.Utils.prototype.get = function() { var utils = { renderer: this.renderer, scene: this.scene, camera: this.camera }; return utils; }; GC3D.Utils.prototype.setObject = function( properties ) { switch( properties.type ) { case THREE.WebGLRenderer: this.renderer = new THREE.WebGLRenderer({ alpha: true, wireframe: false }); break; case THREE.Scene: this.scene = new THREE.Scene(); break; case THREE.PerspectiveCamera: this.camera = new THREE.PerspectiveCamera( properties.fov, properties.aspect, properties.near, properties.far ); break; default: return -1; } }; GC3D.Utils.prototype.getObject = function( type ) { switch( type ) { case THREE.WebGLRenderer: return this.renderer; case THREE.Scene: return this.scene; case THREE.PerspectiveCamera: return this.camera; default: return -1; } }; GC3D.Utils.prototype.renderScene = function() { // about bind() // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind requestAnimationFrame( GC3D.Utils.prototype.renderScene.bind( this ) ); this.renderer.render( this.scene, this.camera ); // for test purpose only this.scene.children.filter(function( item ) { if ( item instanceof THREE.Mesh ) item.rotation.x += 0.02; }); // }; GC3D.Utils.prototype.setCameraPosition = function( camera, newPosition ) { if ( camera instanceof THREE.Camera ) camera.position.set( newPosition.x, newPosition.y, newPosition.z ); else return -1; }; GC3D.Utils.prototype.setCameraViewOnObject = function( camera, object ) { if ( camera instanceof THREE.Camera &amp;&amp; object instanceof THREE.Mesh) this.camera.lookAt( object ); else return -1; }; GC3D.Utils.prototype.createCube = function( properties ) { var cube = new GC3D.Cube( properties ); return cube; }; GC3D.Utils.prototype.addGeometricObject = function( properties ) { switch( properties.type ) { case GC3D.Cube: var cube = this.createCube( properties ); this.scene.add( cube.mesh ); return cube; default: return -1; } }; GC3D.Application = function() { this.utils = new GC3D.Utils(); }; GC3D.Application.prototype.build = function() { this.utils.setObject( GC3D.Enums.renderer ); this.utils.setObject( GC3D.Enums.scene ); this.utils.setObject( GC3D.Enums.camera ); // for test purpose only var cubeProperties = { type: GC3D.Cube, width: 1, height: 1, depth: 1, segments: { width: 1, height: 1, depth: 1 }, color: 0xff0000, wireframe: false, position: { x: 0, y: 0, z: 0 } }; var cube = this.utils.addGeometricObject( cubeProperties ); this.utils.setCameraPosition( this.utils.camera, { x: 3, y: 3, z: 3 } ); this.utils.setCameraViewOnObject( this.utils.camera, cube.mesh ); // this.utils.renderScene(); }; window.onload = function() { var application = new GC3D.Application(); application.build(); }; </code></pre>
[]
[ { "body": "<p>All in all, that is some pretty impressive code, I only have some minor comments.</p>\n\n<ul>\n<li><p>Instead of returning -1, I would suggest to simply throw a</p>\n\n<pre><code>new Exception('informative message')\n</code></pre></li>\n<li><p>This :</p>\n\n<pre><code>GC3D.Cube.prototype.setPositionAxisValue = function( axis, value ) {\n switch( axis ) {\n case 'x':\n this.mesh.position.x = value;\n break;\n case 'y':\n this.mesh.position.y = value;\n break;\n case 'z':\n this.mesh.position.z = value;\n break;\n default:\n return -1;\n }\n};\n</code></pre>\n\n<p>could be </p>\n\n<pre><code>GC3D.Cube.prototype.setPositionAxisValue = function( axis, value ) {\n if( this.mesh.position[axis] ){\n this.mesh.position[axis] = value;\n }\n else\n { \n throw new Exception('Axis ' + axis + ' does not exist');\n }\n};\n</code></pre>\n\n<p>This leaves a tiny window open to trouble; if axis is a variable name that position has which is not x,y,z, then this approach would not detect that</p></li>\n<li><p>This :</p>\n\n<pre><code>GC3D.Cube.prototype.movePosition = function( newPosition ) {\n if ( newPosition.x.direction === '+' ) this.mesh.position.x += newPosition.x;\n else if ( newPosition.x.direction === '-' ) this.mesh.position.x -= newPosition.x;\n\n if ( newPosition.y.direction === '+' ) this.mesh.position.y += newPosition.y;\n else if ( newPosition.y.direction === '-' ) this.mesh.position.y -= newPosition.y;\n\n if ( newPosition.z.direction === '+' ) this.mesh.position.z += newPosition.z;\n else if ( newPosition.z.direction === '-' ) this.mesh.position.z -= newPosition.z;\n};\n</code></pre>\n\n<p>could be </p>\n\n<pre><code>GC3D.Cube.prototype.movePosition = function( newPosition ) {\n this.mesh.position.x += +( newPosition.x.direction + newPosition.x );\n this.mesh.position.y += +( newPosition.y.direction + newPosition.y );\n this.mesh.position.z += +( newPosition.z.direction + newPosition.z ); \n};\n</code></pre>\n\n<p>This uses the fact that +(string) will convert that string to a signed number. Note that this is still copy pasted code, so you could consider a helper function for this, but I don't that see that as imperative. You could for example also think about calling <code>movePositionAxisValue()</code> as your helper function.</p></li>\n<li><p>This piece</p>\n\n<pre><code>GC3D.Cube.prototype.movePositionAxisValue = function( axis, direction, value ) {\n switch( [ axis, direction].join( \"\" ) ) {\n case 'x+':\n this.mesh.position.x += value;\n break;\n case 'y+':\n this.mesh.position.y += value;\n break;\n case 'z+':\n this.mesh.position.z += value;\n break;\n case 'x-':\n this.mesh.position.x -= value;\n break;\n case 'y-':\n this.mesh.position.y -= value;\n break;\n case 'z-':\n this.mesh.position.z -= value;\n break;\n default:\n return -1;\n }\n};\n</code></pre>\n\n<p>could be</p>\n\n<pre><code>GC3D.Cube.prototype.movePositionAxisValue = function( axis, direction, value ) {\n if( this.mesh.position[axis] ){\n this.mesh.position[axis] += +( direction + value );\n if( isNaN( this.mesh.position[axis] ) ){\n throw new Exception( 'Could not add' + +( direction + value ) + ' to ' + axis + ' axis' );\n }\n } else {\n throw new Exception( 'Axis ' + axis + ' does not exist' );\n }\n}\n</code></pre>\n\n<p>using the same <code>+( )</code> trick as in the previous point, I would probably consider a templating function if I were to throw informative exceptions in every function ;)</p></li>\n</ul>\n\n<p>All in all, very decent code, my points are just suggestion, well done.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-03T10:35:18.250", "Id": "112467", "Score": "0", "body": "Can you provide a link to the deleted question? This most likely can be corrected." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-04T06:36:32.500", "Id": "112676", "Score": "0", "body": "I've created another question on codereview, but people again has closed it... Don't understand why... Despite on this pity situation, I want tell you, that mostly I'm interested exactly in your review and opinion. I think, you're a great professional. So, please visit the website site of my 3D WebGL library http://magesi.ru, I won't provide any other links, because all required information is on website. There are specification, how-to manual, sources. I want to hear you professional mark for my project. Please contact me by email: oleg@amegas.ru or add me to skype, brightstar.amegas" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T13:09:23.330", "Id": "47474", "ParentId": "43068", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T15:25:09.880", "Id": "43068", "Score": "2", "Tags": [ "javascript", "object-oriented", "prototypal-class-design" ], "Title": "Prototype OO-style of my THREE.JS application" }
43068
<p>Is there a better way to do this kind of array combination with a PHP native function like <code>array_combine</code>? I'm trying to improve my skills, and at certain points I note that I am using too many nested <code>foreach</code> for almost everything. </p> <p><strong>Using PHP 5.4</strong></p> <pre><code> $array = Array( 'GroupName' =&gt; 'Emilio', 'Moduleid' =&gt; Array( 0 =&gt; 15, 1 =&gt; 12, 2 =&gt; 9, 3 =&gt; 1, 4 =&gt; 11, 5 =&gt; 10 ), 'Permission' =&gt; Array( 15 =&gt; 'W', 12 =&gt; 'R', 14 =&gt; 'W', 9 =&gt; 'W', 1 =&gt; 'R', 13 =&gt; 'W', 11 =&gt; 'W', 10 =&gt; 'R' ) ); foreach ($array['Moduleid'] as $value) { foreach ($array['Permission'] as $key1 =&gt; $value1) { if ($value == $key1) { $result[$key1] = $value1; } } } $newArray = array( 'GroupName' =&gt; $array['GroupName'], 'ModulePermission' =&gt; $result ); unset($array); echo '&lt;pre&gt;'; print_r($newArray); echo '&lt;/pre&gt;'; </code></pre> <p><strong>Output</strong></p> <pre><code>Array ( [GroupName] =&gt; Emilio [ModulePermission] =&gt; Array ( [15] =&gt; W [12] =&gt; R [9] =&gt; W [1] =&gt; R [11] =&gt; W [10] =&gt; R ) ) </code></pre>
[]
[ { "body": "<p>Using <a href=\"http://us1.php.net/manual/en/function.in-array.php\" rel=\"nofollow\">in_array</a> can be droped one <code>foreach</code></p>\n\n<pre><code>$result = array();\nforeach ($array['Permission'] as $key =&gt; $value) {\n if (in_array($key, $array['Moduleid'])) {\n $result[$key] = $value;\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T16:30:06.847", "Id": "43077", "ParentId": "43070", "Score": "3" } }, { "body": "<p>You can simplify this code considerably using the built-in array functions, specifically <code>array_flip</code> and <code>array_intersect_key</code>. </p>\n\n<pre><code>$newArray = array(\n 'GroupName' =&gt; $array['GroupName'],\n 'ModulePermission' =&gt; \n array_intersect_key($array['Permission'], \n array_flip($array['Moduleid'])\n )\n);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T01:53:10.840", "Id": "43108", "ParentId": "43070", "Score": "2" } } ]
{ "AcceptedAnswerId": "43108", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T15:41:42.980", "Id": "43070", "Score": "2", "Tags": [ "php", "array", "php5" ], "Title": "Is there a better way to combine these arrays?" }
43070
<p>In reviewing code in our application, I see a tension between what makes a convenient design for methods accessing database data versus coding to ensure that the JDBC resource objects are closed properly.</p> <p>An example problem:</p> <pre><code>// Application.java: Singleton class for objects which want to execute SQL queries /** * Execute a query and return the Result. Provide a common point of * connection/statement handling * * @param sql * SQL to execute * @return a ResultSet */ public ResultSet executeQuery(String sql) throws Exception { DBConnectionObj connectionObj = dbPoolMgr.getConnection(); try { if (LOG.isDebugEnabled()) { LOG.debug("StateServer.executeQuery(): executing query=" + sql); } return connectionObj.executeQuery(sql); } catch (Exception e) { LOG.error("executeQuery(): error executing SQL=" + sql); throw e; } finally { dbPoolMgr.putConnection(connectionObj); } } // DBConnectionObj.java: JDBC Connection wrapper used in a connection pool public ResultSet executeQuery(String sql, Connection connection) { try { if (Log4jUtils.isDebugLevel(LOG)) { LOG.debug("executeQuery(): " + sql); } return connection.createStatement().executeQuery(sql); } catch (SQLException e) { UnsuccessfulSQLExecutionResult result = new UnsuccessfulSQLExecutionResult(e, sql); LOG.error("executeQuery(): exception executing query. SQL info=" + result.getContents()); e.printStackTrace(); return null; } } </code></pre> <p>With above helper functions, other application classes can just pass the specific SQL and get back a reference to the ResultSet:</p> <pre><code> ResultSet rs = Application.getInstance().executeQuery(getSql()); while (rs.next()) { // process data } rs.close(); </code></pre> <p>The problem with the DBConnectionObj.executeQuery() method, is that it creates a temporary <code>Statement</code> to execute the query, and this temporary object is never closed. But also, because the method returns the <code>ResultSet</code> to the caller, it can't close the <code>Statement</code> until the caller is ready to close the <code>ResultSet</code>. (The code doesn't need to close the <code>Connection</code> object, because it stays open for the lifetime of the application, and is part of a pool of open database connections.)</p> <p>One solution would be to make sure every caller to the <code>executeQuery()</code> method, always does this:</p> <pre><code>rs.close(); rs.getStatement().close(); </code></pre> <p>So the question is this: for usefulness, having a method which takes a SQL string for input and returns a <code>ResultSet</code> feels like a good design. However, it imposes requirement that callers make sure to close both the <code>ResultSet</code> and the Statement, and it can't take advantage of the safer Java 7 try-close feature:</p> <pre><code>try(ResultSet rs = Application.getInstance().executeQuery(getSql())) { while (rs.next()) { // process data } } // rs is automatically closed, but not the Statement object </code></pre> <p>Any comments or suggestions on a better design are appreciated.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-04T13:56:07.500", "Id": "74953", "Score": "0", "body": "`if (LOG.isDebugEnabled()) {` and `if (Log4jUtils.isDebugLevel(LOG)) {` looks like they checked the same thing, but they are not the same, is there a difference ? Do you really need to check if `debug` is set ? (I may be wrong, I'm just curious)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-04T20:02:12.787", "Id": "75052", "Score": "0", "body": "@Marc-Andre: yes, you are right. This is pasted from different sections of our code. For some reason, I always used to code `Level.DEBUG.isGreaterOrEqual(logger.getEffectiveLevel())` to check, so I made a wrapper method so we didn't have to litter our code with that every time. I'm not sure if I somehow overlooked the `isDebugEnabled()` method, or if it was added after we wrote the earlier code." } ]
[ { "body": "<p>JDBC has always been a PITA when it comes to handling/closing resources.</p>\n\n<p>One of the big advancements in the past while has been the advent of ConnectionPools and abstraction layers.... If you are inside a framwork like tomcat, or WebSphere, these are built in. Otherwise you can use things like <a href=\"http://commons.apache.org/proper/commons-dbcp/\" rel=\"nofollow\">Apache DBCP</a> or <a href=\"http://www.mchange.com/projects/c3p0/\" rel=\"nofollow\">C3PO</a>. For both of these frameworks, when you close the Connections it closes any created Statements.</p>\n\n<p>Using a pool like this allows you to trust in the pooling layer... but, I would still recommend that you use a 'clean' implementation for your code. What I have used in the past, and I think is the neatest method, is to have an abstract class like:</p>\n\n<pre><code>public abstract class DBCallable&lt;T&gt; implements Callable&lt;T&gt; {\n private final ConnectionPool pool;\n\n public DBCallable(ConnectionPool pool) {\n this.pool = pool;\n }\n\n public &lt;T&gt; call() throws SQLException {\n try (Connection con = pool.getConnection()) {\n return execute(con);\n }\n }\n\n protected abstract T execute(Connection con);\n}\n</code></pre>\n\n<p>Then, you can do all sorts of things....</p>\n\n<p>For example, you need to populate some widget:</p>\n\n<pre><code>final Widget widget = new Widget();\nfinal ConnectionPool pool = .......\n\nnew DBCallable&lt;Integer&gt;(pool) {\n Integer execute(Connection con) {\n try (Statement stmt = con.createStatement()) {\n int count = 0;\n try (ResultSet rs = con.executeQuery(\"...\")) {\n while (rs.next()) {\n count++;\n widget.doSomethingWith(rs.get(1));\n }\n }\n return count;\n }\n }\n}\n</code></pre>\n\n<p>You can even supply one of those to an ExecutorService, and get a Future from it, and then then run these things in alternate threads.</p>\n\n<p>Very versatile.</p>\n\n<p>Edit: If you would prefer to have (easy) access to the Statement instead of the Connection, create an abstract sub-class of the DBCallable:</p>\n\n<pre><code>public abstract class StmtCallable&lt;T&gt; extends DBCallable&lt;T&gt; {\n\n public DBCallable(ConnectionPool pool) {\n super(pool);\n }\n\n protected T execute(Connection con) {\n try (Statement stmt = con.createStatement()) {\n return query(stmt);\n }\n }\n\n protected abstract T query(Statement stmt);\n}\n</code></pre>\n\n<p>Then, if you want a clean statement each time for your code, you can have</p>\n\n<pre><code>new StmtCallable&lt;Integer&gt;(pool) {\n Integer query(Statement stmt) {\n int count = 0;\n try (ResultSet rs = stmt.executeQuery(\"...\")) {\n while (rs.next()) {\n count++;\n widget.doSomethingWith(rs.get(1));\n }\n }\n return count;\n\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-04T16:31:38.370", "Id": "74996", "Score": "0", "body": "How about changing the helper method to return a collection that would contain the data from the resultset and close all resultset, statement and connection in the finally section? I believe one should not keep the resultset(or any JDBC connection related referenced) hanging around for data processing. Just my opinion." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-04T16:33:58.613", "Id": "74999", "Score": "0", "body": "@SriniKandula The resultset, and all related references **are** closed. Nothing escapes the `execute()` method. The work is done inside the context of the ResultSet, and the return value, in this case, is the number of rows processed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-04T16:42:01.833", "Id": "75002", "Score": "0", "body": "my comment refers to the original post and I'm asking your opinion about my suggestion. However in your execute() method also the resultset is open while widget.doSomethingWith() is running. My point is one shouldn't keep the connection alive while we process the data." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-04T16:55:54.207", "Id": "75005", "Score": "1", "body": "@SriniKandula for the most part, converting a ResultSet to a Collection of some sort is a waste of time and effort, and you lose the ability to do native type management (getInt(col), getString(...), etc.). While you should not keep a ResultSet open for longer than necessary, I would consider any code that uses the ResultSet without sleeping, blocking, or user-interaction to be fine." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-04T20:21:12.767", "Id": "75055", "Score": "1", "body": "Thanks for the ideas above. We have a standalone application, so we would need to integrate one of the libraries you mentioned. One question I have about the code you posted: `ResultSet rs = con.executeQuery(\"...\")`, which type of `Connection` object has an `executeQuery()` method? This would be good to use, because it avoids the whole issue of creating a separate `Statement` object which we rarely care about. (Some times we reuse `PreparedStatement` objects, but it is very rare.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-04T20:24:23.317", "Id": "75057", "Score": "0", "body": "@SamGoldberg you have me there... I simply forgot that executeQuery is on the Statement.... But, that's one of the advantages of the system I suggest as well, let me edit:" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-04T13:25:17.993", "Id": "43404", "ParentId": "43072", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T15:45:42.307", "Id": "43072", "Score": "3", "Tags": [ "java", "jdbc" ], "Title": "Design considerations for classes/methods using JDBC to ensure resources closed correctly" }
43072
<p>I have the following key value pair in an array, and am trying to extract and load them into a collection.</p> <p>The below code is working but it can be optimized using Linq:</p> <pre><code>string _data = "Website=url:www.site1.com,isdefault:true,url:www.site2.com,isdefault:true"; List&lt;WebSiteAddress&gt; _websiteList = new List&lt;WebSiteAddress&gt;() ; WebSiteAddress _website = new WebSiteAddress(); string[] _websiteData = _divider[1].Split('='); string[] _WebsiteKeyValuePair = _websiteData[1].Split(','); for (int j = 0; j &lt; _WebsiteKeyValuePair.Length; j++) { string key = _WebsiteKeyValuePair[j].Split(':')[0]; string value = _WebsiteKeyValuePair[j].Split(':')[1]; if (key.ToLower() == "url") { _initWebsite.Url = value; } else if (key.ToLower() == "isdefault") { _website.IsDefault = Convert.ToBoolean(value); _websiteList.Add(_website); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T16:27:41.053", "Id": "74316", "Score": "0", "body": "There's some discussion about where this belongs. Someone (not the OP) migrated/copied it here from [StackOverflow](http://stackoverflow.com/questions/22100017/how-to-get-the-split-value-from-collection). It's got at least one answer on SO." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T16:55:37.787", "Id": "74323", "Score": "0", "body": "What's `_divider`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T17:32:21.653", "Id": "74326", "Score": "2", "body": "You are never using `_data`, and you did not provide a sample of `_divider[1]`. Please review and update your question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T23:34:34.193", "Id": "74372", "Score": "1", "body": "Instead of performing the same split operation twice to get the key and value you should split once and store the result in a temporary variable first. You should also do the `ToLower()` operation when you assign the value to `key`. That way you don't have to do a `ToLower()` in each `if` statement." } ]
[ { "body": "<h3>Naming</h3>\n<p>I don't get the <code>_</code> underscore prefix. This typically identifies a <em>private field</em> (albeit controversial). I'm pretty sure there's a consensus about simple <code>camelCasing</code> for local identifiers.</p>\n<p>The name <code>_websiteList</code> is a bad one, for two reasons:</p>\n<ul>\n<li>It's of type <code>WebSiteAddress</code>, which has words <code>Web</code> and <code>Site</code>; the name isn't following the established casing convention, should be <code>_webSiteList</code>.</li>\n<li>It's tying the variable to its type. Would the name still make sense if the type was <code>WebSiteAddress[]</code>?</li>\n</ul>\n<p>A better name would be, simply, <code>webSiteAddresses</code>.</p>\n<h3>Typing</h3>\n<p>If you want to use LINQ, you're targeting .NET 3.5+. Therefore, you can use implicit typing to improve the readability (and possibly the maintainability) of your code (although that's possibly personal preference).</p>\n<p>Consider:</p>\n<ul>\n<li><code>var webSiteData = _divider[1].Split('=');</code></li>\n</ul>\n<hr />\n<p>The SO answer gives you a nice <em>LINQ-oriented</em> approach.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T17:03:27.450", "Id": "43080", "ParentId": "43074", "Score": "5" } }, { "body": "<p>My suggestions:</p>\n\n<ul>\n<li>Use a foreach instead of a for;</li>\n<li>Don't redo operations such as <code>_WebsiteKeyValuePair[j].Split(':')</code> and <code>key.ToLower()</code>, store them in a variable instead;</li>\n<li>Use a switch instead of an if-chain.</li>\n</ul>\n\n<p>Switch would look like:</p>\n\n<pre><code>switch(key.ToLower())\n{\n case \"url\":\n _initWebsite.Url = value;\n break;\n case \"isdefault\":\n ...\n break;\n}\n</code></pre>\n\n<p>As for LINQ, you have an answer in the Stackoverflow cross-post: <a href=\"https://stackoverflow.com/a/22100355/148412\">https://stackoverflow.com/a/22100355/148412</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T17:35:32.653", "Id": "43081", "ParentId": "43074", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T16:08:51.360", "Id": "43074", "Score": "3", "Tags": [ "c#", "strings", "array", "linq" ], "Title": "How to get the Split value from collection?" }
43074
<p>I wrote a program for one of my Object Oriented Programming in Java classes(Program 2) and I got docked off because my method was too long, which I'm not complaining about.</p> <p>I got the note: "Modularize more, method too long."</p> <p>I was wondering what any of you more experienced programmers would do to simplify/shorten my code for future sake so that I learn how to shorten this sort of code.</p> <pre><code>public void run() throws java.io.IOException { stdin = new Scanner(System.in); String input; String fraction; int numPerLine; boolean inList = false; input = stdin.next(); // Get the read while(!input.equalsIgnoreCase("Q")) { if(input.equalsIgnoreCase("A")) { fraction = stdin.next(); // Get the fraction read thisFract = new Fraction(fraction); list.add(thisFract); System.out.println(thisFract.toString() + " was added " + "to the list."); } else if (input.equalsIgnoreCase("D")) { fraction = stdin.next(); thisFract = new Fraction(fraction); inList = list.delete(thisFract); if(inList == true) System.out.println(thisFract.toString() + " was removed " + "from the list."); else System.out.println(thisFract.toString() + " is not in the" + " list."); } else if(input.equalsIgnoreCase("S")) { System.out.println("The sum of the list is: " + list.sum()); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T16:30:54.673", "Id": "74318", "Score": "0", "body": "Crossposted from: http://stackoverflow.com/questions/22100184/how-to-modularize-more-efficiently" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T16:37:44.887", "Id": "74321", "Score": "0", "body": "Your code works as expected but simply contains \"code smells\". You should refactor your code and check the clean code paradigm." } ]
[ { "body": "<p>\" wondering what any of you ... would do to simplify/shorten my code...\"</p>\n\n<p>How about you use Switch statements rather than those cumbersome cascade of if/else statements? That should make it cleaner and more readable. </p>\n\n<p>Something like</p>\n\n<pre><code>switch(input) { \n case 'X' : \n break; \n case 'Y' : \n break; \n case 'Z' : \n break;\n default : \n break;\n} \n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T16:27:54.667", "Id": "43076", "ParentId": "43075", "Score": "5" } }, { "body": "<p>There are some <a href=\"http://en.wikipedia.org/wiki/Code_smell\">code smells</a> in your code.</p>\n\n<p><strong>Duplicated Code:</strong></p>\n\n<pre><code>fraction = stdin.next(); // Get the fraction read\nthisFract = new Fraction(fraction);\nlist.add(thisFract);\n\nfraction = stdin.next();\nthisFract = new Fraction(fraction);\ninList = list.delete(thisFract);\n</code></pre>\n\n<p>These lines do (almost) the same thing. It is commonly practice in software development to hold solutions at <em>one place</em>. In this case a method which reads the next fraction and another method which add a fraction to a list. This is meant by <em>modularization</em>. Divide your solution in little subsolutions which can be changed at one place and used at different places.</p>\n\n<p>This code optimization is called <a href=\"http://en.wikipedia.org/wiki/Code_refactoring\">Refactoring</a>.\nThere a lots of <em>patterns</em> for code refactoring.</p>\n\n<p><strong>Replace Conditional with Polymorphism:</strong></p>\n\n<p>You could think about using a switch-statement instead of the if-else blocks but it is highly recommended to use <a href=\"http://www.refactoring.com/catalog/replaceConditionalWithPolymorphism.html\">Polymorphism instead of conditional checks</a> in object oriented programming languages.</p>\n\n<p><strong>Clean Code:</strong></p>\n\n<p>I would recommend also to read the book <em>Clean Code</em> written by Robert \"Uncle Bob\" C. Martin which explains lots of patterns to write well organized code.</p>\n\n<p><strong>For Example you can modularize your code like this:</strong></p>\n\n<ol>\n<li>move the if-else in one method</li>\n<li>find code clones in the condition blocks and separate into methods</li>\n<li><p>refactor methods top-down</p>\n\n<pre><code>public void run() throws java.io.IOException {\n stdin = new Scanner(System.in);\n String input;\n input = nextFraction();\n\n while (!input.equalsIgnoreCase(\"Q\")) {\n handleInput(input);\n }\n}\n\nprivate void handleInput(String input) {\n String fraction;\n int numPerLine;\n boolean inList = false;\n\n if (input.equalsIgnoreCase(\"A\")) {\n handleA(); \n } else if (input.equalsIgnoreCase(\"D\")) {\n handleD(); \n } else if (input.equalsIgnoreCase(\"S\")) {\n handleS(); \n }\n}\n\nprivate void handleA() {\n assignNextFraction();\n addFractionToList();\n outputFractionAdded(); \n}\n\nprivate void handleD() {\n assignNextFraction();\n inList = deleteFractionFromList();\n if (inList) {\n outputFractionRemoved();\n } else {\n outputFractionNotInList();\n } \n}\n\nprivate void handleS() {\n outputListSum(); \n}\n\nprivate boolean deleteFractionFromList() {\n boolean inList;\n inList = list.delete(thisFract);\n return inList;\n}\n\nprivate void addFractionToList() {\n list.add(thisFract);\n}\n\nprivate void assignNextFraction() {\n String fraction;\n fraction = nextFraction();\n thisFract = createFraction(fraction);\n}\n\nprivate void outputFractionAdded() {\n output(thisFract.toString() + \" was added \" + \"to the list.\");\n}\n\nprivate void outputFractionRemoved() {\n output(thisFract.toString() + \" was removed \" + \"from the list.\");\n}\n\nprivate Fraction createFraction(String fraction) {\n return new Fraction(fraction);\n}\n\nprivate String nextFraction() {\n String fraction;\n fraction = stdin.next(); // Get the fraction read\n return fraction;\n}\n\nprivate void outputFractionNotInList() {\n output(thisFract.toString() + \" is not in the\" + \" list.\");\n}\n\nprivate void outputListSum() {\n output(\"The sum of the list is: \" + list.sum());\n}\n\nprotected void output(String s) {\n System.out.println(s);\n}\n</code></pre></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T17:34:33.363", "Id": "74327", "Score": "6", "body": "I wish Clean Code was required in any mid-level programming class..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T18:32:52.153", "Id": "74329", "Score": "0", "body": "`fraction`, `numPerLine`, `inList` are not used in `handleInput` method. Don't think this as a criticism but when you suggested OP to use *Polymorphism instead of conditional checks* your code should also reflect that. Unless *recursion* continues :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T16:45:43.577", "Id": "43079", "ParentId": "43075", "Score": "16" } }, { "body": "<p>To expand on Jan Koester's excellent answer, I would refactor the methods to a separate class. If done properly, this will allow you to write <a href=\"http://www.vogella.com/tutorials/JUnit/article.html\">unit tests</a> on the functionality. It will also make the switch statement you suggested better.</p>\n\n<pre><code>public class FractionSummingService {\n\n public void addFraction(string fraction) {\n // error check and add fraction to list here\n }\n\n public void removeFraction(string fraction) {\n // error check and remove fraction from list here\n }\n\n public string sumFractions()\n {\n // error check and sum list here\n }\n}\n</code></pre>\n\n<p>Then you're main function looks something like this</p>\n\n<pre><code>public void run() throws java.io.IOException {\n stdin = new Scanner(System.in);\n\n FractionSummingService service = new FractionSummingService();\n while (true) {\n\n String input = nextFraction();\n\n switch(input) { \n case 'A' : \n service.addFraction(input);\n break; \n case 'D' : \n service.removeFraction(input);\n break; \n case 'S' : \n writeLine(service.sumFractions();\n break;\n case 'Q':\n // end loop\n break;\n default:\n writeUnknownCommand();\n break;\n } \n }\n}\n</code></pre>\n\n<p>to go one step further, you could put the valid commands into constants so your switch looks like this</p>\n\n<pre><code>switch(input) { \n\n case ADD : \n service.addFraction(input);\n break; \n case DELETE : \n service.removeFraction(input);\n break; \n case SAVE : \n writeLine(service.sumFractions();\n break;\n case QUIT:\n // end loop\n break;\n default:\n writeUnknownCommand();\n break;\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-02T22:06:51.857", "Id": "74632", "Score": "1", "body": "These could be enums. Fun fact: Enums can have abstract method. Could be handy for this case here." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T17:54:42.510", "Id": "43082", "ParentId": "43075", "Score": "11" } }, { "body": "<p>Just to add another view to already great answers. It is more about a different approach and personal preference than obviously better code.</p>\n\n<p>A different approach that you can use could be a map (I tell you why I personally like it better) where your input would be a key and the value would a class implementing interface (let's) say FractionService.</p>\n\n<pre><code>public interface FractionService{\npublic void process(String input);\n\n}\n</code></pre>\n\n<p>Then you could have three subclasses FractionAdditionService, FractionRemovalService, FractionIgnoreService. Those three would implement the process method and inside they would have your desired behavior that is described in your question and refined in the answers.</p>\n\n<p>Then in the main class:</p>\n\n<pre><code>/*Better would be to use a map that when receiving a null as a key would return some dummy implementation that does nothing. This would prevent a NullPointerEx. But you get an idea about the map.*/\nprivate static final Map&lt;String, FractionService&gt; mapOfServices = new HashMap&lt;String,FractionService&gt;();\n\nstatic {\n mapOfServices.put(\"A\", new FractionAdditionService());\n mapOfServices.put(\"D\", new FractionRemovalService());\n mapOfServices.put(\"S\", new FractionIgnoreService());\n\n}\n\npublic void run() throws java.io.IOException {\n stdin = new Scanner(System.in);\n String input;\n input = nextFraction();\n\n while (!input.equalsIgnoreCase(\"Q\")) {\n mapOfServices.get(input).process(input);\n }\n}\n</code></pre>\n\n<p>An advantage with the map is that when you want to add another input letter and function for it you add one row here in your \"manager\" class and then the functionality into a separate class. Dowside, looking up in a map is slower than switch but you would care about that after you would find out that this is a bottleneck for you.</p>\n\n<p>Then another suggestion that I would have is to pass the arguments into the methods where possible rather than using the instance variables. Particularly in @Jan Koester answer (his answer is great, dont get me wrong) I get slightly lost what is being assigned into the instance variable when and in which order. So to give you an example for one method:</p>\n\n<pre><code>private void handleA() {\n Fraction newFraction = assignNextFraction();\n addFractionToList(newFraction);\n outputFractionAdded(newFraction); \n}\n</code></pre>\n\n<p>Instead of assigning a value into \"thisFract\" in method \"assignNextFraction\" and then use it in the next methods you return it and then pass it as argument. For me it is better readable because I can better track what is flowing where and how it gets assigned. It is a notion from functional programming where ideally the functions (method) should not have any side effects (=playing around with non-local variables). Another advantage that I think it has is that you can test the functions better. You pass an argument and see the result, instead of having to set up instance variables in correct form and then test the result. Just a different approach, I personally like it better. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T12:28:37.410", "Id": "74431", "Score": "0", "body": "absolutely right. It makes code easy to read and easy to test if methods doesn't have side effects :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-02T22:00:27.423", "Id": "74630", "Score": "0", "body": "This is a great example of the Command Pattern by the GOF" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T10:53:41.037", "Id": "43128", "ParentId": "43075", "Score": "5" } }, { "body": "<p>Per request, here is another approach and explanation. An interface was proposed; +1\nthe use of a Map was proposed. +1</p>\n\n<p>Better yet is to put them together. </p>\n\n<ul>\n<li>For starters, we can leverage the fact that Enums can have an abstract method -- which is essentially an interface. </li>\n<li>Second, we can leverage the valueOf(someEnum.name()) to replace the Map proposed in other solutions. </li>\n<li>We can iterate through enums and print their toString() to handily show what we support. </li>\n</ul>\n\n<p>try this (Use enums with abstract methods, skip the map and use 'valueOf'. Skip the interface):</p>\n\n<pre><code>public enum FractionService {\n\n A {\n @Override\n public void process(String input) {\n\n }\n @Override\n public String toString() {\n return \"ADD\";\n }\n },\n D {\n @Override\n public void process(String input) {\n\n }\n @Override\n public String toString() {\n return \"DELETE\";\n }\n },\n S {\n @Override\n public void process(String input) {\n\n }\n @Override\n public String toString() {\n return \"SAVE\";\n }\n }\n ,\n Q {\n @Override\n public void process(String input) {\n\n }\n\n @Override\n public String toString() {\n return \"QUIT\";\n }\n };\n\n\n public abstract void process(String input);\n\n public static void main(String[] args) {\n for (FractionService fractionService : FractionService.values()) {\n System.out.format(\"Commands are: %s: %s\", fractionService.name(), fractionService.toString());\n\n }\n FractionService service = FractionService.valueOf(\"Q\"); // results in QUIT\n service.process(\"foo\");\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-03T15:56:52.413", "Id": "74755", "Score": "2", "body": "Welcome to Code Review! Could you add a bit more explanation in your answer. It's good to propose a solution but we are reviewing code, an explanation would be much appreciated." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-03T15:48:06.187", "Id": "43311", "ParentId": "43075", "Score": "3" } } ]
{ "AcceptedAnswerId": "43079", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T16:16:51.000", "Id": "43075", "Score": "11", "Tags": [ "java" ], "Title": "Modularize more efficiently in an if/else setup" }
43075
<p>I validate this program for</p> <pre><code>Non numeric inputs x/0 type fractions 0/0 and 0/y type fractions x/1 and x/x type fractions -x/-y and x/-y type fractions </code></pre> <p>I'd appreciate it if someone can look at this code and tell where I can improve this coding. I'd also like to know about other validations best practices I can use or contribute on Github.</p> <p>IDE used: Eclipse (Kepler)</p> <p><a href="http://gigal.blogspot.com/2014/02/java-fraction-calculator-example.html">Blog post</a></p> <p><a href="https://github.com/GigalBlog/Java-Fraction-Calculator-Example">Github repositary</a></p> <p><strong>FractionsApp.java</strong></p> <pre><code>package com.gigal.fractionexercise.app; import java.util.Scanner; import com.gigal.fractionexercise.helper.Messages; import com.gigal.fractionexercise.model.Division; import com.gigal.fractionexercise.model.Fraction; import com.gigal.fractionexercise.model.Multiplication; import com.gigal.fractionexercise.model.Subtraction; import com.gigal.fractionexercise.model.Addition; public class FractionsApp { private static Scanner keyboard = new Scanner(System.in); public static void main(String args[]) { Fraction fraction1 = new Fraction(); // first fraction Fraction fraction2 = new Fraction(); // second fraction // Display application header Messages.displayHeader(); // get user inputs for fraction one and validate them do { System.out.println("Enter values for fration one"); Messages.insertNumerator(); try { fraction1.setNumerator(keyboard.nextInt()); // get user input } catch (Exception e) { Messages.inputError(e); // display error return; } Messages.inputDenominator(); try { fraction1.setDenominator(keyboard.nextInt()); // get user input } catch (Exception e) { Messages.inputError(e); return; } if (fraction1.getDenominator() == 0) { // check for x/0 error Messages.DenominatorCannotBeZero(); } } while (fraction1.getDenominator() == 0); // Display fraction one System.out.print("Fraction one : "); fraction1.display(); Messages.newLine(); // get user inputs for fraction two and validate them do { System.out.println("Enter values for fration two"); Messages.insertNumerator(); try { fraction2.setNumerator(keyboard.nextInt()); // get user input } catch (Exception e) { Messages.inputError(e); return; } Messages.inputDenominator(); try { fraction2.setDenominator(keyboard.nextInt()); // get user input } catch (Exception e) { Messages.inputError(e); return; } if (fraction2.getDenominator() == 0) { // check for x/0 error Messages.DenominatorCannotBeZero(); } } while (fraction2.getDenominator() == 0); // Display fraction two System.out.print("Fraction two : "); fraction2.display(); Messages.newLine(); // Addition Addition addition = new Addition(fraction1, fraction2); addition.display(); // Subtraction Subtraction subtraction = new Subtraction(fraction1, fraction2); subtraction.display(); // Multiplication Multiplication multiplication = new Multiplication(fraction1, fraction2); multiplication.display(); // Division Division division = new Division(fraction1, fraction2); division.display(); // Display application footer Messages.displayFooter(); } } </code></pre> <p><strong>Messages.java</strong></p> <pre><code>package com.gigal.fractionexercise.helper; import com.gigal.fractionexercise.model.Fraction; /* * This class is used to give meaningful messages to user * So whenever we want to change a message we don't want to check whole app but this class */ public class Messages { // This message is use to display the program header public static void displayHeader() { System.out.println("_________________________________________________________"); System.out.println(" Fraction App - a Gigal Blog Production"); System.out.println("_________________________________________________________"); newLine(); } // This message is use to display the program footer public static void displayFooter() { newLine(); System.out.println(" ----------- Thank you for using Fraction App -----------"); System.out.println("_________________________________________________________"); newLine(); } // This message is use to tell user to input value for Numerator in a fraction public static void insertNumerator() { System.out.print("Numerator : "); } // This message is use to tell user to input a value for denominator public static void inputDenominator() { System.out.print("Denominator : "); } // This method is used to get line of space public static void newLine() { System.out.println("\n"); } // This message is used when user input something miss match public static void inputError(Exception e) { newLine(); System.out.println("Input Error: " + e.toString()); System.out.println("Closing application ..."); System.out.println("Fraction app is closed."); displayFooter(); } // This message is used when user input 0 for Denominator in a fraction public static void DenominatorCannotBeZero() { System.out.println("Input Error: Denominator Cannot be zero"); newLine(); } // This message is used to display answers public static void displayAnswer(String operation, String operator, Fraction fraction1, Fraction fraction2, Fraction answer) { System.out.print(operation + " : "); fraction1.display(); System.out.print(" " + operator + " "); fraction2.display(); System.out.print(" = "); answer.display(); newLine(); } } </code></pre> <p><strong>Addition.java</strong></p> <pre><code>package com.gigal.fractionexercise.model; /* * This class models addition */ import com.gigal.fractionexercise.helper.Messages; public class Addition { private Fraction fraction1; private Fraction fraction2; private Fraction answer; // Constructor public Addition(Fraction fraction1, Fraction fraction2) { this.fraction1 = fraction1; this.fraction2 = fraction2; this.answer = new Fraction(); Calculate(); } // perform the calculation public void Calculate() { answer.setNumerator((fraction1.getNumerator() * fraction2.getDenominator()) + (fraction2.getNumerator() * fraction1.getDenominator())); answer.setDenominator(fraction1.getDenominator() * fraction2.getDenominator()); } // display the answer public void display() { Messages.displayAnswer("Addition", "+", fraction1, fraction2, answer); } } </code></pre> <p><strong>Division.java</strong></p> <pre><code>package com.gigal.fractionexercise.model; /* * This class models division */ import com.gigal.fractionexercise.helper.Messages; public class Division { private Fraction fraction1; private Fraction fraction2; private Fraction answer; // Constructor public Division(Fraction fraction1, Fraction fraction2) { this.fraction1 = fraction1; this.fraction2 = fraction2; this.answer = new Fraction(); Calculate(); } // perform the calculation public void Calculate() { answer.setNumerator(fraction1.getNumerator() * fraction2.getDenominator()); answer.setDenominator(fraction1.getDenominator() * fraction2.getNumerator()); } public void display() { // Check for the divide by zero error if (fraction2.getNumerator() == 0) { System.out.println("Division : Cannot divide by zero!"); return; } else { // display the answer Messages.displayAnswer("Division", "/", fraction1, fraction2, answer); } } } </code></pre> <p><strong>Fraction.java</strong></p> <pre><code>package com.gigal.fractionexercise.model; /* * This class models the fraction */ public class Fraction { private int Numerator; // x private int Denominator; // y public int getNumerator() { return Numerator; } public void setNumerator(int Numerator) { this.Numerator = Numerator; } public int getDenominator() { return Denominator; } public void setDenominator(int Denominator) { this.Denominator = Denominator; } // This method is used to display fractions // Some kind of processing also public void display() { // 0/y and x/1 types if (Numerator == 0 || Denominator == 1) { System.out.print(Numerator); } // -x/-y and x/-y types else { if ((Numerator &lt; 0 &amp;&amp; Denominator &lt; 0) || (Numerator &gt; 0 &amp;&amp; Denominator &lt; 0)) { Numerator *= -1; Denominator *= -1; } // x/x type if (Numerator == Denominator) { System.out.print(Numerator); return; } System.out.print(this.Numerator + "/" + this.Denominator); } } } </code></pre> <p><strong>Multiplication.java</strong></p> <pre><code>package com.gigal.fractionexercise.model; /* * This class models multiplication */ import com.gigal.fractionexercise.helper.Messages; public class Multiplication { private Fraction fraction1; private Fraction fraction2; private Fraction answer; // Constructor public Multiplication(Fraction fraction1, Fraction fraction2) { this.fraction1 = fraction1; this.fraction2 = fraction2; this.answer = new Fraction(); Calculate(); } // perform the calculation public void Calculate() { answer.setNumerator(fraction1.getNumerator() * fraction2.getNumerator()); answer.setDenominator(fraction1.getDenominator() * fraction2.getDenominator()); } // display the answer public void display() { Messages.displayAnswer("Multiplication", "*", fraction1, fraction2, answer); } } </code></pre> <p><strong>Subtraction.java</strong></p> <pre><code>package com.gigal.fractionexercise.model; /* * This class models subtraction */ import com.gigal.fractionexercise.helper.Messages; public class Subtraction { private Fraction fraction1; private Fraction fraction2; private Fraction answer; // Constructor public Subtraction(Fraction fraction1, Fraction fraction2) { this.fraction1 = fraction1; this.fraction2 = fraction2; this.answer = new Fraction(); Calculate(); } // perform the calculation public void Calculate() { answer.setNumerator((fraction1.getNumerator() * fraction2.getDenominator()) - (fraction2.getNumerator() * fraction1.getDenominator())); answer.setDenominator(fraction1.getDenominator() * fraction2.getDenominator()); } // display the answer public void display() { Messages.displayAnswer("Subtraction", "-", fraction1, fraction2, answer); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-03T08:35:20.143", "Id": "74691", "Score": "0", "body": "You say you validate for 5 cases. They beg to be automated tests." } ]
[ { "body": "<p>There are several things that can be improved in your code, I will point out some of them here.</p>\n\n<h3>Polymorphism</h3>\n\n<p>Your Addition/Subtraction/Multiplication/Division classes has a lot in common. You should use polymorphism and inheritance to use them better. You can make an abstract class for them.</p>\n\n<p>Also, you should make your unchangeable <code>Fraction</code> fields <strong>final</strong>. Also, the method <code>Calculate</code> should be named <code>calculate</code> to comply with the Java coding conventions. This would also apply to methods such as <code>DenominatorCannotBeZero</code>. All methods should start with lower-case letter. The same goes for <code>Numerator</code> and <code>Denominator</code> in your <code>Fraction</code> class.</p>\n\n<p>As your <code>Messages.displayAnswer</code> method was only called from the calculation classes, I put that code in this method instead.</p>\n\n<pre><code>public abstract class Calculation {\n private final Fraction fraction1;\n private final Fraction fraction2;\n private final String operation;\n private final char operator;\n protected Fraction answer;\n\n public Calculation(Fraction fraction1, Fraction fraction2, String operation, char operator) {\n this.fraction1 = fraction1;\n this.fraction2 = fraction2;\n this.operation = operation;\n this.operator = operator;\n this.answer = new Fraction();\n calculate();\n }\n\n public abstract void calculate();\n\n public void displayAnswer() {\n System.out.print(operation + \" : \");\n fraction1.display();\n System.out.print(\" \" + operator + \" \");\n fraction2.display();\n System.out.print(\" = \");\n answer.display();\n System.out.println(\"\");\n System.out.println(\"\");\n }\n}\n\n// Example with the Addition class\npublic class Addition extends Calculation {\n public Addition(Fraction fraction1, Fraction2) {\n super(fraction1, fraction2, \"Addition\", '+');\n }\n public void calculate() {\n answer.setNumerator((fraction1.getNumerator() * fraction2.getDenominator())\n + (fraction2.getNumerator() * fraction1.getDenominator()));\n answer.setDenominator(fraction1.getDenominator() * fraction2.getDenominator());\n }\n}\n</code></pre>\n\n<h3>Your <code>Messages</code> class</h3>\n\n<p><code>Messages.insertNumerator();</code> is only called when you are asking the user to input some value. Move the entire input code to this method, you could also let the method take care of the error-handling, this way you would only have to call:</p>\n\n<pre><code>fraction1.setNumerator(Messages.inputNumerator());\n</code></pre>\n\n<p>Overall, I think you are overusing your <code>Messages</code>, or in one way underusing. You are using it to reduce code-duplication, and yet you still have code duplication. Once you put the input for both <code>inputNumerator</code> and <code>inputDenominator</code> into your <code>Messages</code> classes, I would agree with the usage of it more. However, a method for new-line is a bit overkill IMO. I personally would think it is more clear to actually print <code>System.out.println();</code> once or twice when you want an empty line.</p>\n\n<h3>Other suggestions</h3>\n\n<p>Instead of what I have done above, you could use a <code>CalculationResult</code> class to store the <code>answer</code> and let it have the <code>displayAnswer</code> method.</p>\n\n<hr>\n\n<p>Instead of creating the Calculation on one line and displaying it on the next and then never using that variable again, you can use this:</p>\n\n<pre><code>new Addition(fraction1, fraction2).display();\n</code></pre>\n\n<p>No variable created, you just create the object and use it directly.</p>\n\n<hr>\n\n<p>A comment like this is completely overkill. Make your code as self-documenting as possible. The variable name <code>addition</code> tells you that it is addition.</p>\n\n<pre><code>// Addition\nAddition addition = ...\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-08-13T16:50:31.130", "Id": "184224", "Score": "0", "body": "@Simon Hi I am writing a code very similar to this, and am thinking as the abstract class is abstract, would it not mean that the abstract class can not be instantiated? Many Thanks" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T19:50:46.680", "Id": "43095", "ParentId": "43084", "Score": "13" } }, { "body": "<h3>Fraction representation</h3>\n\n<p>@Simon has a good suggestion, which I'll elaborate on: <code>Fraction</code> should be immutable, for <a href=\"http://www.javalobby.org/articles/immutable/\" rel=\"nofollow\">several reasons</a>:</p>\n\n<ul>\n<li><strong>Reduce defensive copying:</strong> In a more complex application, you'll be passing <code>Fraction</code>s around. If fractions are not immutable, then each function that you pass it to will want to make a defensive copy to make sure that it stays consistent even if the original object's value changes. For example, if you use a <code>Fraction</code> as a key in a <code>HashMap</code>, the <code>HashMap</code> could become inconsistent, because <code>HashMap</code> doesn't make a defensive copy.</li>\n<li><strong>Better constructor:</strong> It's good practice to create objects that are in a self-consistent, usable state. The default constructor is what I would call a half-assed constructor. In fact, <code>new Fraction()</code> produces an illegal value (the denominator is zero). It would be better to force users to call a <code>Fraction(int numerator, int denominator)</code> constructor.</li>\n<li><strong>Consistency:</strong> The <code>Integer</code> and <code>BigDecimal</code> classes in Java are also immutable. The language designers have thought it through; you should probably go with the flow.</li>\n<li><strong>Simpler notation:</strong> If the numerator and denominator were <code>final</code>, then you could consider making them <code>public</code> as well. (This suggestion may be controversial, and you may choose to ignore it.)</li>\n</ul>\n\n<p>The <code>Fraction</code> class shouldn't be tied to <code>System.out</code> in any way. Instead of <code>display()</code>, implement <code>toString()</code>.</p>\n\n<h3>Operator representation</h3>\n\n<p>All of your operators have something in common, and should implement a common interface or extend from a common base class.</p>\n\n<p>You don't really want to the object to include its operands — you'd have to instantiate a new one for each calculation. You can make them singletons instead.</p>\n\n<p>Suggestion (there are a lot of ideas here):</p>\n\n<pre><code>public interface FractionBinaryOperator {\n Fraction calculate(Fraction a, Fraction b);\n}\n\npublic class FractionalDivision implements FractionBinaryOperator {\n /**\n * Singleton\n */\n public static final OPERATOR = new FractionalDivision();\n private FractionalDivision() {}\n\n Fraction calculate(Fraction dividend, Fraction divisor) {\n return FractionalMultiplication.OPERATOR.calculate(dividend, divisor.reciprocal());\n }\n}\n</code></pre>\n\n<p>A more advanced approach, using anonymous inner classes:</p>\n\n<pre><code>public abstract class Operator {\n public abstract Fraction calculate(Fraction a, Fraction b);\n\n …\n\n public static final Operator MUL = new Operator() {\n public Fraction calculate(Fraction a, Fraction b) {\n return new Fraction(a.numerator * b.numerator, a.denominator * b.denominator);\n }\n }; \n\n public static final Operator DIV = new Operator() {\n public Fraction calculate(Fraction dividend, Fraction divisor) {\n return Operator.MUL.calculate(dividend, divisor.reciprocal());\n }\n };\n}\n\npublic class FractionsApp {\n public static void main(String[] args) {\n …\n System.out.println(Operator.ADD.calculate(fraction1, fraction2));\n …\n }\n}\n</code></pre>\n\n<h3>Error handling</h3>\n\n<p><code>Division.calculate()</code> shouldn't print a complaint when dividing by zero. Code that calculates should stick to calculating, and shouldn't concern itself with input/output. Instead, it should throw an exception, and let the caller decide how to handle it. In fact, if you don't check for a zero divisor, Java will naturally throw an <code>ArithmeticException</code> for you. You just have to have <code>main()</code> catch it and display a nicer message.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T20:55:41.797", "Id": "74357", "Score": "0", "body": "Thank you for pointing out those things. That help a lot." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-03T08:25:56.370", "Id": "74690", "Score": "0", "body": "I agree with @200_success's error handling advice. But a few words need to be said to make a finer point. If you want a `RuntimeException` that you throw, such as `ArithmeticException`, be caught and handled by the callers of that method (including code yourself have written), you should declare that your method `throws` that exception. And If you want \"division by zero\" be handled differently from **any other potential `ArithmeticException` ever** you should throw some custom exception, which possibly extends `ArithmeticException`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T20:43:16.350", "Id": "43098", "ParentId": "43084", "Score": "12" } }, { "body": "<p>While there are some good points in other answers, I would suggest something completely different. OOP is not only about Polymorphism and Inheritance towards which you intuitively designed your operation classes, although incompletely and it was pointed out by Simon André Forsberg. OOP is also about Encapsulation which is often neglected by many. Encapsulation simply says that you have to hide the details of your implementation behind the public interface. This has a good side effect which is one of the most important OOP features: it makes you keep your data and routines that operate on that data together in one place. Encapsulation is what differentiates OOP from Procedural programming. A related principle is called <a href=\"http://martinfowler.com/bliki/TellDontAsk.html\" rel=\"nofollow\">Tell, Don't Ask</a>.</p>\n\n<p>This said, a proper OOP-style design would be to convert the operation classes to methods of the <code>Fraction</code> class</p>\n\n<pre><code>public class Fraction {\n public void add(Fraction fraction) {}\n public void subtract(Fraction fraction) {}\n public void multiply(Fraction fraction) {}\n public void divide(Fraction fraction) {}\n}\n</code></pre>\n\n<p>Another thing is that you should make use of a constructor other than the default one. The constructor will ensure that the newly created <code>fraction</code> is complete and good to go. What happens if someone tries to perform an operation on a fraction without setting the numerator and denominator first? This will force you to validate fractions before each operation. Constructor also is a good way to specify the required object properties</p>\n\n<pre><code>public class Fraction {\n public Fraction(int numerator, int denominator) {}\n public void add(Fraction fraction) {}\n public void subtract(Fraction fraction) {}\n public void multiply(Fraction fraction) {}\n public void divide(Fraction fraction) {}\n}\n</code></pre>\n\n<p>Also, I agree with 200_success on that the <code>Fraction</code> class should be immutable</p>\n\n<pre><code>public class Fraction {\n public Fraction(int numerator, int denominator) {}\n public Fraction add(Fraction fraction) {}\n public Fraction subtract(Fraction fraction) {}\n public Fraction multiply(Fraction fraction) {}\n public Fraction divide(Fraction fraction) {}\n}\n</code></pre>\n\n<p>PS. If you want to have a set of operations, <code>Enum</code> would be a better choice.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-17T21:57:39.067", "Id": "109132", "Score": "0", "body": "I think this is the most valuable piece of advice. All the other answers point out important aspects but creating and encapsulating abstract data types is very important" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-04T09:29:19.843", "Id": "43388", "ParentId": "43084", "Score": "4" } }, { "body": "<p><strong>DRY your code</strong></p>\n\n<p>In every place where you used copy+paste - you should check whether you could refactor it to re-use the code you've written. Aside from making the code shorter and easier on the eyes, it also makes it more maintainable, as if you need to fix something, you don't need to fix it for <em>every copy</em> of the code.</p>\n\n<p>@Simon already addressed the Polymorphism of the <code>Calaculate</code> classes, but it is not all about OOP, for example, to prompt the user for the second fraction, you've copied the code from the first fraction. Your error handling there is also copied from one prompt to another - since you stop the program after each failure, you don't need to catch each one in flow - one catch at the end of the prompting it enough:</p>\n\n<pre><code>private Fraction promptForFraction(string name) {\n Fraction fraction = new Fraction();\n do {\n System.out.println(\"Enter values for fraction \" + name);\n Messages.insertNumerator();\n fraction.setNumerator(keyboard.nextInt()); // get user input\n\n Messages.inputDenominator();\n fraction.setDenominator(keyboard.nextInt()); // get user input\n if (fraction.getDenominator() == 0) { // check for x/0 error\n Messages.DenominatorCannotBeZero();\n }\n } while (fraction.getDenominator() == 0);\n\n System.out.print(\"Fraction \" + name + \" : \");\n fraction.display();\n Messages.newLine();\n return fraction;\n}\n\npublic static void main(String args[]) {\n\n // Display application header\n Messages.displayHeader();\n\n Fraction fraction1 = null;\n Fraction fraction2 = null;\n try {\n\n fraction1 = promptForFraction(\"one\"); // first fraction\n fraction2 = promptForFraction(\"two\"); // second fraction\n\n } catch (Exception e) {\n Messages.inputError(e); // display error\n return;\n }\n\n // snip...\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-04T11:32:18.643", "Id": "43396", "ParentId": "43084", "Score": "4" } }, { "body": "<p>From a mathematical viewpoint it would be important that your fractions will be reduced to a minimal representation by removing common factors to numerator and denominator. So a private function <code>Fraction.normalize</code> is expected to reduce the terms and put the (possible) negative sign in the numerator.</p>\n\n<p>This is useful for several reasons:</p>\n\n<ol>\n<li><p>numerator and denominator could grow so big that computations are no longer possible;</p></li>\n<li><p>it makes easier to compare two fractions</p></li>\n<li><p>it makes output more clean: \\$\\frac{-1}{2}\\$ is far better than \\$\\frac{5}{-10}\\$</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-17T14:57:52.133", "Id": "60300", "ParentId": "43084", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T18:29:47.083", "Id": "43084", "Score": "12", "Tags": [ "java", "calculator", "rational-numbers" ], "Title": "Java Fraction Calculator" }
43084
<p>This is the requirement I have (from the book: Cracking the Coding Interview)</p> <blockquote> <p>Imagine you have a call center with three levels of employees: fresher, technical lead (TL), and product manager (PM). There can be multiple employees, but only one TL or PM. An incoming telephone call must be allocated to a fresher who is free. If a fresher can't handle the call, he or she must escalate the call to technical lead. If the TL is not free or not able to handle it, then the call should be escalated to PM. Design the classes and data structures for this problem. Implement a method <code>getCallHandler()</code>.</p> </blockquote> <p>And this is my implementation:</p> <pre><code>public interface CallAllocator { public Employee getCallHandler() throws NoEmployeeInTheHouseException; void setTL(TechnicalLead technicalLead); void setPM(ProductManager productManager); void addFresher(Fresher fresher); } </code></pre> <p>Implementation for the interface:</p> <pre><code>public class CallAllocatorImpl implements CallAllocator { private TechnicalLead technicalLead; private ProductManager productManager; private List&lt;Fresher&gt; freshers = new ArrayList&lt;Fresher&gt;(); @Override public Employee getCallHandler() throws NoEmployeeInTheHouseException { if (freshers.isEmpty() &amp;&amp; technicalLead == null &amp;&amp; productManager == null) { throw new NoEmployeeInTheHouseException(); } if (!freshers.isEmpty()) { Employee fresher = freshers.get(new Random().nextInt(freshers.size())); if (fresher.getCanHandle()) { return fresher; } } if (technicalLead != null &amp;&amp; technicalLead.getCanHandle()) { return technicalLead; } if (productManager != null &amp;&amp; productManager.getCanHandle()) { return productManager; } throw new NoEmployeeInTheHouseException(); } @Override public void setTL(TechnicalLead technicalLead) { this.technicalLead = technicalLead; } @Override public void setPM(ProductManager productManager) { this.productManager = productManager; } @Override public void addFresher(Fresher fresher) { if (fresher.isFree()) { freshers.add(fresher); } } } </code></pre> <p>Employee class:</p> <pre><code>public class Employee { private boolean free; private boolean canHandle; public boolean isFree() { return free; } public void setFree(boolean free) { this.free = free; } public boolean getCanHandle() { return canHandle; } public void setCanHandle(boolean canHandle) { this.canHandle = canHandle; } } </code></pre> <p>I have 3 classes with names: <strong>Fresher, TechnicalLead and ProductManager</strong>. They all extend <strong>Employee</strong> but do not override any methods or anything..</p> <p>And this is my TestClass:</p> <pre><code>public class TestClass { public static void main(String[] args) throws NoEmployeeInTheHouseException { CallAllocator callAllocator = new CallAllocatorImpl(); Fresher fresherOne = new Fresher(); fresherOne.setCanHandle(false); fresherOne.setFree(true); Fresher fresherTwo = new Fresher(); fresherTwo.setCanHandle(true); fresherTwo.setFree(true); Fresher fresherThree = new Fresher(); fresherThree.setCanHandle(false); fresherThree.setFree(true); Fresher fresherFour = new Fresher(); fresherFour.setCanHandle(false); fresherFour.setFree(false); callAllocator.addFresher(fresherOne); callAllocator.addFresher(fresherTwo); callAllocator.addFresher(fresherThree); callAllocator.addFresher(fresherFour); TechnicalLead technicalLead = new TechnicalLead(); technicalLead.setCanHandle(false); technicalLead.setFree(true); callAllocator.setTL(technicalLead); ProductManager productManager = new ProductManager(); productManager.setCanHandle(true); productManager.setFree(true); callAllocator.setPM(productManager); Employee callHandler = callAllocator.getCallHandler(); System.out.println(callHandler.getClass().getSimpleName()); } } </code></pre> <p>So how can I improve this code? Any suggestions? </p>
[]
[ { "body": "<p>Overall, code is easy to read.</p>\n\n<p>A few minor nit-picky items.</p>\n\n<p>Try not us use <code>booleans</code>, use <code>enums</code> instead.</p>\n\n<p>i.e. </p>\n\n<pre><code>public enum EmployeeStatus {\n OnCall,\n Available \n}\n</code></pre>\n\n<p>This allows you to add more status as requirements change:</p>\n\n<pre><code>public enum EmployeeStatus {\n OnCall,\n Available,\n OutToLunch,\n OnVacation,\n OnBreak\n}\n</code></pre>\n\n<p>I don't like that <code>getCallHandler()</code> can populate the freshers. I would inject the list or maybe a factory that will be able to do that. This will decouple the code, and allow for much easier unit testing in the future.</p>\n\n<p>I also don't like the set methods. Using inheritance should eliminate the need for that. Admittedly I don't see the solution right now, but there is one there. Basically by having different methods to handle different instances, you are tying yourself to those three types. What happens if you add a forth type, say ProductExpert? You now have to change this class to deal with it. </p>\n\n<p>The <code>canHandle</code> method seems like it should be a calculation based off the status enum. This way you only have to set one flag in the class, not two.</p>\n\n<pre><code>public class Employee {\n\n // code\n\n public boolean isFree() {\n return status == EmployeeStatus.Available;\n }\n\n // code\n}\n\nFresher fresherTwo = new Fresher();\nfresherTwo.setStatus(EmployeeStatus.Available);\n</code></pre>\n\n<p>I also don't like the name `NoEmployeeInTheHouseException', I find it a little too causal. I would do something line 'NoEmployeeAvailableException' or something. It comes across as a little more businesslike.</p>\n\n<p>This is a good start, and I'm glad you are concerned about this stuff. Keep working at it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T19:22:40.630", "Id": "74340", "Score": "0", "body": "What do you mean I don't like that getCallHandler() can populate the freshers. ? This method does not populate freshers?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T19:31:36.660", "Id": "74341", "Score": "1", "body": "I think its bad practice when I class can populate itself. The analogy that is most used is that you don't expect a car to know how to build itself, you build it up with pieces using other machines..." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T19:15:30.687", "Id": "43089", "ParentId": "43087", "Score": "13" } }, { "body": "<p>Firstly, I'm not sure you're actually implementing the requirement as it's written. The description says:</p>\n\n<p>An incoming call must be allocated to a fresher who is free. If a fresher can't handle the call, he or she must escalate to technical lead.</p>\n\n<p>This sounds like if there are no free freshers, the call shouldn't be handled at all (an exception thrown?), rather than skipping to the TL. This sort of makes sense as a real world requirement: it may be preferable for a caller to have to call back a bit later if there are no freshers available, rather than to waste the technical lead's time with a call that a fresher should be able to handle. Whatever calls this could, for example, plan to catch that exception and do <code>addCallToUnhandledCallQueue()</code> or whatever.</p>\n\n<p>This also goes a bit more to the meat of the question, which I believe is trying to get you to answer with the chain-of-responsibility pattern. In this pattern each object (in this case an <code>Employee</code>) responsible for processing a command (in this case a call) contains logic to check whether it is capable of processing a given command, and if not, also knows the next object in the chain to call.</p>\n\n<p>One benefit from this pattern is adherence to the open/close principle. As you'll see below, doing something like adding a new employee type or changing the structure a bit is unlikely to require you to fiddle around with <code>if{...} else{...}</code> logic in <code>getCallHandler()</code>. Additionally, it means that <code>Employee</code>s only need to know about their immediate boss, rather than some master class having to know and persist the entire employee structure (which would fast become unpleasant, especially if you need to add other methods which also require knowing this structure).</p>\n\n<p>A meta-benefit, given that this is apparently to be approached as an interview question, is that if somebody asked me this in an interview, I'd be pretty sure they'd <em>want</em> me to talk about this pattern, so even if for whatever reason you ultimately decide there's a better solution, it's important to understand this one if only to be able to describe intelligently why you reject it.</p>\n\n<p>So using this pattern, your <code>getCallHandler(Call call)</code> method would look something like this:</p>\n\n<pre><code>Employee fresher = getAnyFreeFresher(); //Should throw if there are none\nreturn fresher.handle(call);\n</code></pre>\n\n<p>Then the <code>Employee</code> class would look something like:</p>\n\n<pre><code>public class Employee{\n private Employee boss;\n\n private bool canHandle(Call call){\n //...\n }\n\n public Employee handle(Call call){\n if(canHandle(call)){\n return this;\n }\n if(boss == null){\n //Nobody in the chain could handle, throw\n }\n return boss.handle(call);\n }\n}\n</code></pre>\n\n<p>That's a very rough outline, there's detail to fill in on how bosses are set, and you'd probably want employee types to inherit from <code>Employee</code> to implement <code>canHandle</code>, etc.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T19:32:22.677", "Id": "74342", "Score": "0", "body": "Thanks for the answer, I see your point. Maybe you are right, maybe I totally got the requirement wrong. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T22:00:24.260", "Id": "74367", "Score": "2", "body": "Absolute agreement on the main point: you are not solving a problem, you are in an interview. Your priority is not to understand the problem; it is to understand the problem under the interviewer eyes." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T19:30:23.393", "Id": "43093", "ParentId": "43087", "Score": "20" } }, { "body": "<h2>Naming Issue</h2>\n\n<ul>\n<li><code>CallAllocatorImpl</code> have a group of freshers, TL &amp; a PM. So I think naming it <code>Office</code> or <code>CallCenter</code> seems feasible.</li>\n<li><code>getCanHandle</code> is misleading. You won't usually see methods name have <code>get</code> and <code>can</code> both. Secondly what to handle? <strong>Call</strong>. So <code>canHandleCall</code> seems reasonable.</li>\n<li>Same goes for <code>setCanHandle</code>.</li>\n</ul>\n\n<hr>\n\n<h2>Answer the Question properly</h2>\n\n<blockquote>\n <p>There can be multiple employees, but <strong>only one</strong> TL or PM</p>\n</blockquote>\n\n<p>Smelling a <em>singleton-ish</em> work.</p>\n\n<p>So <code>setTL</code> needs few more LOC</p>\n\n<pre><code>public void setTL(TechnicalLead technicalLead) {\n if(technicalLead == null) {\n this.technicalLead = technicalLead;\n }\n else {\n throw new TLAlreadyExistsException(\"Only one Team-Leader allowed\").\n }\n}\n</code></pre>\n\n<p>Same goes for <code>setPM</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T23:07:19.310", "Id": "74370", "Score": "3", "body": "Well, two points of disagreement. First I wouldn't use the word \"singleton\" with to that, even after appending an \"ish\". The singleton pattern is a specific thing, which that isn't. Second, that exception makes no sense there. If you set something that already exists, you're replacing it, not trying to add another one. What you're suggesting is actually immutability, which is pretty much unrelated to only having one. Just having a single TechnicalLead rather than a collection is sufficient." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T01:49:48.873", "Id": "74395", "Score": "0", "body": "`CallAllocatorImpl` is the implementation of `CallAllocator`, so if you changed the name of the implementation you need to change the name of the interface too." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T22:22:18.827", "Id": "43100", "ParentId": "43087", "Score": "2" } }, { "body": "<p>First I will comment on your implementation, then I will propose my version at the end.</p>\n\n<p>Here we go, from top to bottom:</p>\n\n<pre><code>public interface CallAllocator {\n public Employee getCallHandler() throws NoEmployeeInTheHouseException;\n void setTL(TechnicalLead technicalLead);\n void setPM(ProductManager productManager);\n void addFresher(Fresher fresher);\n}\n</code></pre>\n\n<ul>\n<li><p>\"Employee\" is too generic a term for somebody who handles calls. I would call it <code>ICallHandler</code>. The actual employee classes are irrelevant in the discussion of handling calls, they should not be part of the model design.</p></li>\n<li><p>The <code>setTL</code>, <code>setPM</code>, <code>addFresher</code> methods all use terms and arguments that are too implementation specific. An interface definition should be as abstract as possible.</p></li>\n</ul>\n\n<p>Next:</p>\n\n<pre><code>if (freshers.isEmpty() &amp;&amp; technicalLead == null &amp;&amp; productManager == null) {\n throw new NoEmployeeInTheHouseException();\n}\n</code></pre>\n\n<p>I see that in your implementation you handle the availability of freshers/lead/manager as being empty or null. This is state management, not modeling. It would be better to capture the notion of being available or not by the model, using explicit interface methods.</p>\n\n<pre><code>if (!freshers.isEmpty()) {\n Employee fresher = freshers.get(new Random().nextInt(freshers.size()));\n if (fresher.getCanHandle()) {\n return fresher;\n }\n}\n</code></pre>\n\n<ul>\n<li><code>getCanHandle</code> is really awkward, <code>canHandle</code> would be more natural</li>\n<li>The notion of getting the next available fresher deserves its own method: you can think of different implementations, such as pick any free fresher at random, or pick the least picked, or pick the most picked, and so on.</li>\n</ul>\n\n<p>Ok so here's my solution to model the description quite accurately:</p>\n\n<pre><code>interface ITicket {}\n\ninterface ICallHandler {\n boolean isAvailable();\n boolean canHandle(ITicket ticket);\n}\n\ninterface ICallHandlerPicker {\n ICallHandler getAvailableCallHandler();\n}\n\ninterface ICallCenter {\n ICallHandler getCallHandler(ITicket ticket);\n}\n\nclass SingleLeadSingleManagerCallCenter implements ICallCenter {\n private final ICallHandlerPicker picker;\n private final ICallHandler lead;\n private final ICallHandler manager;\n\n SingleLeadSingleManagerCallCenter(ICallHandlerPicker picker, ICallHandler lead, ICallHandler manager) {\n this.picker = picker;\n this.lead = lead;\n this.manager = manager;\n }\n\n @Override\n public ICallHandler getCallHandler(ITicket ticket) {\n ICallHandler handler = picker.getAvailableCallHandler();\n if (handler == null) {\n // nobody available. perhaps throw new NoSuchElementException() ?\n return null;\n }\n if (handler.canHandle(ticket)) {\n return handler;\n }\n if (lead.isAvailable() &amp;&amp; lead.canHandle(ticket)) {\n return lead;\n }\n return manager;\n }\n}\n</code></pre>\n\n<p>This sticks to the well-defined parts of the description and leaves the undefined parts unimplemented on purpose, such as:</p>\n\n<ul>\n<li>If there are many free freshers, which one to pick? --> implement as you like</li>\n<li>If there are no free freshers, what to do? --> null implies that there's nobody to handle, though I admin I don't like this part much</li>\n</ul>\n\n<p>Other things to note:</p>\n\n<ul>\n<li>The interfaces are short and to the point, with only getters, no mutators</li>\n<li>The class members are all final, and the class is fully defined at construction time, there's no room left for guessing</li>\n<li>In terms of handling calls, the tech lead and product manager are call handlers just like the freshers, so using interfaces makes good sense, no need to give them dedicated classes</li>\n</ul>\n\n<p>Of course this is not scalable. The description itself excluded scalability by specifying a single tech lead and a single product manager. I would fix that by modeling the multiple levels as a chain of call centers:</p>\n\n<pre><code>class MultiLevelCallCenter implements ICallCenter {\n private final ICallHandlerPicker picker;\n private final ICallCenter nextCallCenter;\n\n MultiLevelCallCenter(ICallHandlerPicker picker, ICallCenter nextCallCenter) {\n this.picker = picker;\n this.nextCallCenter = nextCallCenter;\n }\n\n @Override\n public ICallHandler getCallHandler(ITicket ticket) {\n ICallHandler handler = picker.getAvailableCallHandler();\n if (handler == null) {\n // nobody available. perhaps throw new NoSuchElementException() ?\n return null;\n }\n if (handler.canHandle(ticket)) {\n return handler;\n }\n return nextCallCenter.getCallHandler(ticket);\n }\n}\n\nclass UltimateCallCenter implements ICallCenter {\n private final ICallHandler handler;\n\n UltimateCallCenter(ICallHandler handler) {\n this.handler = handler;\n }\n\n @Override\n public ICallHandler getCallHandler(ITicket ticket) {\n return handler.isAvailable() ? handler : null;\n }\n}\n</code></pre>\n\n<p>Then, we could implement the call center in the description in terms of these more scalable classes as:</p>\n\n<pre><code>ICallCenter getSingleLeadSingleManagerCallCenter(ICallHandlerPicker picker, final ICallHandler lead, ICallHandler manager) {\n ICallCenter managerCallCenter = new UltimateCallCenter(manager);\n ICallCenter leadCallCenter = new MultiLevelCallCenter(new ICallHandlerPicker() {\n @Override\n public ICallHandler getAvailableCallHandler() {\n return lead.isAvailable() ? lead : null;\n }\n }, managerCallCenter);\n return new MultiLevelCallCenter(picker, leadCallCenter);\n}\n</code></pre>\n\n<p>Again, I left out the details of the freshers and how we pick them. These are not specified in the description, and not really relevant. This leaves you free to inject whatever implementation you like.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T08:58:16.770", "Id": "43125", "ParentId": "43087", "Score": "3" } }, { "body": "<p><strong>Naming:</strong>\nI don't know the Java coding convention but names of setters and getters such as setCanHandle() look a bit awkward to me.</p>\n\n<p>In my opinion the logic whether an Employee can handle a call can be encapsulated by the class. In my own C# implementation I've decided to use <a href=\"https://en.wikipedia.org/wiki/Chain-of-responsibility_pattern\" rel=\"nofollow\">Chain-of-responsibility pattern</a> which looks more appropriate in this case. </p>\n\n<p>CallHandler class:</p>\n\n<pre><code>public interface ICallHandler\n{\n IResponse Handle(ICallContext callContext); \n bool IsFree { set; get; }\n bool CanHandle { get; } \n}\n\npublic abstract class CallHandlerBase : ICallHandler\n{\n private ICallHandler _successor;\n\n public CallHandlerBase(ICallHandler successor){\n _successor = successor;\n }\n\n //logic whether a call handler can handle a call\n public abstract bool CanHandle { get; }\n\n public virtual bool IsFree { set; get; }\n\n public virtual IResponse Handle(ICallContext callContext)\n {\n IResponse response;\n if (CanHandle &amp;&amp; IsFree){\n //Handle logic\n response = new Response();\n } else {\n //escalate to the successor\n response = _successor.Handle(callContext);\n }\n return response;\n }\n}\n\npublic class Fresher : CallHandlerBase{ }\n\npublic class TeamLead : CallHandlerBase{ }\n\npublic class ProductManager : CallHandlerBase\n{ \n //PM always can handle a call \n public override bool CanHandle{\n return true;\n }\n}\n</code></pre>\n\n<p>I would've also encapsulated the logic of getting a new fresher. In this case an <a href=\"https://en.wikipedia.org/wiki/Object_pool_pattern\" rel=\"nofollow\">ObjectPool</a> to keep freshers looks very convenient.</p>\n\n<pre><code>public class CallCenter\n{ \n private ICallHandler _teamLead;\n private ICallHandler _productManager; \n private ObjectPool&lt;ICallHandler&gt; _freshersPool;\n\n public class CallCenter(ICallHandler productManager, ICallHandler teamLead, Func&lt;ICallHandler&gt; createFresher){ \n _freshersPool = new ObjectPool&lt;ICallHandler&gt; (createFresher);\n }\n\n public ICallHandler GetCallHandler(){\n fresher = _objectPool.GetObject();\n return fresher;\n }\n\n public void SetFree(ICallHandler handler){\n _freshersPool.PutObject(handler);\n }\n}\n</code></pre>\n\n<p>Clients code:</p>\n\n<pre><code>var productManager = new ProductManager(); \nvar teamLead = new TeamLead(productManager);\n\nvar callCenter = new CallCenter(productManager, teamLead, () =&gt; new Fresher(teamLead));\nvar callHandler = callCenter.GetCallHandler();\n\nvar callContext = new CallContext();\nvar response = callHandler.Handle(callContext); \ncallCenter.SetFree(callHandler);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-02-28T11:24:21.110", "Id": "121357", "ParentId": "43087", "Score": "1" } } ]
{ "AcceptedAnswerId": "43093", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T18:50:50.533", "Id": "43087", "Score": "23", "Tags": [ "java", "object-oriented", "beginner", "interview-questions", "inheritance" ], "Title": "Modelling a Call Center" }
43087
<p>Some time ago I made my simple game loop, so here's the code:</p> <pre><code>public class Game { private final int TARGET_FPS = 60; /** optimal waiting time in milliseconds */ private final long OPTIMAL_TIME = 1000 / TARGET_FPS; /** last Frame time */ private long lastFrame; private int fps; /** last FPS time in ms */ private long lastFPS; private boolean running; public Game() { running = true; } public static void main(String[] args) { Game game = new Game(); game.gameLoop(); } private void gameLoop() { initialize(); while (running) { int delta = getDelta(); update(delta); render(); synchronize(lastFrame - getTime() + OPTIMAL_TIME); } } private void initialize() { getDelta(); lastFPS = getTime(); } private void update(int delta) { // ToDo updateFPS(); } private void render() { // ToDo } private void synchronize(long ms) { try { if (ms &gt; 0) { Thread.sleep(ms); } } catch (InterruptedException ex) { System.err.println(ex.getMessage()); System.exit(-1); } } /** * Returns System time in milliseconnds * @return System time in ms */ private long getTime() { return System.nanoTime() / 1000000; } /** * Returns time difference since the last Frame * @return time difference in ms */ private int getDelta() { long time = getTime(); int delta = (int) (time - lastFrame); lastFrame = time; return delta; } private void updateFPS() { if (getTime() - lastFPS &gt; 1000) { System.out.println("FPS: " + fps); fps = 0; lastFPS += 1000; } fps++; } } </code></pre> <p>Now I want to ask, what can I improve here?</p> <p>One thing that I would really like to change is the <code>updateFPS()</code> method. Of course that <code>System.out</code> would get deleted, but recently I thought about lastFPS... if the game is running long enough then it could overflow right? Because of that I tried to solve it like this:</p> <pre><code>private void updateFPS(int delta) { if (lastFPS &gt; 1000) { System.out.println("FPS: " + fps); fps = 0; lastFPS = 0; } lastFPS += delta; fps++; } </code></pre> <p>Running fine so far, but there's something that bothers me:</p> <p>When I count the fps in the original version it usually gets fps between 59-60, but when I try that new version it'll show 61-62 fps. I don't know... can the new version be faster after that change or is my calculation wrong?</p>
[]
[ { "body": "<p>I would expect that your loop will run at 62.5 FPS based on the code you have.... but with some variation on timers and rounding-down, I would expect that to drop slightly to 61 FPS occasionally.</p>\n\n<p>This would reflect your results where you see between 61 and 62 FPS.</p>\n\n<p>Why?</p>\n\n<p>Because your code is full of integer-division, and you are losing precision everywhere.</p>\n\n<p>Consider the first statements in your code:</p>\n\n<blockquote>\n<pre><code>private final int TARGET_FPS = 60;\n/** optimal waiting time in milliseconds */\nprivate final long OPTIMAL_TIME = 1000 / TARGET_FPS;\n</code></pre>\n</blockquote>\n\n<p>Target frames-per-second is 60.</p>\n\n<p>Now, 1000ms / 60 is 16.666 milliseconds, except, it's not. It is 16ms because you are doing integer division.</p>\n\n<p>So, your frame period is set at 16ms... with 16ms frames, you get and actual FPS of 62.5 FPS.</p>\n\n<p>But, later on, calculate the current time in milliseconds as:</p>\n\n<blockquote>\n<pre><code>private long getTime() {\n return System.nanoTime() / 1000000;\n}\n</code></pre>\n</blockquote>\n\n<p>Which does another integer division... and the use of nanoTime is completely useless because all the nanoseconds are simply lost. so you don't do any 'rounding' on the code.</p>\n\n<p>The code is full of these types of integer-based division problems.</p>\n\n<p>What you need to do is settle on just using values denominated in nanoseconds. The rounding errors will be 1 millionth of what you have now, and the time constraints will 'just work'.</p>\n\n<p>Note that the <code>Thread.sleep(long, TimeUnit)</code> method allows you to specify Nanosecond delays, but the reality is that it will not help because many systems are not that granular with their interrupts.</p>\n\n<p>Having said all of that, what you really want to do is use a repeating timer with a gated access to a result.</p>\n\n<p>Set up a <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Executors.html#newScheduledThreadPool%28int%29\" rel=\"nofollow\">ScheduledThreadPool</a> which can either run your frame's work, or alternatively it can gate the main thread.</p>\n\n<p>This would be the best way to get consistent (and predictable) frame rates</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T20:04:29.573", "Id": "74344", "Score": "1", "body": "Well I thought using integer was okay because ``Thread.sleep()`` won't take some floats. Didn't consider the rounding erros would be relevant. But I'll definitely look into that ``ScheduledThreadPool`` :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T19:19:04.960", "Id": "43090", "ParentId": "43088", "Score": "4" } } ]
{ "AcceptedAnswerId": "43090", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T18:55:45.937", "Id": "43088", "Score": "5", "Tags": [ "java", "game" ], "Title": "Game Loop and FPS" }
43088
<p>I've been considering the pro's and con's between implementing my page objects with privately backed properties and lazily instantiating them or just returning new instances every time and am curious what other people think is the best practice.</p> <p>For example, I could have something like;</p> <pre><code> private IWebElement title = null; public IWebElement Title { get { if (title == null) title = _driver.FindElement(By.Id("Title")); return title; } } </code></pre> <p>To represent a button on the page, or I could just have;</p> <pre><code> public IWebElement Title { get { _driver.FindElement(By.Id("Title")); } } </code></pre> <p>Which method do you think is better and why?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T20:43:22.090", "Id": "74352", "Score": "0", "body": "Can you explain why this is considered too opinion based? You could easily provide data to support a design decision and it's codereview... is there any code review that isn't opinion based? I spent quite awhile last night looking for blog posts/papers that provided some data to support the differences between these approaches but couldn't find anything, based on that this seemed like the best place to ask." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T20:57:50.447", "Id": "74358", "Score": "2", "body": "In our [about] page, it says the following: Don't ask about: Best practices in general (that is, it's okay to ask \"Does this code follow common best practices?\", but not \"What is the best practice regarding X?\")" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T21:00:45.590", "Id": "74362", "Score": "1", "body": "Also, you ask about \"what other people **think** is the **best practice**\" and \"Which method do you **think** is better and **why?**\". Basically, it all depends on which parameters you consider for something to be \"best practice\". You are right that code review is often opinion based, but this question is *primarily* opinion based. You're asking \"Which is best, A or B?\" and generally such questions are not well appreciated around here." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T21:35:57.327", "Id": "74365", "Score": "0", "body": "@SimonAndréForsberg this is a code review site, code reviews are inherently opinion based... The examples in your about are just people posting their opinions about how to implement something. This community is even more pretentious than SO's which is saying a lot." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T22:28:33.503", "Id": "74368", "Score": "2", "body": "If you really feel so, please start a question on our [meta] to discuss the on-topicness off this question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T22:47:58.677", "Id": "74369", "Score": "0", "body": "Yes, this sounds opinion-based. It's also not really asking for a code review, just a comparison of two example code snippets. This question may be better for Programmers, which deals with best practices in general. You should also revise the question to request credible info instead of opinions." } ]
[ { "body": "<p>That all really depends on one thing and one thing only:</p>\n\n<p><strong>How costly</strong> is the <code>_driver.FindElement(By.Id(\"Title\"));</code> operation?</p>\n\n<p>Secondly... OK then, maybe two things: <strong>How often</strong> do you plan on calling this method?</p>\n\n<p>If the operation is cheap, I would use the return directly version.<br /> If the operation is costly, use the approach with the variable.</p>\n\n<p>Additionally, if this is a multi-threaded environment - or rather, <em>when</em> this possibly becomes a multi-threaded environment - the first approach goes out the window unless you synchronize on some lock (which will add some additional overhead). The first approach as it looks today is not thread safe at all.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T20:24:29.907", "Id": "74349", "Score": "0", "body": "I would add that the variable approach, as shown, has no thread-safety." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T20:29:36.543", "Id": "74350", "Score": "0", "body": "@JesseC.Slicer Good thinking, added that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T20:51:42.557", "Id": "74354", "Score": "0", "body": "@SimonAndréForsberg aside from the thread safety points that's the main trade off I've been considering. I was hoping someone would provide something more concrete like a nice little table with data for various scenarios, something I can actually make an educated guess with... Perhaps I'll have to do it myself." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T20:55:30.170", "Id": "74356", "Score": "2", "body": "@evanmcdonnal As we don't have the same computer, the same code, the same anything. You really should do it yourself." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T21:09:51.707", "Id": "74363", "Score": "0", "body": "@evanmcdonnal Remember though that if you make some code to compare the different scenarios, we'd gladly review that code to see if you can make it more flexible and prettier :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T21:25:26.803", "Id": "74364", "Score": "0", "body": "@SimonAndréForsberg I disagree that not using my hardware, code ect is necessary. I can't find anywhere on the internet some ballpark numbers to get started with. The performance of find by id on a page with a given content length is not going to vary with everything else held the same. Simply a comparison of xpath look ups vs by id look ups would be extremely useful and isn't readily available online." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T20:12:07.300", "Id": "43097", "ParentId": "43094", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T19:37:01.677", "Id": "43094", "Score": "-1", "Tags": [ "c#" ], "Title": "lazy instantiation and instance lifetimes in POM" }
43094
<p>I'm using jQuery's <code>.get()</code> method to load content from external HTML files into my main index file. I created 25 different functions, function <code>videoLoad1()</code>, function <code>videoLoad2()</code> etc, for the 25 videos that I'm loading separately when its corresponding link is clicked. The content that is being swapped out in my HTML index file is the video src and video details. I'm new to jQuery and have been trying to find a more practical way of writing the code.</p> <p>HTML - links for the onclick function:</p> <pre><code>&lt;div class="row"&gt; &lt;div id="movie_list" class="movie_sec-1 pull-left"&gt; &lt;h6&gt;&lt;a href="Javascript:void(0);" id="cars_hb"&gt;cars.com: be honest&lt;/a&gt;&lt;/h6&gt; &lt;h6&gt;&lt;a href="Javascript:void(0);" id="cars_t"&gt;cars.com: tag&lt;/a&gt;&lt;/h6&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>HTML for video inclusion:</p> <pre><code>&lt;div id="kz-video" style="display: none;"&gt;&lt;/div&gt; </code></pre> <p>External HTML file that is being loaded via <code>$.get()</code> (file name is cars_bh.html):</p> <pre><code>&lt;div class="video-info"&gt; &lt;h1&gt;Video&lt;/h1&gt; &lt;h4&gt;Now Playing&lt;/h4&gt; &lt;h4&gt;cars.com: be honest&lt;/h4&gt; &lt;/div&gt; &lt;!-- Video --&gt; &lt;video id="kz-player" width="100%" height="100%" controls preload&gt; &lt;source src="vid/CarscomBeHonest.mp4" type='video/mp4;'&gt; &lt;source src="vid/CarscomBeHonest.webmhd.webm" type='video/webm;'&gt; &lt;source src="vid/CarscomBeHonest.oggtheora.ogv" type='video/ogg;'&gt; &lt;/video&gt; </code></pre> <p>jQuery function:</p> <pre><code>function videoLoad2() { $("a#cars_hb").click(function(e) { e.preventDefault(); e.stopPropagation(); $.get('cars_hb.html', function( data ) { $('#kz-video').html( data ); }); }); //close overlay/hide content $('.close').click(function (e) { e.stopPropagation(); $('#kz-player')[0].pause(); $('#kz-video').hide(); $('.close').fadeOut(800); $('#video_overlay').fadeOut(800); }); } </code></pre>
[]
[ { "body": "<p>When you say </p>\n\n<blockquote>\n <p>I created 25 different functions for the 25 videos that I'm loading separately when its corresponding link is clicked. </p>\n</blockquote>\n\n<p>Does that mean you have multiple <code>function videoLoad#() {</code> ? </p>\n\n<p>I think this will help: </p>\n\n<pre><code>$(\"div#movie_list a\").click(function (e) {\n e.preventDefault();\n e.stopPropagation();\n id = e.target.id;\n loadVideo(id);\n});\n\nfunction loadVideo(id) {\n file = id + \".html\";\n $.get(file, function (data) {\n $('#kz-video').html(data);\n });\n});\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T20:47:16.233", "Id": "74353", "Score": "0", "body": "yes. I created 25 different functions as you mentioned, ie function videoLoad1(), function videoLoad2(), etc. \n\nI'll try your suggestion. thanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T20:53:47.300", "Id": "74355", "Score": "0", "body": "I am writing a similar function to handle closing your videos in the same dynamic way. I'll edit my answer with a jsfiddle link soon. - Oh, nevermind. You only show one video at the time." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T20:57:50.733", "Id": "74359", "Score": "0", "body": "Note that I had improperly closed my click function. I have edited the line from `}` to `});`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T20:58:19.717", "Id": "74360", "Score": "0", "body": "yeah, but please share your fiddle. it might help someone else in the future!" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T20:45:15.657", "Id": "43099", "ParentId": "43096", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T19:54:53.430", "Id": "43096", "Score": "3", "Tags": [ "javascript", "beginner", "jquery", "html", "ajax" ], "Title": "Loading content from external HTML files" }
43096
<p>Currently I have a binary tree template setup where my main is using it with strings to make a question/answer game. I'm using a knowledge base that works as an interface to the binary tree that main uses. My code seems to work fine inserting/rearranging nodes as necessary but I think my design is pretty bad.</p> <p>Is it usually best to just put the <code>Node</code> and <code>BinaryTree</code> classes in the same file since neither is independently useful?</p> <p>I'm not sure how to not use class friending (assuming this is bad design) unless I just do away with the knowledge base. Without knowledge base being able to see <code>private</code> node members, it wouldn't be able to move it's "current" node pointer around the tree through questions/guesses unless it passed its current pointer by reference to a binary tree function that moved it each time.</p> <p>Also with this setup, the binary tree doesn't really do anything except provide a root node. I'm also unsure how to move some traversal, etc. functionality from <code>kbase</code> to <code>btree</code> without just making a bunch of <code>kbase</code> functions that call their <code>btree</code> counterparts. </p> <p>Is there a way to use <code>std::swap</code> in each file also without polluting with the utility header? This design looks to be bad OO-wise.</p> <p><strong>Node.h:</strong></p> <pre><code>#ifndef NODE_H #define NODE_H #include &lt;utility&gt; template&lt;typename T&gt; class Node { friend class KnowledgeBase&lt;T&gt;; public: Node() {lChild = rChild = nullptr;} Node(T&amp; newData) {lChild = rChild = nullptr; data = newData;} ~Node(); Node(const Node&amp;); bool isLeaf() {return (lChild == nullptr) &amp;&amp; (rChild == nullptr);} void setData(T newData) {data = newData;} void setRchild(Node* newRchild) {rChild = newRchild;} void setLchild(Node* newLchild) {lChild = newLchild;} Node&lt;T&gt;&amp; operator=(const Node); private: T data; Node *lChild; Node *rChild; }; template&lt;typename T&gt; Node&lt;T&gt;::~Node() { delete lChild; delete rChild; lChild = nullptr; rChild = nullptr; } template&lt;typename T&gt; Node&lt;T&gt;::Node(const Node&amp; other) { data = other.data; lChild = new Node&lt;T&gt;; rChild = new Node&lt;T&gt;; *lChild = *(other.lChild); *rChild = *(other.rChild); } template&lt;typename T&gt; Node&lt;T&gt;&amp; Node&lt;T&gt;::operator=(const Node other) { std::swap(data, other.data); std::swap(lChild, other.lChild); std::swap(rChild, other.rChild); return *this; } #endif /* NODE_H */ </code></pre> <p><strong>BinaryTree.h:</strong></p> <pre><code>#ifndef BINARYTREE_H #define BINARYTREE_H #include &lt;utility&gt; template&lt;typename T&gt; class Node; template&lt;typename T&gt; class KnowledgeBase; template&lt;typename T&gt; class BinaryTree { friend class KnowledgeBase&lt;T&gt;; public: BinaryTree() {root = nullptr;} ~BinaryTree() {delete root; root = nullptr;} BinaryTree(const BinaryTree&amp;); BinaryTree&lt;T&gt;&amp; operator=(const BinaryTree other); private: Node&lt;T&gt; *root; }; template&lt;typename T&gt; BinaryTree&lt;T&gt;::BinaryTree(const BinaryTree&amp; other) { root = new Node&lt;T&gt;; *root = *(other.root); } template&lt;typename T&gt; BinaryTree&lt;T&gt;&amp; BinaryTree&lt;T&gt;::operator=(const BinaryTree other) { std::swap(root, other.root); return *this; } #endif /* BINARYTREE_H */ </code></pre> <p><strong>KnowledgeBase.h:</strong></p> <pre><code>#ifndef KNOWLEDGEBASE_H #define KNOWLEDGEBASE_H #include &lt;utility&gt; template&lt;typename T&gt; class BinaryTree; template&lt;typename T&gt; class Node; template&lt;typename T&gt; class KnowledgeBase { public: KnowledgeBase(); ~KnowledgeBase() {delete current; current = nullptr;} KnowledgeBase(const KnowledgeBase&amp;); void addQandA(T&amp;, T&amp;, char); void giveUp() {unableToGuess = true; guessedWrong = true;} bool outOfQ() {return unableToGuess == true;} bool isGuess() {return current-&gt;isLeaf();} T getQ() const {return current-&gt;data;} void resetTraverse() {current = bTree.root;} void traverse(char); KnowledgeBase&lt;T&gt;&amp; operator=(const KnowledgeBase); private: BinaryTree&lt;T&gt; bTree; Node&lt;T&gt; *current; bool unableToGuess, guessedWrong; }; template&lt;typename T&gt; KnowledgeBase&lt;T&gt;::KnowledgeBase() { current = bTree.root; unableToGuess = true; guessedWrong = false; } template&lt;typename T&gt; KnowledgeBase&lt;T&gt;::KnowledgeBase(const KnowledgeBase&amp; other) { bTree = other.bTree; unableToGuess = other.unableToGuess; guessedWrong = other.guessedWrong; current = new Node&lt;T&gt;; *current = *(other.current); } template&lt;typename T&gt; void KnowledgeBase&lt;T&gt;::addQandA(T&amp; question, T&amp; answer, char side) { Node&lt;T&gt; *newQnode = new Node&lt;T&gt;(question); Node&lt;T&gt; *newAnode = new Node&lt;T&gt;(answer); newQnode-&gt;setRchild(newAnode); if (!guessedWrong) { if (!(bTree.root == nullptr)) { if ((side == 'y') || (side == 'Y')) current-&gt;rChild = newQnode; else current-&gt;lChild = newQnode; } else { bTree.root = newQnode; } } else { //wrong guess, need to move current node to "no" guess after "yes" from newAnswer Node&lt;T&gt; *nodeToMove = new Node&lt;T&gt;; nodeToMove-&gt;setData(current-&gt;data); nodeToMove-&gt;setRchild(current-&gt;rChild); nodeToMove-&gt;setLchild(current-&gt;lChild); current-&gt;setData(question); current-&gt;setRchild(newAnode); current-&gt;setLchild(nodeToMove); } guessedWrong = false; unableToGuess = false; current = bTree.root; } template&lt;typename T&gt; void KnowledgeBase&lt;T&gt;::traverse(char direction) { if ((direction == 'y') || (direction == 'Y')) { if (current-&gt;rChild == nullptr) unableToGuess = true; else current = current-&gt;rChild; } else { if (current-&gt;lChild == nullptr) unableToGuess = true; else current = current-&gt;lChild; } } template&lt;typename T&gt; KnowledgeBase&lt;T&gt;&amp; KnowledgeBase&lt;T&gt;::operator =(const KnowledgeBase other) { std::swap(bTree, other.bTree); std::swap(unableToGuess, other.unableToGuess); std::swap(guessedWrong, other.guessedWrong); std::swap(current, other.current); return *this; } #endif /* KNOWLEDGEBASE_H */ </code></pre> <p><strong>main.cpp:</strong></p> <pre><code>#include "BinaryTree.h" #include "KnowledgeBase.h" #include "Node.h" #include &lt;vector&gt; #include &lt;algorithm&gt; #include &lt;iostream&gt; using namespace std; vector&lt;char&gt; vowels = {'a', 'e', 'i', 'o', 'u'}; int main(int argc, char** argv) { void playRound(KnowledgeBase&lt;string&gt;&amp;); KnowledgeBase&lt;string&gt; Kbase; playRound(Kbase); return 0; } void playRound(KnowledgeBase&lt;string&gt;&amp; Kbase) { void checkVowel(string, string); cout &lt;&lt; endl &lt;&lt; endl &lt;&lt; "Ok. Think of an animal. Ready? ('y' to continue): "; char keepPlaying, traversalSide, guessResponse; cin &gt;&gt; keepPlaying; while ((keepPlaying == 'y') || (keepPlaying == 'Y')) { if (!Kbase.outOfQ()) { //still have questions/guesses left if (!Kbase.isGuess()) { //question found cout &lt;&lt; Kbase.getQ() &lt;&lt; " "; cin &gt;&gt; traversalSide; Kbase.traverse(traversalSide); } else { //guess found checkVowel(Kbase.getQ(), "Is it"); cin &gt;&gt; guessResponse; if ((guessResponse == 'y') || (guessResponse == 'Y')) { cout &lt;&lt; "I win!" &lt;&lt; endl; cout &lt;&lt; "Would you like to play again? ('y' or 'n')? "; cin &gt;&gt; keepPlaying; Kbase.resetTraverse(); } else { //program guesses wrong, need to rearrange nodes traversalSide = 'n'; Kbase.giveUp(); } } } else { //out of questions/guesses cout &lt;&lt; endl &lt;&lt; "I give up. What is it? "; string newAnswer; cin &gt;&gt; newAnswer; checkVowel(newAnswer, "What question would tell me it's"); string newQuestion; cin.ignore(80, '\n'); getline(cin, newQuestion); Kbase.addQandA(newQuestion, newAnswer, traversalSide); cout &lt;&lt; "Would you like to play again? ('y' or 'n'): "; cin &gt;&gt; keepPlaying; cout &lt;&lt; endl; } } } void checkVowel(string toCheck, string output) { if (find(vowels.begin(), vowels.end(), toCheck.at(0)) != vowels.end()) cout &lt;&lt; output &lt;&lt; " an " &lt;&lt; toCheck &lt;&lt; "? "; else cout &lt;&lt; output &lt;&lt; " a " &lt;&lt; toCheck &lt;&lt; "? "; } </code></pre>
[]
[ { "body": "<p>First of all, I'd rewrite the constructors to use member initialization lists instead of assignment in the body of the ctor (where possible). For example, Node's ctor could become:</p>\n\n<pre><code>Node(T&amp; data) : data(data), lChild(nullptr), rChild(nullptr) { }\n</code></pre>\n\n<p>Your destructor for <code>Node</code> currently does some pointless work:</p>\n\n<pre><code>template&lt;typename T&gt;\nNode&lt;T&gt;::~Node() {\n delete lChild;\n delete rChild;\n lChild = nullptr;\n rChild = nullptr;\n}\n</code></pre>\n\n<p>After the dtor runs, the object no longer exists, so setting its members to <code>nullptr</code> accomplishes nothing useful. This can be reduced to just:</p>\n\n<pre><code>template&lt;typename T&gt;\nNode&lt;T&gt;::~Node() {\n delete lChild;\n delete rChild;\n}\n</code></pre>\n\n<p>I'd got a little further than just putting <code>Node</code> and <code>BinaryTree</code> in the same file. I'd make <code>Node</code> a nested class inside the <code>BinaryTree</code> class. I'd also add a <code>get</code> to the <code>Node</code> class, so KnowledgeBase can use it instead of accessing Node's private data directly.</p>\n\n<pre><code>template&lt;typename T&gt;\nstruct BinaryTree {\n struct Node {\n friend class KnowledgeBase&lt;T&gt;;\n\n Node() : lChild(nullptr), rChild(nullptr) { }\n Node(T&amp; data) : data(data), lChild(nullptr), rChild(nullptr) { }\n Node(const Node&amp;);\n\n bool isLeaf() { return (lChild == nullptr) &amp;&amp; (rChild == nullptr); }\n void setData(T newData) { data = newData; }\n void setRchild(Node* newRchild) { rChild = newRchild; }\n void setLchild(Node* newLchild) { lChild = newLchild; }\n T get() const { return data; }\n\n Node&amp; operator=(const Node);\n\n ~Node() {\n delete lChild;\n delete rChild;\n }\n\n private:\n T data;\n Node *lChild;\n Node *rChild;\n };\n\n BinaryTree() {root = nullptr;}\n ~BinaryTree() {delete root; root = nullptr;}\n BinaryTree(const BinaryTree&amp;);\n\n BinaryTree&amp; operator=(const BinaryTree other);\n friend class KnowledgeBase&lt;T&gt;;\nprivate:\n Node *root;\n};\n</code></pre>\n\n<p>I think at least for now I'll pass on reviewing <code>KnowledgeBase</code> -- I'm reasonably certain it's buggy. Specifically, at least part of the time, KnowledgeBase::current can contain a pointer to a node in KnowledgeBase::bTree. However, its destructor attempts to <code>delete current;</code>. This will result in a double-delete, since <code>bTree</code> is a member of <code>KnowledgeBase</code>, and will be destroyed automatically when the <code>KnowledgeBase</code> object is destroyed.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-04T22:18:56.490", "Id": "75090", "Score": "0", "body": "Thanks for suggestions, I implemented all of these changes and now have 0 friending for no private data access from other classes. But does using gets in this way \"break\" encapsulation? Now my node class has a get and set for each private member, along with the a get/set for the binary tree's root for changing it and resetting the traversal pointer current in kbase. This seems just as open as friending? Is the only way to get around this to remove a knowledge base class and allow main to communicate directly with the binary tree class?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-05T05:43:58.493", "Id": "75158", "Score": "1", "body": "@Instinct: Public get/set pairs generally point to poor design, or else something that should probably just be a struct with public members. In this case, putting `node` inside of `BinaryTree` (mostly) protects it from \"public\" consumption in any case, so it can make sense to just make it a struct with all its contents public (but only perhaps accessible only to the `BinaryTree` class)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-07T00:25:54.917", "Id": "75519", "Score": "0", "body": "Updated moving node inside tree as a struct, along with moving functionality over to tree leaving kbase just as an interface between main and tree to improve encapsulation. Does this look correct? No get/set pairs now although kbase mostly just passes things back and forth between tree and main, but that way nothing can be directly manipulated from main." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-02T09:26:05.293", "Id": "43213", "ParentId": "43101", "Score": "4" } }, { "body": "<p>I am concerned that there might be a problem with your Node copy constructor.</p>\n\n<pre><code>template&lt;typename T&gt;\nNode&lt;T&gt;::Node(const Node&amp; other) {\n data = other.data;\n lChild = new Node&lt;T&gt;;\n rChild = new Node&lt;T&gt;;\n *lChild = *(other.lChild);\n *rChild = *(other.rChild);\n}\n</code></pre>\n\n<p>As it is written, you will traverse the entire tree and copy construct all of the children of other as desired, but when you finally hit a leaf node and either <code>other.lChild</code> or <code>other.rChild</code> are <code>nullptr</code>, you'll be dereferencing a <code>nullptr</code> and the program will crash.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-04T22:20:47.263", "Id": "75091", "Score": "0", "body": "True didn't think of this, using cout's to check though the node's copy ctor is never even being used, only the default and non-defaults. What a good fix though be just calling isLeaf() on other first?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-05T12:43:57.800", "Id": "75205", "Score": "1", "body": "no, calling `isLeaf` will only check if both children are `nullptr`. You'll need to check each child individually before you `new` it up. If you find that one of the children from other is a `nullptr` just set your child to `nullptr`, no allocation from `new`, no dereferencing." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-04T16:19:32.893", "Id": "43419", "ParentId": "43101", "Score": "4" } } ]
{ "AcceptedAnswerId": "43213", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T22:46:04.077", "Id": "43101", "Score": "5", "Tags": [ "c++", "object-oriented", "c++11", "tree" ], "Title": "Binary tree/knowledge base design" }
43101
<p>I'm trying to implement a bunch of sorting algorithms in JavaScript, and I can't figure out why my shell sort is so slow. It's 6x slower than my merge sort, and only slightly faster than my insertion sort. I've seen another implementation online, but I'm more focused on making it clear and readable (as I have a blog for noobs) and the faster implementation is too concise for my purposes. Any thoughts on how I can keep the general plan but get it moving faster? I tried using Marcin Ciura's gap sequence <code>[701, 301, 132, 57, 23, 10, 4, 1]</code>, but it was slightly slower. I'm not sure what's the biggest factor slowing down my sort.</p> <pre><code> var shellSort = function( list ) { var gapSize = Math.floor( list.length / 2 ); while( gapSize &gt; 0 ) { _shellInsertionSort( list, gapSize ); gapSize = Math.floor( gapSize / 2 ); } return list; }; function _shellInsertionSort( list, gapSize ) { var temp, i, j; for( i = gapSize; i &lt; list.length; i += gapSize ) { j = i; while( j &gt; 0 &amp;&amp; list[ j - gapSize ] &gt; list[j] ) { temp = list[j]; list[j] = list[ j - gapSize ]; list[ j - gapSize ] = temp; j -= gapSize; } } }; </code></pre> <p>My tests:</p> <pre><code> var testSpeed = function( testSize, rounds ) { var testArrays = [], algorithms = Array.prototype.slice.call( arguments, 2 ), results = [], i, j; for( i = 0; i &lt; rounds; i++ ) { testArrays[i] = []; for( j = 0; j &lt; testSize; j++ ) { testArrays[i].push( Math.ceil( Math.random() * testSize )); } } for( i = 0; i &lt; algorithms.length; i++ ) { for( j = 0; j &lt; rounds; j++ ) { if( !results[i] ) { results[i] = []; } results[i].push( testAlgorithm( algorithms[i], testArrays[j] )); } } return results; }; var testAlgorithm = function( algorithm, set ) { var clone = set.slice(), start = new Date().getTime(), end; algorithm( clone ); end = new Date().getTime(); return end - start; }; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T01:23:11.157", "Id": "74389", "Score": "2", "body": "The `while` test should be `j >= gapSize` to keep from checking negative indices with `j - gapSize`, but that should barely make a dent in the speed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T01:28:48.510", "Id": "74392", "Score": "2", "body": "And the psuedocode on the Wikipedia page increments `i` by 1 rather than `gapSize` in the outer `for` loop. While that means more iterations, perhaps it people forms better by sorting more large gaps." } ]
[ { "body": "<p>@David Harkness sent my search in the right direction. As it is, the insertion sort portion is only going through one round for each gap, rather than walking up each round, so it's not actually going for more than one round, and most of the sorting isn't done until the gap is 1. When I start fixing problem, it just started getting more convoluted, so I ditched my original approach and followed the pseudocode on wikidepia. Now, it's quite snappy:</p>\n\n<pre><code>var shellSort = function( list ) {\n var gap = Math.floor( list.length / 2 );\n\n while( gap &gt; 0 ) {\n for( i = gap; i &lt; list.length; i++ ) {\n temp = list[i];\n for( j = i; j &gt;= gap &amp;&amp; list[j - gap] &gt; temp; j -= gap ) {\n list[j] = list[j - gap];\n }\n list[j] = temp;\n }\n\n gap = Math.floor( gap / 2 );\n }\n\n return list;\n };\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T04:01:33.193", "Id": "43117", "ParentId": "43104", "Score": "3" } } ]
{ "AcceptedAnswerId": "43117", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T23:40:49.057", "Id": "43104", "Score": "7", "Tags": [ "javascript", "algorithm", "performance", "sorting" ], "Title": "How can I speed up my shell sort?" }
43104
<p>I got really tired of having this code in all of my classes and methods:</p> <pre><code>public class SomeClass { private static final Logger LOGGER = Logger.getLogger(SomeClass.class); //... public int someMethod() { final String methodName = "someMethod()"; LOGGER.debug("Entering " + methodName); int returnValue = 0; //... LOGGER.debug("Exiting " + methodName + +", returning " + returnValue); return returnValue; } } </code></pre> <p>... so I created the following utility class which would allow me to just call <code>LoggingUtil.logMethodEntrance()</code>:</p> <pre><code>public class LoggingUtil { private static final Logger LOGGER = Logger.getLogger(LoggingUtil.class); private static final int GET_CALLING_METHOD_NAME_DEPTH = 3; public static void logMethodEntrance() { if(LOGGER.isDebugEnabled()) { LOGGER.debug("Entering " + getCallingMethodName()); } } private static String getCallingMethodName() { return Thread.currentThread().getStackTrace()[GET_CALLING_METHOD_NAME_DEPTH].getMethodName() + "()"; } } </code></pre> <p>This was the first iteration. I put it here so you could understand the general concept. Before you mention that the <code>isDebugEnabled()</code> call isn't necessary to prevent the logging, the reason it's there is because the <code>getStackTrace()</code> method has notoriously poor performance and I don't want it called unless it's actually going to be used.</p> <p>Now I wanted to add on to this basic framework and make it more powerful/dynamic by overloading the method and allowing the user to pass in a <code>Priority</code> if they don't want it to be <code>DEBUG</code>.</p> <p>Normally, I would chain the methods like the following:</p> <pre><code>private static final Level DEFAULT_LOGGING_LEVEL = Level.DEBUG; public static void logMethodEntrance() { logMethodEntrance(DEFAULT_LOGGING_LEVEL); } public static void logMethodEntrance(Priority level) { if(LOGGER.isEnabledFor(level)) { LOGGER.log(level, "Entering " + getCallingMethodName()); } } </code></pre> <p>The problem with this is that there's no way for the <code>getCallingMethodName()</code> method to know how deep to search in the stack for the appropriate "calling method". If the calling code invoked <code>logMethodEntrance()</code>, it will be one off from if they called <code>logMethodEntrance(Level.INFO)</code>.</p> <p>I thought about passing down an <code>int</code> that described the stack depth to look for the method name, but it ended up boiling down to all of them passing a <code>1</code> down to the common method call. So this is what I wound up going with in my final implementation:</p> <pre><code>public class LoggingUtil { private static final Logger LOGGER = Logger.getLogger(LoggingUtil.class); private static final Object METHOD_SIGNATURE_BREAKER = new Object(); private static final Level DEFAULT_LOGGING_LEVEL = Level.DEBUG; private static final int GET_CALLING_METHOD_NAME_DEPTH = 4; public static void logMethodEntrance() { logMethodEntrance(DEFAULT_LOGGING_LEVEL, METHOD_SIGNATURE_BREAKER); } public static void logMethodEntrance(Priority level) { logMethodEntrance(level, METHOD_SIGNATURE_BREAKER); } private static void logMethodEntrance(Priority level, Object signature) { if(LOGGER.isEnabledFor(level)) { LOGGER.log(level, "Entering " + getCallingMethodName()); } } private static String getCallingMethodName() { return Thread.currentThread().getStackTrace()[GET_CALLING_METHOD_NAME_DEPTH].getMethodName() + "()"; } } </code></pre> <p>I'm not particularly happy with this solution, but it does work fine. The issue is even more noticeable in the <code>logMethodExit()</code> method set, which I allow the calling code to either use with no arguments, use with <code>Priority</code>, use with a <code>T returnValue</code>, or supply both.</p> <p>The <code>METHOD_SIGNATURE_BREAKER</code> object only exists to allow a further method overload. What I mean is that there's no actual <em>need</em> for it, except that I have to have another parameter supplied to the common <code>private</code> method in order for it to exist. (i.e., I can't have it as below):</p> <pre><code>public static void logMethodEntrance() {} public static void logMethodEntrance(Priority level) {} private static void logMethodEntrance(Priority level) {} </code></pre> <p>Passing down <code>null</code> seemed even dirtier without the constant. I'm not willing to copy and paste code around or duplicate it. I fully believe that if you need to make a code change to fix a bug or something that you should only have to do it in one place. Ideally, I'd like to find a way to chain the methods downward, but I don't see how to do that well and preserve the <code>getCallingMethodName()</code>'s functionality. So, any great ideas?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T01:00:48.077", "Id": "74384", "Score": "0", "body": "Is there a reason you picked that over just giving the method a different name?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T01:03:35.203", "Id": "74385", "Score": "0", "body": "@BenAaronson ... Yeah, I realized that would've been easier as I was typing the question, haha. But it would be nice if someone has a solution where the `getCallingMethodName()` method can dynamically get the right one and allow the methods to be chained together. It would make the code cleaner, I think, than relying on a separate `private` version." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T01:41:05.117", "Id": "74394", "Score": "0", "body": "I don't know about all the logging framework but in log4j I don't need to specify myself the class or the method name, I just need to change the pattern layout. I guess they used the same slow component, but you don't need any new classes at least. This won't fit all you need, but could be a good start." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T05:06:44.917", "Id": "74414", "Score": "0", "body": "@Marc-Andre Yeah, this is using log4j. I actually didn't know that you could configure it to give you the method name in the logging statements (thought it was only the class name)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T11:31:02.750", "Id": "74421", "Score": "0", "body": "Check AOP too if you don't know about it already: http://stackoverflow.com/q/12732069/843804" } ]
[ { "body": "<p>I have been through this loop (quite recently, actually), for a rather large project in a very commercial environment.</p>\n\n<p>Frankly, it's not sustainable.</p>\n\n<p>Let me run through some of the issues:</p>\n\n<ul>\n<li>getStackTrace() is not just slow, it is molasses, and it affects all threads on the JVM, not just the current one.</li>\n<li>Different versions of Java (same vendor, different versions, or different vendors, etc.) will need to have a different value for GET_CALLING_METHOD_NAME_DEPTH</li>\n<li>did I mention that getStackTrace was slow?</li>\n<li>You will be logging the <strong>method</strong> name, but the class used for the Log output will be <code>LoggingUtil</code>, not the class the method was called on.</li>\n<li>did I mention that getStackTrace was slow?</li>\n<li>the performance of getStackTrace is proportional to the depth of the stack. Testing with shallow stacks is pointless if someone then uses your code in a GUI, or Tomcat, or whatever... which have traces a mile long.... god forbid you do recursion!!!</li>\n</ul>\n\n<p>To put things in perspective, on a 64-core computer (128 hardware threads), a program that was able to run at 80% CPU (i.e. 100 hardward-threads running at 100%) was reduced to about 3% CPU when about 1000 traces were taken each second.</p>\n\n<p>This sort of performance is highly dependant on the JVM version, and the vendor. Stack traces are considered to be part of exception handling, and building the trace is not supposed to be fast.</p>\n\n<p>Questions about Trace versions (FYI, this may, or may not help you):</p>\n\n<blockquote>\n<pre><code>echo &amp;&amp; cat STrace.java &amp;&amp; java -version &amp;&amp; java STrace\n\npublic class STrace {\n public static void main(String[] args) {\n for (StackTraceElement ste : Thread.currentThread().getStackTrace()) {\n System.out.println(ste);\n }\n }\n}\njava version \"1.7.0\"\nJava(TM) SE Runtime Environment (build pxp6470_27-20131115_04)\nIBM J9 VM (build 2.7, JRE 1.7.0 Linux ppc64-64 Compressed References 20131114_175264 (JIT enabled, AOT enabled)\nJ9VM - R27_Java727_GA_20131114_0833_B175264\nJIT - tr.r13.java_20131113_50523\nGC - R27_Java727_GA_20131114_0833_B175264_CMPRSS\nJ9CL - 20131114_175264)\nJCL - 20131113_01 based on Oracle 7u45-b18\njava.lang.Thread.getStackTraceImpl(Native Method)\njava.lang.Thread.getStackTrace(Thread.java:1203)\nSTrace.main(STrace.java:3)\n</code></pre>\n</blockquote>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T01:06:41.173", "Id": "74387", "Score": "0", "body": "Interesting. I knew the method call was slow, and like I said, that's why I make sure `DEBUG` is enabled before going through the trouble. `DEBUG` isn't enabled in any kind of production setting, of course. The most interesting part to me is that you say it slows down *all* threads. I'd think it only affects the current one." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T01:10:16.770", "Id": "74388", "Score": "0", "body": "Also, can you explain why different versions of Java would need to have a different `GET_CALLING_METHOD_NAME_DEPTH`? It seems like, regardless of the version, there will always be a certain amount of calls on the stack between the call and the desired method, right?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T01:25:29.090", "Id": "74391", "Score": "1", "body": "@JeffGohlke See this answer for \"more\" information http://stackoverflow.com/a/442773" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T01:03:52.850", "Id": "43107", "ParentId": "43106", "Score": "6" } }, { "body": "<p>Separate answer because this is taking a completely different tack.</p>\n\n<p>Instead of the knee-jerk reaction to the <code>getStackTrace()</code>, consider the following other issues...</p>\n\n<p>Logging in Java has been a complicated area for the past number of years.... there's so many different Logger utilities, all with slightly different interfaces:</p>\n\n<ul>\n<li>java.util.Logging</li>\n<li>slf4j</li>\n<li>apache log4j</li>\n<li>and <a href=\"http://java.dzone.com/articles/shouldn%E2%80%99t-we-standardize-java\" rel=\"nofollow\">many, many more</a></li>\n</ul>\n\n<p>You seem to be using Apache's log4j API.</p>\n\n<p>What you should consider is how other API's have solved this problem.</p>\n\n<p>For example, java.util.Logging has the following two methods:</p>\n\n<ul>\n<li><a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/logging/Logger.html#entering%28java.lang.String,%20java.lang.String%29\" rel=\"nofollow\">entering(String classname, String method)</a></li>\n<li><a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/logging/Logger.html#exiting%28java.lang.String,%20java.lang.String%29\" rel=\"nofollow\">exiting(String classname, String method)</a></li>\n</ul>\n\n<p>To me this indicates that the best way to manage this problem is 'the hard way' of typing in the method name. Using the stack-trace is not used by any popular system.</p>\n\n<p>Now, a second issue is that Logging is enabled, configured, and diverted based on the 'key' used for the log message. This is typically set as the full class package.Name. Your code is losing that information, and using just the one Logger instance for the LogUtils class. Thus, there is no way to configure the method entry/exit logging for just one class in your system.</p>\n\n<p>For your LoggingUtil class I would consider the method:</p>\n\n<pre><code>public static final void logMethodEntrance(final Logger logger,\n final String class, final String method) {...}\n</code></pre>\n\n<p>Inside that method I would still check <code>logger.isDebugEnabled()</code> before working....</p>\n\n<p>Additionally, one of the features that is missing in apache's log4j is the ability to do String-formatted messages... <a href=\"http://www.slf4j.org/apidocs/org/slf4j/Logger.html#info%28java.lang.String,%20java.lang.Object...%29\" rel=\"nofollow\">which are so useful in slf4j</a>...</p>\n\n<p>String-formatted methods are useful for things like the following... in your code you have (before your 'fix'):</p>\n\n<blockquote>\n<pre><code> LOGGER.debug(\"Entering \" + methodName);\n\n int returnValue = 0;\n\n //...\n\n LOGGER.debug(\"Exiting \" + methodName + +\", returning \" + returnValue);\n</code></pre>\n</blockquote>\n\n<p>Now, that first <code>debug</code> is doing the String-concatenation before the LOGGER can decide whether debug is enabled, or not. This means that you are doing the String-concatenation even when debug is not enabled.</p>\n\n<p>If the LOGGER supported a 'formatted' debug method, it could be called like:</p>\n\n<pre><code>LOGGER.debug(\"Entering %s\", methodName);\n</code></pre>\n\n<p>and the LOGGER could check to see whether <code>isDebugEnabled()</code> before building the actual message (string formatting) with <code>String.format(\"Entering %s\", methodName)</code>.</p>\n\n<p>This 'formatted' log messages is one of the best features available in Logger APIs, and, as far as I am concerned, it is the 'winning' feature for when deciding which API to use...</p>\n\n<p><em>cough</em> slf4j <em>cough</em></p>\n\n<p>Unfortunately slf4j does not support the method entry/exit calls.</p>\n\n<p>What a mess.</p>\n\n<p>If you are determined to have a LogUtilities static class, I would recommend the following:</p>\n\n<pre><code>public static final void logMethodEntrance(final Logger logger,\n final String class, final String method) {...}\n\npublic static final void logMethodEntrance(final Logger logger,\n final String class, final String method, Object...params) {...}\n\npublic static final void logMethodExit(final Logger logger,\n final String class, final String method) {...}\n\npublic static final void log(final Logger logger, String format, Object...values) { ... }\n\npublic static final void debug(final Logger logger, String format, Object...values) { ... }\n\npublic static final void trace(final Logger logger, String format, Object...values) { ... }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-02T18:15:57.390", "Id": "74598", "Score": "0", "body": "Thanks for all your different perspectives. Really helped me work through the issue. It sucks that there's no good, generic way to do this, but you've outlined very well the reasons *why*." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T13:52:00.027", "Id": "43139", "ParentId": "43106", "Score": "3" } } ]
{ "AcceptedAnswerId": "43139", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T00:42:36.957", "Id": "43106", "Score": "8", "Tags": [ "java", "design-patterns", "logging" ], "Title": "Overloading various logging methods" }
43106
<p>I have a few <code>if</code>, <code>else</code>-<code>if</code>, <code>else</code> clauses. The only different thing in the context of these clauses is my LINQ query, one clause has <code>StartsWith</code>, one clause has <code>Contains</code>, and the other does a simple match. Is there a way to have all of this in one clause and somehow create a variable that can change between <code>StartsWith</code>, <code>Contains</code>, etc.? My ultimate goal is to reduce the lines of code.</p> <pre><code>if (parameters[0].ToUpper() == "STARTSWITH" &amp;&amp; parameters[1] != null) { string searchname = parameters[1]; ViewBag.MyMessage = "Displaying device names beginning with \"" + searchname + "\""; SampleEntities sampleEntities = new SampleEntities(); try { var Model = (from dev in sampleEntities.NetworkDevices where dev.Name.StartsWith(searchname) from inter in sampleEntities.DeviceInterfaces where inter.NetworkDevice.Id == dev.Id select new DeviceInterfaceModel { DeviceName = dev.Name, InterfaceName = inter.Name, IPv4Address = inter.IPv4Address, IPv4SubnetMask = inter.IPv4SubnetMask, CIDR = inter.CIDR, Subnet = inter.Subnet }).ToList(); return View(Model); } catch { } return View(); } #endregion #region Name Contains else if (parameters[0].ToUpper() == "CONTAINS" &amp;&amp; parameters[1] != null) { string searchname = parameters[1]; ViewBag.MyMessage = "Displaying device names containing \"" + searchname + "\""; SampleEntities sampleEntities = new SampleEntities(); try { var Model = (from dev in sampleEntities.NetworkDevices where dev.Name.Contains(searchname) from inter in sampleEntities.DeviceInterfaces where inter.NetworkDevice.Id == dev.Id select new DeviceInterfaceModel { DeviceName = dev.Name, InterfaceName = inter.Name, IPv4Address = inter.IPv4Address, IPv4SubnetMask = inter.IPv4SubnetMask, CIDR = inter.CIDR, Subnet = inter.Subnet }).ToList(); return View(Model); } catch { } return View(); } #endregion } else { ViewBag.MyMessage = "Diplaying device names equal to \"" + name + "\""; SampleEntities sampleEntities = new SampleEntities(); try { var Model = (from dev in sampleEntities.NetworkDevices where dev.Name == name from inter in sampleEntities.DeviceInterfaces where inter.NetworkDevice.Id == dev.Id select new DeviceInterfaceModel { DeviceName = dev.Name, InterfaceName = inter.Name, IPv4Address = inter.IPv4Address, IPv4SubnetMask = inter.IPv4SubnetMask, CIDR = inter.CIDR, Subnet = inter.Subnet }).ToList(); return View(Model); } catch { } return View(); } </code></pre>
[]
[ { "body": "<p>This should be more simplified and more clear, now we make the query to the devices context first, then we get the result, instead of repeating the same thing three times. Remember, always use <code>using</code> when dealing with objects that inherits <code>IDisposable</code>:</p>\n\n<pre><code>using (SampleEntities sampleEntities = new SampleEntities())\n{\n string searchname = parameters[1];\n\n var devices = (from dev in sampleEntities.NetworkDevices\n select dev);\n\n if (parameters[0].ToUpper() == \"STARTSWITH\" \n &amp;&amp; parameters[1] != null)\n {\n ViewBag.MyMessage = \"Displaying device names beginning with \\\"\" + searchname + \"\\\"\";\n devices = (from dev in devices \n where dev.Name.StartsWith(searchname));\n }\n else if (parameters[0].ToUpper() == \"CONTAINS\" \n &amp;&amp; parameters[1] != null)\n {\n ViewBag.MyMessage = \"Displaying device names containing \\\"\" + searchname + \"\\\"\";\n devices = (from dev in devices \n where dev.Name.Contains(searchname));\n } \n else\n {\n ViewBag.MyMessage = \"Diplaying device names equal to \\\"\" + name + \"\\\"\";\n devices = (from dev in devices \n where dev.Name == name);\n }\n\n var Model = (from dev in devices\n from inter in sampleEntities.DeviceInterfaces\n where inter.NetworkDevice.Id == dev.Id\n select new DeviceInterfaceModel\n {\n DeviceName = dev.Name,\n InterfaceName = inter.Name,\n IPv4Address = inter.IPv4Address,\n IPv4SubnetMask = inter.IPv4SubnetMask,\n CIDR = inter.CIDR,\n Subnet = inter.Subnet\n })\n .ToList();\n\n return View(Model);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T03:15:07.773", "Id": "74406", "Score": "0", "body": "Thank you, that works! I do have a concern with the performance. It seems like a database call is made the first time that gets all devices via the \"var devices = (from dev in sampleEntities.NetworkDevices\n select dev);\" statement. If theoretically there were millions of devices in this database, is there a better way to optimize the performance of this?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T08:43:25.537", "Id": "74416", "Score": "0", "body": "@LIK no, it is just a query, no database call. The db call will occur when you call `ToList()` in the above code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T12:39:01.013", "Id": "74436", "Score": "0", "body": "`from dev in sampleEntities.NetworkDevices select dev` There is no reason for this, just write `sampleEntities.NetworkDevices` instead (possibly specifying the type explicitly). `from dev in devices where dev.Name == name` This won't compile, you also need a `select`. If you have only one clause, I think that using the method syntax (`.Where()`) is better." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T02:39:08.227", "Id": "43114", "ParentId": "43109", "Score": "3" } } ]
{ "AcceptedAnswerId": "43114", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T01:57:13.653", "Id": "43109", "Score": "2", "Tags": [ "c#", "beginner", "asp.net-mvc-4", "asp.net-mvc" ], "Title": "How can I simplify these if/else clauses?" }
43109
<p>I want to have a caching class to cache different types. I want each type to be cached in a different <code>MemoryCache</code> but in a generic way.</p> <p>Am I doing it right? </p> <pre><code>internal static class RecordsCache { private static Dictionary&lt;string, ObjectCache&gt; cacheStore; static private CacheItemPolicy policy = null; static RecordsCache() { cacheStore = new Dictionary&lt;string, ObjectCache&gt;(); ObjectCache activitiesCache = new MemoryCache(typeof(Activity).ToString()); ObjectCache lettersCache = new MemoryCache(typeof(Letter).ToString()); ObjectCache contactssCache = new MemoryCache(typeof(Contact).ToString()); cacheStore.Add(typeof(Activity).ToString(), activitiesCache); cacheStore.Add(typeof(Letter).ToString(), lettersCache ); cacheStore.Add(typeof(Contact).ToString(), contactssCache ); policy = new CacheItemPolicy(); policy.Priority = CacheItemPriority.Default; policy.AbsoluteExpiration = DateTimeOffset.Now.AddHours(12); } public static void Set&lt;T&gt;(string userID, int year, List&lt;T&gt; records) { var cache = cacheStore[typeof(T).ToString()]; string key = userID + "-" + year.ToString(); cache.Set(key, records, policy); } public static bool TryGet&lt;T&gt;(string userID, int year, out List&lt;T&gt; records) { var cache = cacheStore[typeof(T).ToString()]; string key = userID + "-" + year.ToString(); records = cache[key] as List&lt;T&gt;; return records != null; } public static void Remove&lt;T&gt;(string userID, int year) { var cache = cacheStore[typeof(T).ToString()]; string key = userID + "-" + year.ToString(); cache.Remove(key); } } </code></pre>
[]
[ { "body": "<p>From my point of view, everything is well coded.</p>\n\n<p>Just some personal preference here:</p>\n\n<ol>\n<li><p>I would provide 1 more <code>Set&lt;T&gt;</code> method which accepts a func as input instead of <code>List&lt;T&gt;</code>:</p>\n\n<pre><code>public static void Set(string userId, int year, Func&lt;List&lt;T&gt;&gt; retrieveData) { }\n</code></pre></li>\n<li><p>I would like to have 1 more method to combine <code>Get</code> and <code>Set</code> together which looks like:</p>\n\n<pre><code>public List&lt;T&gt; TryGetAndSet(string userId, int year, Func&lt;List&lt;T&gt;&gt; retrieveData)\n{\n //if cache item exist return cacheItem \n //if cache item does not exist, retrieve data by executing retrieveData\n // If any result retrieved, set to cache and return as result\n}\n</code></pre></li>\n<li><p>1 more item to check whether certain cache item exists</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T07:28:08.070", "Id": "43120", "ParentId": "43111", "Score": "2" } }, { "body": "<ol>\n<li><p>Instead of having a cache</p>\n\n<pre><code>private static Dictionary&lt;string, ObjectCache&gt; cacheStore;\n</code></pre>\n\n<p>you could have one keyed of the types:</p>\n\n<pre><code>private static Dictionary&lt;Type, ObjectCache&gt; cacheStore;\n</code></pre>\n\n<p>This means you don't need to call <code>typeof(T).ToString()</code> everywhere.</p></li>\n<li><p>You duplicate the code of building the key in all 3 methods - it should be extracted into a private <code>BuildKey(string userId, int year)</code> method. This means if you need to change how the key is built you only need to touch one method rather than all of them.</p></li>\n<li><p>I would provide a <code>Register</code> method which accepts a type for which to create a new cache rather than hard-coding it in.</p></li>\n<li><p>The cache policy is also not configurable - which means you are stuck with it unless you want to change the code.</p></li>\n<li><p>You really really should think hard about whether a static cache is the right way to go. It will give you trouble in unit testing and it will also make it impossible for multiple classes to have different cache with different policies for example.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T08:46:25.257", "Id": "74417", "Score": "0", "body": "Thanks, very valuable tips. I am no programmer in real life, it is just a hobby. I never had a programming courses or so. So your tips are like gold to me :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T12:31:36.963", "Id": "74432", "Score": "0", "body": "One more issue with keeping the class static is that it's not thread-safe. And static classes that are not thread-safe are almost unusable in multi-threaded programs (and should be very clearly documented as such)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T12:33:04.000", "Id": "74433", "Score": "0", "body": "@svick but the CacheMemory itself is threadsafe, wouldn't that make it thread safe?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T12:35:34.123", "Id": "74435", "Score": "0", "body": "@MeNoTalk I guess you're right. `Dictionary` isn't thread-safe, but you only read from it (unless you follow Chris's advice about `Register()`), so that should be okay." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T08:01:26.153", "Id": "43123", "ParentId": "43111", "Score": "7" } } ]
{ "AcceptedAnswerId": "43123", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T02:08:32.370", "Id": "43111", "Score": "4", "Tags": [ "c#", "cache" ], "Title": "Generic MemoryCache class" }
43111
<p>I have a signup form in which the user has to enter the email address and after some quick asynchronous processing at the backend I have to tell the user that whether the email address is already registered or not.</p> <p>Below is a sample example of the JSP page that I have created,</p> <pre><code>&lt;input type="email" id="inputEmail" placeholder="*Email" name="inputEmail" required="true" onchange="checkDuplicate();" onpaste="this.onchange();" oninput="this.onchange();" onsubmit="this.onchange();" autocomplete="off"/&gt; &lt;div id="duplicateEmail"&gt;&lt;/div&gt; &lt;script&gt; var request; function createRequest(){ if(window.XMLHttpRequest){ request=new XMLHttpRequest(); } else if(window.ActiveXObject){ request=new ActiveXObject("Microsoft.XMLHTTP"); } } //Below 2 functions are to check whether the email entered by the user is already registered or not function checkDuplicate(){ var email = document.getElementById("inputEmail").value; if(email!=""){ createRequest(); var url = "../ajaxPages/check_email.jsp?email="+email; try{ request.onreadystatechange=duplicateEmailMessage; request.open("GET",url,true); request.send(); }catch(e){ alert("Unable to connect to server"); } } } function duplicateEmailMessage(){ if(request.readyState==4){ var x = document.getElementById("duplicateEmail"); var msg = request.responseText; x.innerHTML = msg; } } &lt;/script&gt; </code></pre> <p>Now the at the backend the <code>check_email.jsp</code> page will be like this,</p> <pre><code>&lt;%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %&gt; &lt;%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%&gt; &lt;c:set var="email" value="${param['email']}"/&gt; &lt;sql:setDataSource var="db" driver="com.mysql.jdbc.Driver" user="root" password="root" url="jdbc:mysql://localhost:3306/ercafe"/&gt; &lt;sql:query dataSource="${db}" sql="SELECT * FROM user_details" var="result" /&gt; &lt;c:forEach var="row" items="${result.rows}"&gt; &lt;c:if test="${row.user_email_id eq email}"&gt; &lt;c:out value="This email is already registered"/&gt; &lt;/c:if&gt; &lt;/c:forEach&gt; </code></pre> <p>I know that it is not advisable to include the database interaction in the JSP page but as this page would be handled in the backend without any direct interaction from the user I'm very tempted to use <code>check_email.jsp</code> as above. Can anyone tell me how to handle the <code>check_email.jsp</code> by the ideal way? </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T03:24:08.183", "Id": "74407", "Score": "1", "body": "If you know that it is not advisable, why are you doing it in the first place ? Even if it does not have a direct interaction with the client, it is still in the view component. Why would you add something that look more like a controller or model operation in the view ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T03:26:54.640", "Id": "74408", "Score": "0", "body": "@Marc-Andre I agree with you but I couldn't figure out how to do this in any other way. It would be extremely helpful if you could guide me through it." } ]
[ { "body": "<ol>\n<li><p>I've never used that <code>sql:setDataSource</code> JSTL tag but <a href=\"http://docs.oracle.com/javaee/5/jstl/1.1/docs/tlddocs/sql/setDataSource.html\" rel=\"nofollow noreferrer\">the documentation is not promising</a>:</p>\n\n<blockquote>\n <p>Creates a simple DataSource suitable only for prototyping. </p>\n</blockquote>\n\n<p>Another answer on Stack Overflow says the same: <a href=\"https://stackoverflow.com/a/7697316/843804\">How to use JSTL sql tag</a>.</p>\n\n<p>(If I have to guess I would say that it opens and close a new database connection on every page load which is a slow operation. Pooling and reusing connections is much better.)</p>\n\n<p>I'd go with servlets.</p></li>\n<li><p>This does not scale/perform well:</p>\n\n<pre><code>&lt;sql:query dataSource=\"${db}\" sql=\"SELECT * FROM user_details\" var=\"result\" /&gt;\n&lt;c:forEach var=\"row\" items=\"${result.rows}\"&gt;\n &lt;c:if test=\"${row.user_email_id eq email}\"&gt;\n &lt;c:out value=\"This email is already registered\"/&gt;\n &lt;/c:if&gt;\n&lt;/c:forEach&gt;\n</code></pre>\n\n<p>The loop iterates over every user_details records. You could add a <code>WHERE</code> condition (like <code>WHERE user_email_id = '${email}'</code> or something similar) but <strong>do not</strong> do that, I guess it would lead to <a href=\"https://en.wikipedia.org/wiki/SQL_injection\" rel=\"nofollow noreferrer\">SQL injection</a>.</p></li>\n<li><pre><code>alert(\"Unable to connect to server\");\n</code></pre>\n\n<p>Try to use something more user-friendly feedback mechanism. See: <a href=\"https://softwareengineering.stackexchange.com/a/106039/36726\">JavaScript's prompt, confirm and alert considered “old-fashioned”</a></p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T14:10:45.120", "Id": "74446", "Score": "1", "body": "thanks you cleared lot of doubts through that JSTL example." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T11:07:59.293", "Id": "43130", "ParentId": "43115", "Score": "3" } }, { "body": "<p><strong>General advice</strong></p>\n\n<blockquote>\n <p>I know that it is not advisable to include the database interaction in\n the JSP page but as this page would be handled in the backend without\n any direct interaction from the user I'm very tempted to use\n check_email.jsp as above.</p>\n</blockquote>\n\n<p>It's a good thing when you know that something is wrong to search for a better way to do it. This is an important part of having good code in my opinion. </p>\n\n<p>What you must not do, is code something that you know is not right, but look like having no impact of security or side effects. There is a chance that you won't be the last programmer on this code. What will happen if he decide that the view is more publicly accessible ? (In this case not much since from my understanding, JSP tag are interpreted server-side)</p>\n\n<p>There is one thing you know for sure, that if this code is in the server/controller/service, it will be where he belong! </p>\n\n<p><strong>Re-usability</strong></p>\n\n<p>This SQL request looks to me like a request that could be re-use in different in an application. Will paste it everywhere you need it or would ratter call a service that will return the result of the query ? The second option look better to me. </p>\n\n<p>I can't provide a good example of a service without knowing what framework you use. There is plenty of resource on the internet that could help you, I could point you some tutorials if I could know what your set-up is. </p>\n\n<p><em>Quick note</em></p>\n\n<p>In your JavaScript you have <code>var url = \"../ajaxPages/check_email.jsp?email=\"+email;</code>. Are those pages suppose to be responses to AJAX request ? If so, you should know that you can probably create a controller that do respond to AJAX request. In my opinion, this will help you keep all the important logic in the controller and remove some JSP pages that I guess are not doing what they should be doing.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T13:04:27.817", "Id": "43137", "ParentId": "43115", "Score": "4" } } ]
{ "AcceptedAnswerId": "43130", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T02:43:02.957", "Id": "43115", "Score": "5", "Tags": [ "sql", "mvc", "ajax", "jsp" ], "Title": "Is it advisable to integrate SQL statements in the JSP pages that are not displayed to the user but handled at the back?" }
43115
<p>I wanted to play around with the following idea:</p> <blockquote> <p>Give a paragraph, I wanted to find out the relative frequency of usage of each of the five vowels. I wanted to plot a pie chart depicting this.</p> </blockquote> <p>Here is my code:</p> <pre><code>from sys import stdin from re import sub import pylab DataToRead = stdin.read() VowelData = sub(r"[^aeiou]","",DataToRead) #Take Out Everything which is NOT a vowel VowelList = ['a','e','i','o','u'] VowelCount = [sum(map(lambda x: x==Vowel,VowelData)) for Vowel in VowelList] # Number of times each vowel appears print VowelCount VowelPerc = [x*100.0/sum(VowelCount) for x in VowelCount] #Find the percentage of each pylab.pie(VowelPerc,None,VowelList,autopct='%1.1f%%') pylab.show() </code></pre> <p>It does what it needs to (I think) but I feel there is a better way of doing this (algorithmically speaking). I like Functional Programming so I threw in the Mapper but there is no other reason for that.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-02T11:57:00.577", "Id": "74560", "Score": "0", "body": "Note that with the `autopct` option, the chart computes percentages automatically." } ]
[ { "body": "<p>I strongly advise against <code>CamelCase</code> for your variable names – consider <code>snake_case</code> instead. Why? Because consistency with existing Python code.</p>\n\n<p>I also suggest better spacing around your operators, e.g. <code>x == vowel</code> instead of <code>x==Vowel</code> and <code>pylab.pie(vowel_perc, None, vowel_list, autopct='%1.1f%%')</code> instead of <code>pylab.pie(VowelPerc,None,VowelList,autopct='%1.1f%%')</code>. In general, consistent, even spacing makes code easier to read.</p>\n\n<p>Do not use <code>map</code>, or more precisely: do not use <code>lambda</code>s. Python has list comprehensions which are exactly as powerful as <code>map</code> and <code>filter</code>, but are considered to be more readable. Here, your line</p>\n\n<pre><code>VowelCount = [sum(map(lambda x: x==Vowel,VowelData)) for Vowel in VowelList]\n</code></pre>\n\n<p>would become</p>\n\n<pre><code>count = [sum([x for x in vowel_data if x == vowel]) for vowel in vowel_list]\n</code></pre>\n\n<p>Of course, that is far from optimal as we make five passes through the data. If we use a dictionary, we can reduce this to a single pass:</p>\n\n<pre><code>vowels = \"aeiou\"\ncounts = dict([(vowel, 0) for vowel in vowels])\nfor x in data:\n counts[x] += 1\npercentages = [counts[vowel] * 100.0 / len(data) for vowel in vowels]\n</code></pre>\n\n<p>Note that I got rid of the unnecessary <code>vowel_</code> prefix here, and that I replaced <code>sum(VowelCount)</code> with the likely cheaper <code>len(data)</code> (but with all “optimizations”, the improvement should be benchmarked, not guessed).</p>\n\n<p>As per the <a href=\"http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.pie\"><em>pie</em>-plot documentation</a>, you should consider setting the aspect ratio of your axes, so that the resulting chart doesn't look distorted.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T10:45:13.203", "Id": "74419", "Score": "3", "body": "Even simpler is to use `counts = collections.Counter(data)`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T11:29:55.257", "Id": "74420", "Score": "0", "body": "You could also use `defaultdict` for a more concise code. (Also, you might like to know that Python has a syntax similar to list comprehension for dicts and sets so that you do not need to go through list definition)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-02T04:14:23.083", "Id": "74527", "Score": "0", "body": "I am realizing more and more that Hashmaps and Dictionaries are magical data structures." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T09:29:12.823", "Id": "43127", "ParentId": "43118", "Score": "6" } }, { "body": "<p>amon's comment about the names of your variable and the way you format your code is quite interesting. If you want more details, <a href=\"http://legacy.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP 8</a> is a style guide for Python code. It is definitely worth a read if you want to write code considered pythonic. You can find automated tools to check that your code respects the guideline such as <a href=\"http://pep8online.com/\" rel=\"nofollow\">pep8online</a>.</p>\n\n<hr>\n\n<p>Another thing that could be easily improved is the fact that the same thing is (implicitely) defined twice, violating the good old <a href=\"http://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow\"><strong>Don't repeat yourself</strong></a>. Indeed, you define the set of vowels in <code>VowelData = sub(r\"[^aeiou]\",\"\",DataToRead)</code> and in <code>VowelList = ['a','e','i','o','u']</code>. Probably one of them could be enough. You might think that it's not such a big deal because no one will want to change the definition of vowel but <a href=\"http://en.wikipedia.org/wiki/Y#Vowel\" rel=\"nofollow\">Y should it be so easy</a>.</p>\n\n<hr>\n\n<p><a href=\"http://en.wikipedia.org/wiki/KISS_principle\" rel=\"nofollow\"><strong>Keep it simple</strong></a> : if you were trying to count vowels manually in a very very long string, here's what you would do (or at least what you should do) : go through the string one character at a time, if it is a vowel, increment a corresponding counter (one counter per vowel). On the other hand, here's what you wouldn't do : use regexps to remove unwanted characters, then go through the remaining characters to count <code>a</code> then go through it again to count <code>e</code>, etc. What I am trying to say here is that first you only need to go through the string once, secondly regex is a powerful tool but the overhead in performance and readibility make it a bad option for your use case.</p>\n\n<hr>\n\n<p><strong>Using the right tool</strong> : at the moment, you are using Lists for <code>VowelList</code> and <code>VowelCount</code>. Lists are fine but in your case, you have better things :</p>\n\n<ul>\n<li><p>for <code>VowelList</code>, you should probably use it to know whether a character is to be considerer or not. Thus, the operation you'll care about is to test if a given element is part of a collection. The best data type for that is the <a href=\"http://docs.python.org/2/library/sets.html\" rel=\"nofollow\">set</a> : <code>vowels = {'a','e','i','o','u'}</code>. On top of being more efficient (which might or might not be the case for such q small collection), it shows what you have in mind to anyone reading your code.</p></li>\n<li><p>for <code>VowelCount</code>, it is a bit awkward to have a list of numbers and to have to go through another list to see what they mean. If you want to data (a count) associated to another data (a letter), a <a href=\"http://docs.python.org/2/library/stdtypes.html#mapping-types-dict\" rel=\"nofollow\">dict</a> is usually a good idea. Also for what you are trying to do, Python has some specialised types : <a href=\"http://docs.python.org/2/library/collections.html#collections.defaultdict\" rel=\"nofollow\">defaultdict</a> would allow you not to test if the value is here before incrementing it and even better for you : <a href=\"http://docs.python.org/2/library/collections.html#collections.Counter\" rel=\"nofollow\">Counter</a> does exactly what you want : <code>c = Counter(c for c in data if c in vowels}</code></p></li>\n</ul>\n\n<hr>\n\n<p>Finally :</p>\n\n<pre><code>from collections import Counter\ndata=\"jfalksfhjsdfhljasdhflsdjfhduiysasdvcsdpleaazioqhayiqahbcshjscsd\"\nvowels = {'a','e','i','o','u'}\ncount = Counter(c for c in data if c in vowels}\ncoef = 100./sum(count.itervalues()) # assuming a wovel is found - also use itervalues for Python &lt; 3\nprop = {x:coef*y for x,y in count.iteritems()} # or make this a list if you really want it\n</code></pre>\n\n<p>looks pretty good to me and I hope you'll like it.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T22:26:16.580", "Id": "43172", "ParentId": "43118", "Score": "4" } }, { "body": "<p>I agree with @Josay's suggestion to use <code>Counter</code>. I have just two tiny suggestions to add:</p>\n\n<ul>\n<li>Uppercase letters are vowels too. You stripped them out with your regex. I think that mapping them to lowercase would be more reasonable.</li>\n<li><p>Instead of using a list or a set for the vowels, consider using a string:</p>\n\n<pre><code>vowels = 'aeiou'\n</code></pre>\n\n<p>You don't need to do any fancy set operations on <code>vowels</code>. All you need is to be able to iterate over its elements, and strings are iterable.</p></li>\n</ul>\n\n\n\n<pre><code>from collections import Counter\nfrom string import lower\nfrom sys import stdin\nimport pylab\n\nvowels = 'aeiou'\nvowel_count = Counter(c for c in lower(stdin.read()) if c in vowels)\nprint vowel_count\n\ntotal = sum(vowel_count.itervalues())\nvowel_perc = [100.0 * vowel_count[x] / total for x in vowels]\n\npylab.pie(vowel_perc, labels=vowels, autopct='%1.1f%%')\npylab.show()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-02T09:15:58.103", "Id": "43212", "ParentId": "43118", "Score": "3" } } ]
{ "AcceptedAnswerId": "43127", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T05:32:22.090", "Id": "43118", "Score": "3", "Tags": [ "python" ], "Title": "Plotting Frequency of Vowels in a Paragraph" }
43118
<p>Earlier I posted a question about <a href="https://codereview.stackexchange.com/questions/42332/model-simulation-using-java-annotations">model simulation</a>, now I have code for model 'spatial' representation. My model consists of moving parts that can perform actions and each part occupies space within the model.</p> <p>I would like to use a graph to to represent relationships between model parts. ISpace defines methods for working with points(vertices). Space is the base class and I used two HashMaps to represent vertices and points because there should be one-to-one relation between them. I have looked at JGraph documentation and they represent graphs with sets of vertices and edges(links between two vertices), so maybe I should move my Point class into my Vertex class? (probably just use JGraph or another package instead of my own code).</p> <p>Space2D should represent a 2D toroidal space (like in Conway's game of life). Vertex could be any class.</p> <pre><code>package spacetest; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Random; import java.util.UUID; public class SpaceTest { public static void main(String[] args) { int vertexCount = 1000; int spaceWidth = 99; int spaceHeight = 99; Space2D space = new Space2D(0, spaceWidth, 0, spaceHeight); Random rand = new Random(); for (int i = 0; i &lt; vertexCount; i++) { Vertex v = new Vertex(); Point p = new Point(rand.nextInt(spaceWidth), rand.nextInt(spaceWidth)); while (space.vertexExists(p)) { p.x = rand.nextInt(spaceWidth); p.y = rand.nextInt(spaceHeight); } try { space.addElement(p, v); } catch (Exception e) { System.out.println(e.getStackTrace()); } } printVertices(space); for (int i = 0; i &lt; 10; i++) { Vertex[] vertices = space.getVertices().toArray(new Vertex[0]); for (Vertex vertice : vertices) { Point p = new Point(rand.nextInt(spaceWidth), rand.nextInt(spaceHeight)); try { space.moveVertex(vertice, p); } catch (Exception e) { System.out.println(e.getStackTrace()); } } System.out.println("----------------------------"); printVertices(space); } } private static void printVertices(Space2D space) { for (Vertex v : space.getVertices()) { Point p = space.getPoint(v); System.out.println(p.x + ", " + p.y); for (Vertex n : space.getNeighbors(v)) { Point np = space.getPoint(n); System.out.println("\t" + np.x + ", " + np.y); } } } } interface ISpace&lt;P, V&gt; { boolean addElement(P point, V vertex); boolean removeElement(P point, V vertex); boolean elementExists(P point, V vertex); boolean pointExists(V vertex); P getPoint(V vertex); boolean vertexExists(P point); V getVertex(P point); boolean moveVertex(V vertex, P destination); Collection&lt;P&gt; getPoints(); Collection&lt;V&gt; getVertices(); ArrayList&lt;V&gt; getNeighbors(V vertex); ArrayList&lt;P&gt; getAdjacentPoints(P point); } abstract class Space&lt;P, V&gt; implements ISpace&lt;P, V&gt; { private final Map&lt;P, V&gt; vertices = new HashMap&lt;&gt;(); private final Map&lt;V, P&gt; points = new HashMap&lt;&gt;(); private final Map&lt;P, ArrayList&lt;P&gt;&gt; adjacencyMap = new HashMap&lt;&gt;(); @Override public boolean addElement(P point, V vertex) { ArrayList&lt;P&gt; adjacentPoints = getAdjacentPoints(point); if (!points.containsKey(vertex) &amp;&amp; !vertices.containsKey(point)) { vertices.put(point, vertex); points.put(vertex, point); if (!adjacencyMap.containsKey(point)) { adjacencyMap.put(point, new ArrayList&lt;P&gt;()); } for (P adjacentPoint : adjacentPoints) { if (vertices.containsKey(adjacentPoint)) { adjacencyMap.get(point).add(adjacentPoint); adjacencyMap.get(adjacentPoint).add(point); } } return true; } else { return false; } } @Override public boolean removeElement(P point, V vertex) { if (points.containsKey(vertex) &amp;&amp; vertices.containsKey(point)) { points.remove(vertex); vertices.remove(point); for (P neighbor : adjacencyMap.get(point)) { if (adjacencyMap.containsKey(neighbor)) { adjacencyMap.get(neighbor).remove(point); } } adjacencyMap.remove(point); return true; } else { return false; } } @Override public boolean elementExists(P point, V vertex) { return pointExists(vertex) &amp;&amp; vertexExists(point); } @Override public boolean pointExists(V vertex) { return points.containsKey(vertex); } @Override public P getPoint(V vertex) { if (pointExists(vertex)) { return points.get(vertex); } else { return null; } } @Override public boolean vertexExists(P point) { return vertices.containsKey(point); } @Override public V getVertex(P point) { if (vertexExists(point)) { return vertices.get(point); } else { return null; } } @Override public boolean moveVertex(V vertex, P destination) { if (pointExists(vertex) &amp;&amp; vertexExists(destination)) { removeElement(getPoint(vertex), vertex); addElement(destination, vertex); return true; } else { return false; } } @Override public Collection&lt;P&gt; getPoints() { return points.values(); } @Override public Collection&lt;V&gt; getVertices() { return vertices.values(); } @Override public ArrayList&lt;V&gt; getNeighbors(V vertex) { ArrayList&lt;V&gt; neighbors = new ArrayList&lt;&gt;(); P point = getPoint(vertex); for (P neighboringPoint : adjacencyMap.get(point)) { neighbors.add(getVertex(neighboringPoint)); } return neighbors; } } class Space2D extends Space&lt;Point, Vertex&gt; { private int xMin; private int xMax; private int yMin; private int yMax; public Space2D(int xMin, int xMax, int yMin, int yMax) { this.xMin = xMin; this.xMax = xMax; this.yMin = yMin; this.yMax = yMax; } public int getX_min() { return xMin; } public void setX_min(int x_min) { this.xMin = x_min; } public int getX_max() { return xMax; } public void setX_max(int x_max) { this.xMax = x_max; } public int getY_max() { return yMax; } public void setY_max(int y_max) { this.yMax = y_max; } @Override public ArrayList&lt;Point&gt; getAdjacentPoints(Point origin) { int xWest = (origin.x == xMin) ? (xMax) : (origin.x - 1); int xEast = (origin.x == xMax) ? (xMin) : (origin.x + 1); int yNorth = (origin.y == yMin) ? (yMax) : (origin.y - 1); int ySouth = (origin.y == yMax) ? (yMin) : (origin.y + 1); ArrayList&lt;Point&gt; adjacentPoints = new ArrayList&lt;&gt;(); Point northWest = new Point(xWest, yNorth); Point north = new Point(origin.x, yNorth); Point northEast = new Point(xEast, yNorth); Point east = new Point(xEast, origin.y); Point southEast = new Point(xEast, ySouth); Point south = new Point(origin.x, ySouth); Point southWest = new Point(xWest, ySouth); Point west = new Point(xWest, origin.y); adjacentPoints.add(northWest); adjacentPoints.add(north); adjacentPoints.add(northEast); adjacentPoints.add(east); adjacentPoints.add(southEast); adjacentPoints.add(south); adjacentPoints.add(southWest); adjacentPoints.add(west); return adjacentPoints; } } class Point { int x; int y; public Point(int x, int y) { this.x = x; this.y = y; } @Override public boolean equals(Object o) { if (!(o instanceof Point)) { return false; } Point another = (Point) o; return ((x == another.x) &amp;&amp; (y == another.y)); } @Override public int hashCode() { int hash = 5; hash = 97 * hash + this.x; hash = 97 * hash + this.y; return hash; } } class Vertex { private final UUID id = UUID.randomUUID(); } </code></pre>
[]
[ { "body": "<p>You have some broad-spectrum questions....</p>\n\n<ul>\n<li><p>If JGraph supports the features you need, then absolutely, you should use it.</p>\n\n<p>Writing code is fun, and challenging, and all those things.... but, at some point you have to maintain it. Maintaining code becomes tedious, especially when you could be doing other things like writing code.</p>\n\n<p>Offloading asks that are going to become maintenance tasks is a smart thing.</p></li>\n<li><p>In your own space model, you are not doing things in what I would consider a logical format.... for a start, your code is not thread-safe.</p>\n\n<p>I would expect your program to have performance challenges, and the logical first step in any performance-challenged code is to use parallelism. As a consequence, I would expect Point, Vertex, and Space2D to be Immutable... (class is a <code>public final class ...</code>, all fields are <code>private final</code>, and there are no 'setter' methods). Immutable classes are thread safe, and will help a lot with performance.</p></li>\n<li><p>Vertex+edge vs. your model. Typically with models like this there are a few foundational perspectives that make sense. You could, for example, use polar coordinates instead of x/y because polar-coordinates are more easy to do spacial geometry with. Unfortunately they involve more complicated algorithms getting data in to and out of the model. If your work is primarily 'inside the model' rather than 'outside the model', then using polar space may make sense because the bulk of the work will be faster.</p>\n\n<p>The same is true for things like Edges vs. Vertices. They each have advantages in different conditions. Depending on your conditions, the one model may make sense over the other.</p>\n\n<p>What you have presented here is not nearly enough to make that decision.... but, for what it's worth, what you are doing is also not really pushing the performance limits enough on your systems to make the differences noticeable.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T14:03:18.860", "Id": "74444", "Score": "0", "body": "Yes JgraphT supports UndirectedGraph and also ListenableGraph which would I think fit very nicely with my project.Parallelism is yet another Java feature I will have to learn about. Thank you for your comments" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T12:33:36.163", "Id": "43133", "ParentId": "43124", "Score": "3" } } ]
{ "AcceptedAnswerId": "43133", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T08:55:37.843", "Id": "43124", "Score": "6", "Tags": [ "java", "algorithm" ], "Title": "Model spatial representation" }
43124
<p>I previously attempted to make a C++ vector <a href="https://codereview.stackexchange.com/questions/42297/c-vector-implementation">here</a>, yet it was not very successful. Now I have made a basic reimplementation of it, so I'm checking that it is fine, and that I will not have to re make it again.</p> <p>Note: I also implemented an <code>allocator</code> class, but it works the same as the <code>std::</code> equivalent.</p> <pre><code>template &lt; typename _Ty, typename _Alloc = allocator&lt;_Ty&gt; &gt; class vector { public: typedef vector&lt;_Ty, _Alloc&gt; _Myt; typedef _Ty value_type; typedef _Alloc allocator_type; typedef value_type *pointer; typedef const value_type *const_pointer; typedef value_type *iterator; typedef const value_type *const_iterator; typedef value_type &amp;reference; typedef const value_type &amp;const_reference; typedef std::size_t size_type; typedef std::ptrdiff_t difference_type; vector() : __size(0), __capacity(20), __data(_Alloc().allocate(20)) { } vector(const _Myt &amp;_Rhs) : __size(_Rhs.__size), __capacity(_Rhs.__size + 20), __data(_Alloc().allocate(_Rhs.__size)) { int count = 0; for (iterator i = &amp;_Rhs.__data[0]; i != &amp;_Rhs.__data[_Rhs.__size]; ++i, ++count) { _Alloc().construct(&amp;__data[count], *i); } } ~vector() { if (!empty()) { for (iterator i = begin(); i != end(); ++i) { _Alloc().destroy(i); } _Alloc().deallocate(__data, __capacity); } } _Myt &amp;push_back(const value_type &amp;_Value) { if (++__size &gt;= __capacity) { reserve(__capacity * 2); } _Alloc().construct(&amp;__data[__size - 1], _Value); return *this; } _Myt &amp;push_front(const value_type &amp;_Value) { if (++__size &gt;= __capacity) { reserve(__capacity * 2); } if (!empty()) { iterator _e = end(), _b = begin(); std::uninitialized_copy(_e - 1, _e, _e); ++_e; std::copy_backward(_b, _e - 2, _e - 1); } _Alloc().construct(&amp;__data[0], _Value); return *this; } _Myt &amp;reserve(size_type _Capacity) { int count = 0; if (_Capacity &lt; __capacity) { return *this; } pointer buf = _Alloc().allocate(_Capacity); for (iterator i = begin(); i != end(); ++i, ++count) { _Alloc().construct(&amp;buf[count], *i); } std::swap(__data, buf); for (iterator i = &amp;buf[0]; i != &amp;buf[__capacity]; ++i) { _Alloc().destroy(i); } _Alloc().deallocate(buf, __capacity); __capacity = _Capacity; return *this; } iterator begin() { return &amp;__data[0]; } iterator end() { return &amp;__data[__size]; } size_type size() { return __size; } size_type capacity() { return __capacity; } bool empty() { return !__data; } const_pointer data() { return __data; } private: pointer __data; size_type __size, __capacity; }; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-04T17:54:58.137", "Id": "75023", "Score": "0", "body": "Where are your test cases? And please, carefully check signatures of all members against 23.3.6 of [the draft Standard](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3797.pdf)" } ]
[ { "body": "<p>You're still using leading underscores. Why?? They're reserved.</p>\n\n<p>Methods like size should be const:</p>\n\n<pre><code>size_type size() const\n{\n return __size;\n}\n</code></pre>\n\n<p>The <code>empty</code> method should return <code>size() == 0</code>, not <code>!__data</code>.</p>\n\n<p>The <code>reserve</code> method should return <code>void</code>.</p>\n\n<p>In <code>reserve</code> I think that destroying everything up to <code>buf[__capacity]</code> is a mistake: instead, destroy everything up to <code>buf[__size]</code>.</p>\n\n<p>Because of the above, in push_front and push_back don't increment size before you call reserve.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T21:13:12.570", "Id": "43167", "ParentId": "43136", "Score": "5" } }, { "body": "<p><strong>STOP USING</strong> <code>__</code> its reserved for the implementation. </p>\n\n<p>Basically stop using underscore until you know the rules.\nThis code is basically all broken because of this. You code technically is all undefined.<br>\nWe told you this before. <strong>STOP IT</strong>.</p>\n\n<p>BUG:</p>\n\n<pre><code>vector(const _Myt &amp;_Rhs)\n : __size(_Rhs.__size), __capacity(_Rhs.__size + 20), __data(_Alloc().allocate(_Rhs.__size))\n</code></pre>\n\n<p>You are only allocating size space. But your capacity is 20 bytes larger.<br>\nWhy 20 bytes? Should this not be 20 objects <code>20 * sizeof(_Ty)</code></p>\n\n<p>BUG:</p>\n\n<p>You use the allocator construct routines when you are doing <code>placement new</code>. This means the space has not been constructed before. If the location has already got an element in it you must copy over it using the copy constructor.</p>\n\n<p>Thus in</p>\n\n<pre><code>_Myt &amp;push_front(const value_type &amp;_Value)\n</code></pre>\n\n<p>This line:</p>\n\n<pre><code> _Alloc().construct(&amp;__data[0], _Value);\n</code></pre>\n\n<p>You are constructing into location 0 a new object without calling the old objects destructor. If your type is anything non trivial this will screw up any memory management.</p>\n\n<p>BUG</p>\n\n<pre><code>bool empty()\n{\n return !__data; // Both constructors allocate memory.\n} // So this will never be true.\n</code></pre>\n\n<p>I think you mean</p>\n\n<pre><code> return size != 0;\n</code></pre>\n\n<p>You have a potential leak situation in your reserve().<br>\nYou provide the strong exception gurantee. BUT if the copy fails (with an exception) then you will leak the buffer. You need to hold the buffer in a smart pointer until you swap so that if there is an exception you gurantee that you deallocate the unused buffer.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T21:49:38.613", "Id": "43170", "ParentId": "43136", "Score": "11" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T12:49:39.403", "Id": "43136", "Score": "4", "Tags": [ "c++", "reinventing-the-wheel", "vectors" ], "Title": "Reimplementation of C++ vector" }
43136
<p>Do you see any inefficient parts with the following code? On internet I see 30 ms for 100.000 integers but I can sort 100.000 integers in 300ms. The data is random. I am using late 2013 macbook pro so I don't expect a 10x slowdown from CPU, but who knows.</p> <pre><code>void mergesort2(int* list, int begin, int end,int *tmplist=0){ bool allocated = false; if (end-begin &lt; 1) { return; } if (tmplist == 0) { allocated = true; tmplist = new int[end-begin+1]; } int middle = (begin+end)/2; mergesort2(list, begin, middle, tmplist); mergesort2(list, middle+1, end, tmplist); for (int first=begin, second=middle+1, tmp=0; tmp&lt;end-begin+1; tmp++) { if (first &gt; middle) { memcpy(tmplist+tmp, list+second, sizeof(int)*(end-begin-tmp+1)); } else if (second &gt; end) { memcpy(tmplist+tmp, list+first, sizeof(int)*(end-begin-tmp+1)); } else if (list[first] &lt;= list[second]) { tmplist[tmp] = list[first++]; }else{ tmplist[tmp] = list[second++]; } } memcpy(list+begin, tmplist, (end-begin+1)*sizeof(int)); if (allocated) { delete tmplist; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-07T06:09:24.637", "Id": "99096", "Score": "0", "body": "You have a memory allocation bug: you allocate with `operator new[]` but delete with `operator delete`. You should clean up `tmplist` with `delete [] tmplist;`" } ]
[ { "body": "<p>Few things here...</p>\n\n<ul>\n<li><p>the format of your input parameters is inconvenient. You should probably just replace the <code>begin</code> and <code>end</code> parameters with a single <code>size</code>. The method can then be called as:</p>\n\n<pre><code>mergesort2(list, middle, tmplist);\nmergesort2(list + middle, end - middle, tmplist);\n</code></pre>\n\n<p>this also fixes a lot of <code>+1</code> offsets you have where the <code>end</code> index is not convenient. It will also remove a lot of math where you are doing <code>end-begin+1</code> or equivalent.</p></li>\n<li><p>consider changing your mid-point calculation to be:</p>\n\n<pre><code>int middle = begin + (end - begin) / 2;\n</code></pre>\n\n<p>This avoids a bug when <code>begin</code> and <code>end</code> are large values, and the sum of them overflows the <code>int</code>.</p></li>\n<li><p>Actually, if it were me, I would be using the size method above, and I would declare <code>middle</code> to be 1 different than you:</p>\n\n<pre><code>int middle = (size + 1) / 2;\n</code></pre>\n\n<p>this makes the second 'half' the 'smaller' half, and it removes all the '+1' offsets you have to apply later in the code (it also changes some other range checks/limits), but, overall it will simplify the code.</p></li>\n<li><p>Small nit-pick - I dislike magic numbers, especially 'vagrant' <code>+ 1</code> values... consider this line here:</p>\n\n<blockquote>\n<pre><code>for (int first=begin, second=middle+1, tmp=0; tmp&lt;end-begin+1; tmp++) {\n</code></pre>\n</blockquote>\n\n<p>This <code>+1</code> could be avoided with (if you have a good size, and middle):</p>\n\n<pre><code>for (int first=begin, second=middle, tmp=0; tmp&lt;size; tmp++) {\n</code></pre></li>\n<li><p>performance/correctness: declare <code>begin</code> and <code>end</code> to be constants in the method signature.</p></li>\n<li><p>performance/correctness: inside your loop you have two conditions:</p>\n\n<blockquote>\n<pre><code>if (first &gt; middle) { .... }\nelse if (second &gt; end) { .... }\n</code></pre>\n</blockquote>\n\n<p>inside each of those blocks you should <code>break;</code> so that you do not need to repeatedly copy the memory which does not need merging.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T15:20:40.843", "Id": "74458", "Score": "0", "body": "I have always struggled with +1 -1s, I will try to follow these guidelines and I hope they will help me in the long run!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-04T01:34:31.820", "Id": "74864", "Score": "2", "body": "Don't like the idea of using size rather than begin and end. It goes against the normal way C++ code is written. If the code had been tagged C then I would have agreed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-04T01:59:41.860", "Id": "74869", "Score": "1", "body": "@LokiAstari - yeah, I was trapped by the [original question not having a language tag at all](http://codereview.stackexchange.com/revisions/43138/1), and the OP [never really paid much attention at the time](http://codereview.stackexchange.com/questions/43138/mergesort-performance#comment74447_43138)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T15:09:02.077", "Id": "43143", "ParentId": "43138", "Score": "5" } }, { "body": "<p>A C++ merge sort in the style of a Standard Library algorithm could be written as </p>\n\n<pre><code>template&lt;class BiDirIt, class Compare = std::less&lt;typename std::iterator_traits&lt;BiDirIt&gt;::value_type&gt;&gt;\nvoid merge_sort(BiDirIt first, BiDirIt last, Compare cmp = Compare())\n{\n auto const N = std::distance(first, last);\n if (N &lt; 2) return;\n auto middle = std::next(first, N / 2);\n merge_sort(first, middle, cmp);\n merge_sort(middle, last, cmp);\n std::inplace_merge(first, middle, last, cmp);\n}\n</code></pre>\n\n<p>Let's look at how this improves upon your design:</p>\n\n<ul>\n<li><strong>generic interface</strong>: it takes two iterators and a comparison function of arbitrary types, instead of two indices into a pointer to an array of <code>int</code> and the implicit but fixed <code>&lt;</code> comparison.</li>\n<li><strong>in-place</strong>: behind the covers it calls <code>std::inplace_merge</code> that can allocate extra memory but it does it so that users don't have to supply this, instead of your <code>tmplist</code> parameter.</li>\n<li><strong>half-open intervals</strong>: it will split the input range <code>[first, last)</code> into <code>[first, middle)</code> and <code>[middle, last)</code> which automically takes care of easy to make \"off-by-one\" errors in code like <code>middle + 1</code> (in your code it is correct, but you still have to think about it, half-open intervals are easier to get right).</li>\n<li><strong>named algorithms</strong>: it uses <code>std::inplace_merge</code> as a ready-to-use component instead of a somewhat long and certainly tricky final step in your algorithm. Not only makes this your <code>merge_sort</code> more compact, the <code>inplace_merge</code> itself is a resuable component in its own right!</li>\n<li><strong>heavily optimized</strong>: Standard Library experts are very likely to know about the state of the art in writing performance-optimized algorithms. A factor of 10 of performance compared to your code seems a lot, but if you forget some hidden copies, use a hand-written loop that has <code>O(N^2)</code> complexity instead of <code>O(N log N)</code> you can quickly get there.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-03T14:03:47.830", "Id": "43303", "ParentId": "43138", "Score": "14" } }, { "body": "<p>Back to the original question, I created a small test fixture for experimenting with your code (after all, had to confirm it actually worked first!)</p>\n\n<pre><code>#define NUM_OF_INTS 100000\n#define DEBUG 0\nint main()\n{\n int numbers[NUM_OF_INTS]; \n int i;\n int *tmplist;\n\n tmplist = new int[NUM_OF_INTS];\n\n srand(0);\n\n for( i = 0; i &lt; NUM_OF_INTS; i++ )\n numbers[i] = rand()%10000;\n\n if (DEBUG == 1)\n for( i = 0; i &lt; NUM_OF_INTS; i++ )\n printf( \"%03i:%04i\\n\", i, numbers[i] ); \n\n mergesort2( &amp;numbers[0], 0, NUM_OF_INTS, tmplist );\n\n if (DEBUG == 1 ) printf( \"\\n\"); \n\n if (DEBUG == 1)\n for( i = 0; i &lt; NUM_OF_INTS; i++ )\n printf( \"%03i:%04i\\n\", i, numbers[i] ); \n\n return 0;\n}\n</code></pre>\n\n<p>Running this test fixture in my enviroment, I see about .7s for 100k ints. I initially thought checking for tmplist in every recursive iteration might be causing a performance degradation, but it made a negligible change in execution time. I then started down the path of reimplementing mergesort without a temporary array, thinking that the array memcopies might be the root cause of the performance issue, when I stumbled upon what is wrong with your code. </p>\n\n<p>Hint</p>\n\n<ul>\n<li>Think about why the memcpy's are there inside the for loop. What is their purpose? Why are they necessary? What does it mean algorithmically when those memcpy's are done executing? What should happen next?</li>\n</ul>\n\n<p>Spoiler (really think &amp; test your code before looking at this)</p>\n\n<blockquote class=\"spoiler\">\n <p> You need to do a <code>break;</code> to quit the for loop after each memcopy for the two degenerate cases (first advances past midpoint, middle advances past end). Otherwise you are doing repeated memcpys (which lucky or unlucky, have no effect on the output), until tmp finally reaches the end.</p>\n</blockquote>\n\n<p>With the fix, the code can now do 100k ints in .08s in my environment, hence the 10x improvement you were looking for.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-04T07:43:03.520", "Id": "43380", "ParentId": "43138", "Score": "3" } }, { "body": "<p>After fixing the problem @RichHendricks pointed out this still has...not a problem exactly, but still a design that's less than optimal (at least in my opinion).</p>\n\n<p>In the initial phase, you basically do:</p>\n\n<pre><code>calculate middle\nrecurse on left side\nrecurse on right side\n</code></pre>\n\n<p>Each of those recursive calls does the same thing again. Modern processors have done quite a bit to make calls and returns more efficient, but that still adds quite a bit of overhead when the fundamental operation involved is basically just computing the arithmetic mean of two numbers.</p>\n\n<p>You can avoid that by using a bottom-up merge-sort. Instead of recursively splitting the array in half until it gets down to some manageable size, you can simply take the first N elements and sort them with some low-overhead sort (typically an insertion sort). Repeat N elements at a time until you reach the end of the collection (though, of course, the last group might not be the same same size as the others).</p>\n\n<p>Then take the first two sorted groups of N elements and merge them. Repeat for the next pair of groups until you reach the end. Repeat that process until all the groups have been merged into one.</p>\n\n<p>As to how to do the merging: a couple of papers<sup>1</sup> have been written about in-place merging. I should add that quite a few algorithms to do this have been devised, but many (most?) are primarily theoretical--in theory, they have low enough computational complexity to maintain the O(N log n) complexity of the merge sort as a whole, but in fact they impose so much overhead that other methods are faster for almost any practical amount of data. I've tried to restrict the list of citations below to ones that seem to have at least some chance of being practical, not just theoretical.</p>\n\n<p>One last point: contrary to one widespread belief, this is an area where you actually stand a pretty decent chance of writing code significantly better than the standard library provides. The C++ standard library does include an inplace_merge algorithm, but it's allowed to be significantly slower than the best algorithms now known. At least if I recall correctly these requirements haven't been updated since the 1998 standard, which was before many of the best in-place merging algorithms were invented. I don't claim to have looked at every implementation of in-place merging in every standard library, but I have seen at least a few relatively recent ones that used older, substantially less efficient algorithms.</p>\n\n<hr>\n\n<ol>\n<li>For a few examples:</li>\n</ol>\n\n<p><a href=\"http://akira.ruc.dk/~keld/teaching/algoritmedesign_f04/Artikler/04/Huang88.pdf\" rel=\"nofollow\">http://akira.ruc.dk/~keld/teaching/algoritmedesign_f04/Artikler/04/Huang88.pdf</a>\n<a href=\"http://www.sofsem.cz/sofsem06/data/prezentace/23/A/Kim-OnOptimalandEfficientInPlaceMerging.ppt\" rel=\"nofollow\">http://www.sofsem.cz/sofsem06/data/prezentace/23/A/Kim-OnOptimalandEfficientInPlaceMerging.ppt</a>\n<a href=\"http://www.dcs.kcl.ac.uk/technical-reports/papers/TR-04-05.pdf\" rel=\"nofollow\">http://www.dcs.kcl.ac.uk/technical-reports/papers/TR-04-05.pdf</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-10T15:01:16.313", "Id": "43944", "ParentId": "43138", "Score": "3" } } ]
{ "AcceptedAnswerId": "43143", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T13:46:31.267", "Id": "43138", "Score": "7", "Tags": [ "c++", "performance", "sorting", "mergesort" ], "Title": "MergeSort performance" }
43138
<blockquote> <p>Write the program <code>tail</code>, which prints the last <code>n</code> lines of its input. By default, <code>n</code> is 10, let us say, but it can be changed by an optional argument, si that <code>tail -n</code> prints the last <code>n</code> lines. The program should behave rationally no matter how unresonable the input or the value <code>n</code>. Write the program so it makes the best use of available storage; lines should be stored as in the sorting program of section 5.6, not in a two-dimensional array of fixed size.</p> </blockquote> <p>The exercise can be found on page 133 in K&amp;R.</p> <p>I will explain the way my program works. First it parses the value of the symbolic argument(if any). Based on the value of the symbolic argument the program will initialize a queue which stores pointer to each line.</p> <p>Then, the program will read lines and push every line in the queue until the end of files is reached. When the end of file is reached all elements of the queue are printed out.</p> <p>There are multiple files in my project:</p> <p><code>main.c</code>:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include "tail.h" #define MAXLINES 100 #define LINESIZE 100 int main(int argc, char *argv[]) { int linesNumber = 10; if(argc &gt; 2) { return 1; } else if(argc == 2) { linesNumber = atoi(argv[1] + 1); if(linesNumber == 0) { return 0; } initQueue(linesNumber, LINESIZE); } else { initQueue(linesNumber, LINESIZE); } readLines(LINESIZE, MAXLINES); printQueueElements(); return 0; } </code></pre> <p><code>linesNumber</code> represent the variable that will store the size of the queue. By default this variable is <code>10</code>. If the value of the symbolic argument is <code>0</code> there is no reasone to continue reading lines, so the program will terminate execution.</p> <p><code>queue.c</code></p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; #include "alloc.h" static char **queue; static int queueSize; static int head = -1; static int rear = -1; static int isEmpty(void) { return (head == -1 &amp;&amp; rear == -1); } static int isFull(void) { return (rear + 1) % queueSize == head ? 1 : 0; } void initQueue(int lineNumbers, int sizeOfEachLine) { int i; queue = palloc(lineNumbers); queueSize = lineNumbers; for(i = 0; i &lt; lineNumbers; i++) { queue[i] = alloc(sizeOfEachLine); } } char *dequeue(void) { char *returnValue; if(isEmpty()) { return NULL; } else if(head == rear) { returnValue = queue[head]; head = -1; rear = -1; return returnValue; } returnValue = queue[head]; head = (head + 1) % queueSize; return returnValue; } void enqueue(char *source) { if(isFull()) { dequeue(); } if(isEmpty()) { rear = 0; head = 0; } else { rear = (rear + 1) % queueSize; } strcpy(queue[rear], source); } void printQueueElements(void) { while(!isEmpty()) { printf("%s", dequeue()); } } </code></pre> <p>This is an array based implementation of a queue. I use the circular array data structure for my queue.</p> <p>When the queue is full, <code>enqueue</code> will call <code>dequeue</code> to make space for the incoming element. </p> <p><code>printQueueElements</code> will <code>dequeue</code> each element and print it, since I don't need anymore the lines. </p> <p><code>readlines.c</code>:</p> <pre><code>#include &lt;stdio.h&gt; #include "alloc.h" #include "tail.h" static int getLine(char *source, int lim) { int c; int i; c = getchar(); lim--; /* 1 space for null charachter */ for(i = 0; c != EOF &amp;&amp; c != '\n' &amp;&amp; lim &gt; 0; i++, c = getchar(), lim--) { source[i] = c; } if(c == '\n') { source[i] = '\n'; i++; } source[i] = '\0'; return i; } void readLines(int lineSize, int maxLines) { char *temp = alloc(lineSize); for(; maxLines &amp;&amp; getLine(temp, lineSize); maxLines--) { enqueue(temp); } } </code></pre> <p>This function will read each line and <code>enqueue</code> it.</p> <p><code>alloc.c</code></p> <pre><code>#include &lt;stdio.h&gt; #define ALLOCSIZE 10000 static char allocBuf[ALLOCSIZE]; static char *allocp = allocBuf; /* next free position */ char *alloc(int allocSize) { if(allocBuf + ALLOCSIZE - allocp &gt;= allocSize) { allocp += allocSize; return allocp - allocSize; } else { return NULL; } } </code></pre> <p>This function will return a pointer to a block of <code>allocSize</code> <code>chars</code>.</p> <p><code>palloc.c</code></p> <pre><code>#include &lt;stdio.h&gt; #define BLOCKSIZE 100000 static char *sharedBlock[BLOCKSIZE]; static char **pSharedBlock = sharedBlock; char **palloc(int size) { if(sharedBlock + BLOCKSIZE - pSharedBlock &gt;= size) { pSharedBlock += size; return pSharedBlock - size; } else { return NULL; } } </code></pre> <p>This function wil return a pointer to a block of <code>size</code> <code>pointers to char</code>.</p> <p><code>palloc</code> and <code>alloc</code> are used to set the size of the queue dynamically. The <code>malloc</code> function was not introduced at this point, so I don't think it will be a valid solution if I use this function.</p> <p><code>alloc.h</code></p> <pre><code>char *alloc(int); char **palloc(int); </code></pre> <p><code>tail.h</code></p> <pre><code>/* input functions */ void readLines(int lineSize, int maxLines); /* queue related functions */ void initQueue(int lineNumbers, int sizeOfEachElement); void enqueue(char *source); void printQueueElements(void); char *dequeue(void); int getSimbolicArgValue(char* source); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T17:00:40.893", "Id": "74468", "Score": "0", "body": "I can't really help you on that, but limiting the line size to 100 chars is a mistake in my opinion." } ]
[ { "body": "<p>I don't think the program meets the requirements (i.e. &quot;behave rationally no matter how unresonable the input&quot;) because it fails if the line size is greater than LINESIZE.</p>\n<p>To behave rationally it would perhaps, ideally:</p>\n<ul>\n<li>At least detect if a line is &quot;too large&quot; and fail properly</li>\n<li>Or, properly handle a huge line (which fits on disk but is too large to fit in memory)</li>\n</ul>\n<p>I'd suggest writing 2 versions.</p>\n<ol>\n<li><p>The first version should guess how long each line is (e.g. 200 bytes). If the user asks for 10 lines, it should therefore fseek to the last 2000 bytes of the file, try to parse the last 2000 bytes, and display the result if successful.</p>\n<p>If it doesn't find the right number of lines in the last 2000 bytes, then either try again with the previous 2000 bytes, or fail over to scanning the entire file.</p>\n</li>\n<li><p>When it scans the entire file, it should remember the start (byte offset) of the most recent 10 lines, so that when it reaches the end of the file it can print the end of the file from the 10th-most-recent byte offset. I see no need to remember the contents of each line.</p>\n</li>\n</ol>\n<p>The first is just a speed optimization for normal large files (assuming that fseek is faster than parsing). If it just needs to be correct instead of fast then only implement the 2nd version.</p>\n<hr />\n<p><a href=\"http://www.gnu.org/software/coreutils/manual/html_node/tail-invocation.html\" rel=\"noreferrer\">tail</a> usually accepts a filename as an input parameter, and files are usually seekable.</p>\n<p>If it's reading from stdin then stdin may not be seekable, in which you case you must buffer the lines which you read (and intend to print) in memory.</p>\n<hr />\n<p>I don't fully agree with your decision not to use malloc.</p>\n<p>If you want to use your palloc function I think it has too many pointers (surely you want an array of bytes, not an array of byte-pointers), and should be like this instead:</p>\n<pre><code>#define BLOCKSIZE 100000\n\nstatic char sharedBlock[BLOCKSIZE];\nstatic size_t alreadyAllocated;\n\nchar *palloc(int size) {\n if(size + alreadyAllocated &lt;= BLOCKSIZE) {\n char* rc = &amp;sharedBlock[alreadyAllocated];\n alreadyAllocated += size;\n return rc;\n }\n else {\n return NULL;\n }\n}\n</code></pre>\n<hr />\n<p>I haven't analyzed/inspected your readline.c and queue.c in detail.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T19:52:46.053", "Id": "43164", "ParentId": "43142", "Score": "6" } }, { "body": "<p>That is a lot of code for the job. It can be done significantly more easily in two areas:</p>\n\n<ul>\n<li>use an array instead of a queue</li>\n<li>use the POSIX function, <code>getline</code>, which will handle lines of any size. </li>\n</ul>\n\n<p>If you don't want to use <code>getline</code> (which admittedly might not have existed when K&amp;R wrote their book), concentrate on writing its equivalent. </p>\n\n<p>Here is a version that uses an allocated array or char* pointers. The array is zeroed (by <code>calloc</code>) so that we can tell whether the entry holds a line (which might not be so if the input is less than 10 (or the requested number of) lines.</p>\n\n<pre><code>int\ntail(size_t n_lines, FILE *fp)\n{\n char **lines = calloc(sizeof(char*), n_lines);\n if (!lines) {\n perror(\"calloc\");\n return -1;\n }\n size_t size = 0;\n size_t in = 0;\n for (char *ln = 0; getline(&amp;ln, &amp;size, fp) &gt; 0; in = (in + 1) % n_lines) {\n if (lines[in]) {\n free(lines[in]);\n }\n lines[in] = ln;\n ln = NULL;\n size = 0;\n }\n for (size_t i = 0; i &lt; n_lines; ++i) {\n if (lines[in]) {\n printf(\"%s\", lines[in]);\n free(lines[in]);\n }\n in = (in + 1) % n_lines;\n }\n free(lines);\n return 0;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T20:57:14.793", "Id": "74488", "Score": "0", "body": "size needs to be reset to 0 before you call [getline](http://man7.org/linux/man-pages/man3/getline.3.html) again. And you need to call `free(lines[in])` before you overwrite a previously-initialized (non-empty) line." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-06-19T09:37:50.747", "Id": "316278", "Score": "0", "body": "It's not safe to assume that memory zeroed by `calloc()` can be safely accessed as pointer values and compare equal to a null pointer. Whilst the most common representation of a 0 pointer is all-bits-zero, that's not mandated by Standard C." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T20:39:34.187", "Id": "43166", "ParentId": "43142", "Score": "10" } }, { "body": "<p>For a general <code>tail</code> implementation, there are two distinct cases that have very different optimal solutions:</p>\n\n<ul>\n<li><p>When the input is <a href=\"http://man7.org/linux/man-pages/man3/fseek.3.html\" rel=\"nofollow\"><strong>seekable</strong></a>, you can read it backwards from the end (by seeking to the end and then repeatedly reading a block of, say, a couple of kilobytes and seeking backwards to the previous block) to find the beginning of the <em>n</em>-th last line, and then just read and print the content of the file starting from that position. Done properly, this will allow you to solve the problem using a constant amount of memory.</p></li>\n<li><p>If the input is <strong>not seekable</strong>, you'll <em>have</em> to read it sequentially and buffer the <em>n</em> last lines you've seen so far. The task, then, is to do this as efficiently as possible.</p>\n\n<p>As the other answers have pointed out, you cannot generally assume an upper limit on the length of a line; it's quite possible to have a file with several gigabytes of text and no line breaks at all, making it all one long line. The simplest solution to this issue is probably to use POSIX <a href=\"http://man7.org/linux/man-pages/man3/getline.3.html\" rel=\"nofollow\"><code>getline()</code></a>; if you can't or don't want to use it, you'll have to implement your own e.g. using <a href=\"http://man7.org/linux/man-pages/man3/fgets.3.html\" rel=\"nofollow\"><code>fgets()</code></a> and <a href=\"http://man7.org/linux/man-pages/man3/realloc.3.html\" rel=\"nofollow\"><code>realloc()</code></a>.</p>\n\n<p>Alternatively, you could simply allocate a <a href=\"http://en.wikipedia.org/wiki/Circular_buffer\" rel=\"nofollow\">circular buffer</a> to store the last <em>k</em> bytes of the file, while keeping track (in another circular buffer) of the starting positions of the last <em>n</em> lines in it. Before reading each new block of input, check if you have room to do so without overwriting the <em>n</em>-th last line; if not, increase (e.g. double) the buffer size with <code>realloc()</code>.</p>\n\n<p>If you <em>really</em> want to optimize you code for the worst case, you could, if the buffer gets too large, even consider switching to a different storage method where you split the buffer into chunks of, say, a few megabytes each, and store each of them in an <a href=\"http://man7.org/linux/man-pages/man2/mmap.2.html\" rel=\"nofollow\"><code>mmap()</code></a>ed temp file. The main advantage of this method (over just letting the OS swap out parts of your buffer) is that you can efficiently discard old swapped-out data just by unmapping the file without having to first read it back into RAM. However, this is probably getting a bit too advanced for this exercise.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-02T01:47:23.420", "Id": "43192", "ParentId": "43142", "Score": "2" } } ]
{ "AcceptedAnswerId": "43164", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T15:06:46.610", "Id": "43142", "Score": "12", "Tags": [ "c", "beginner", "queue", "pointers" ], "Title": "Tail implementation in C" }
43142
<p>This is the situation : the table order has a column with ID AUTO INCREMENT but (there is always a but)<br> i can't use it because i don't want number order 1234567 after 5 years but i want 1/2014 , 1/2015 etc etc. For doing this i have created this columns into the table :</p> <pre><code>ID AUTO INCREMENT &lt;--- unique ID used for manage the order after the insert numberorder INT &lt;--- fake number of order showed at the user NOT unique IDyear YEAR &lt;--- the year for the order e.g. 2014 or 2015 </code></pre> <p>For doing this i write this code before the query for insert a new order<br> and processed at the submit form :</p> <pre><code>$query_Recordset4 = "SELECT MAX(IDyear) AS maxyear FROM order"; $Recordset4 = $mysqli-&gt;query($query_Recordset4); $row_Recordset4 = $Recordset4-&gt;fetch_assoc(); $maxyear = $row_Recordset4['maxyear'] ; $thisyear = date("Y") ; if ($maxyear === $thisyear) { $query_Recordset5 = "SELECT MAX(numberorder) FROM order WHERE IDyear=$thisyear ;"; $Recordset5 = $mysqli-&gt;query($query_Recordset5); $row_Recordset5 = $Recordset5-&gt;fetch_assoc(); $numberorder = $row_Recordset5['MAX(numberorder)'] + 1 ; } else { $numberorder = 1 ; } </code></pre> <p>And then i use $numberorder for insert them into the table order in his column.</p> <p><strong>QUESTION REVIEW</strong></p> <p>Maybe my question was not clear written and now i try to add some elements.</p> <p>Thit is what i have now into the table order :</p> <pre><code>|----------|-------------|--------| | ID | numberorder | yearId | |----------|-------------|--------| ! 1 | 1 | 2014 | |----------|-------------|--------| | " | " | " | &lt;---- more orders |----------|-------------|--------| | 500 | 500 | 2014 | &lt;---- last order year 2014 |----------|-------------|--------| </code></pre> <p>When the year change what i need is this :</p> <pre><code>|----------|-------------|--------| | 501 | 1 | 2015 | &lt;---- first order year 2015 (2016,2017 etc etc) |----------|-------------|--------| </code></pre> <p>Like a suggestion, my code has a concurrency problem.</p> <p>Have a second table yearid with another AUTO_INCREMENT field for take to them a unique ID for numberorder field is perfect solution but when the year finish i can't restarting the AUTO_INCREMENT at 1 because for security reason the TRUNCATE and DROP commands are not available for the user created for the connection.</p> <p>The only way i see is create a new table each year e.g. yearid2015 for have ID = 1.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T18:02:18.197", "Id": "74475", "Score": "0", "body": "It would be more helpful if you included your database table schema." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T18:45:30.000", "Id": "74479", "Score": "0", "body": "@SimonAndréForsberg done :)" } ]
[ { "body": "<pre><code>$query_Recordset4 = \"SELECT MAX(IDyear) AS maxyear FROM order\";\n</code></pre>\n\n<p>Whenever you need to postfix the name of a variable, class or anything else with number because you already used that name...you're doing it wrong. Either your function does too much and should be split into smaller functions, or you need to choose better names.</p>\n\n<hr>\n\n<pre><code>$query_Recordset5 = \"SELECT MAX(numberorder) FROM order WHERE IDyear=$thisyear ;\";\n</code></pre>\n\n<p>Even when you declare the variable, you should make a habit out of using parameterized queries.</p>\n\n<hr>\n\n<p>There's something wrong about your table layout. At the moment I imagine it should look something like this:</p>\n\n<pre><code>TABLE order\n numberorder INT\n IDyear INT\n</code></pre>\n\n<p>A more sane layout would be this:</p>\n\n<pre><code>TABLE order\n id INT AUTO_INCREMENT\n idYear INT\n orderedAt DATETIME\n</code></pre>\n\n<p>The main difference is that I rely on an ID field which is managed by the database. It does not matter what the accountant wants or how your boss thinks the billing numbers should look like, you need something <em>unique to identify a record</em> and nothing beats a <em>unique, automatically managed counter</em> for doing that job.</p>\n\n<p>Creating the necessary number you want is as easy as</p>\n\n<pre><code>SELECT CONCAT(idYear, '/', YEAR(orderedAt)) FROM order;\n</code></pre>\n\n<p>and if you place this in a stored procedure or in a function in your object you never need to think about it again. Incrementing this number is also rather easy:</p>\n\n<pre><code>SELECT IFNULL(MAX(idYear), 0) + 1 FROM order WHERE YEAR(orderedAt) = yourYear;\n</code></pre>\n\n<p>It can not break and you're free to put the date of the order into the past or the future (which is sometimes needed in accounting). In your method working outside of the current year will break the numbering.</p>\n\n<hr>\n\n<p>Ideally you would set that number if you insert the record into the database to minimize race-conditions (and possible duplicate numbers).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T17:35:42.820", "Id": "74472", "Score": "0", "body": "My method is \"for break the numbering\" and restart at 1 each year. The first column in order table is ID AUTO INCREMNT and for the management of the order i refer at this unique ID but at the user is showed only the \"fake\" id nuber $numberorder e.g. 12 / 2014 where 12 is $numberorder and 2014 is IDyear (ok, ok.. now i change it in idYear ;) )" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T16:57:24.393", "Id": "43151", "ParentId": "43147", "Score": "2" } }, { "body": "<p>This is not so much a question about mysqli and php, but about databases and database theory.</p>\n\n<p>Consider two simultaneous accesses to your page... they will both get the same result for:</p>\n\n<pre><code>$numberorder = $row_Recordset5['MAX(numberorder)'] + 1 ;\n</code></pre>\n\n<p>and they will both try to insert with the same ID value, and one of them will fail.</p>\n\n<p>The AUTOINCREMENT system is designed to be concurrently safe, and guarantees that just one record has the value.</p>\n\n<p>Depending on who you read/listen/pay attention to, you will get different answers, but, in your case, you really have to question: <em>Why do you need a special primary key?</em>. If the answer is because you want a value that fits some other format, well, then, there are other solutions.... for example, you can do the following:</p>\n\n<pre><code>create table YearId (\n int year not null,\n int firstid not null,\n int lastid not null\n}\n</code></pre>\n\n<p>Then you can have a column that you can update as :</p>\n\n<pre><code>update table set yearid = (select year + '/' + (id - firstid) from YearId where id between firstid and lastid)\n</code></pre>\n\n<p>The alternatives to this sort of logic are complicated transactions that need to be managed in PHP using begin-transactions and commit-transactions.</p>\n\n<p>Doing that would be a 'leap' in your requirements.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T17:29:31.243", "Id": "74470", "Score": "0", "body": "the code work when the user click on submit button, not before and bring ofcourse the last ID. No way to have the same ID value." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T17:32:21.183", "Id": "74471", "Score": "0", "body": "@geomo - what if two people click the submit button at the same time...?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T17:57:06.780", "Id": "74473", "Score": "0", "body": "sorry for the lag.. we have try now many time.. always one user arrived first then other.. even if we click at the same time.. i think only two robot doing this but if the line cable is more long then other so one query arrived second." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T18:01:30.520", "Id": "74474", "Score": "1", "body": "@geomo Trying to check if concurrency works or not by trying to click a button \"at the same time\" isn't very useful. I think rolfl is right here and that it *could* cause a problem. If that problem happens once every 10 times, once every 1000 times or once every million times is another question - but it is still a problem. Using rolfl's approach, you can guarantee that there will not be a problem." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T17:00:21.023", "Id": "43152", "ParentId": "43147", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T16:41:39.013", "Id": "43147", "Score": "2", "Tags": [ "php", "mysqli" ], "Title": "Workaround for have 2 column with pseudo AUTO INCREMENT" }
43147
<p>I am writing a wrapper to Eigen QR for my personal use and I am wondering if there are any memory leaks or undocumented behavior in my implementation, especially in the function <code>get_QR()</code>.</p> <p>The answer is as expected. This is related to my previous question <a href="https://stackoverflow.com/questions/22103526/weird-behavior-when-using-eigen">here</a>.</p> <pre><code>using std::cout; using std::endl; using namespace Eigen; /*! Obtains the QR decomposition as A=QR, where all the matrices are in Eigen MatrixXd format. */ void get_QR(MatrixXd A, MatrixXd&amp; Q, MatrixXd&amp; R) { int m = A.rows(); int n = A.cols(); int minmn = min(m,n); // A_E = Q_E*R_E. HouseholderQR&lt;MatrixXd&gt; qr(A); Q = qr.householderQ()*(MatrixXd::Identity(m, minmn)); R = qr.matrixQR().block(0, 0, minmn, n).triangularView&lt;Upper&gt;(); } /*! Obtains the QR decomposition as A=QR, where all the matrices are in double format. */ void get_QR(double* A, int m, int n, double*&amp; Q, double*&amp; R) { MatrixXd Q_E, R_E; int minmn = min(m,n); // Maps the double to MatrixXd. Map&lt;MatrixXd&gt; A_E(A, m, n); get_QR(A_E, Q_E, R_E); Q = (double*)realloc(Q_E.data(), m*minmn*sizeof(double)); R = (double*)realloc(R_E.data(), minmn*n*sizeof(double)); } int main(int argc, char* argv[]) { srand(time(NULL)); int m = atoi(argv[1]); int n = atoi(argv[2]); // Check the double version. int minmn = min(m,n); double* A = (double*)malloc(m*n*sizeof(double)); double* Q = (double*)malloc(m*minmn*sizeof(double)); double* R = (double*)malloc(minmn*n*sizeof(double)); double RANDMAX = double(RAND_MAX); // Initialize A as a random matrix. for (int index=0; index&lt;m*n; ++index) { A[index] = rand()/RANDMAX; } get_QR(A, m, n, Q, R); std::cout &lt;&lt; Q[0] &lt;&lt; std::endl; // Check the MatrixXd version. Map&lt;MatrixXd&gt; A_E(A, m, n); MatrixXd Q_E, R_E; get_QR(A_E, Q_E, R_E); cout &lt;&lt; Q[0] &lt;&lt; endl; cout &lt;&lt; Q_E(0,0) &lt;&lt; endl; free(A); free(Q); free(R); } </code></pre> <p>For instance, I get the output as</p> <blockquote> <pre><code>-0.360995 -0.360995 -0.360995 </code></pre> </blockquote>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T18:19:21.597", "Id": "74477", "Score": "1", "body": "You mean apart from using `malloc` in C++ code?" } ]
[ { "body": "<p>First check that there are the enough command line parameters</p>\n\n<pre><code>// If there are not enough parameters\n//\n// If there are no parameters passed then\n// Then argv[1] is NULL\n// argv[2] is random\n int m = atoi(argv[1]);\n int n = atoi(argv[2]);\n</code></pre>\n\n<p>If not enough parameters are passed then this can get you funny number in <code>m</code> and <code>n</code> which will affect how much memory you allocate.</p>\n\n<p>Don't use malloc in C++ code.<br>\nYou can not mix malloc/free with new/delete. So by only using one system of memory management you will not mix up the two different types of memory.</p>\n\n<pre><code> double* A = (double*)malloc(m*n*sizeof(double));\n\n // Also the C++ interface is simpler.\n\n double* A = new double[m*n];\n</code></pre>\n\n<p>Secondly don't use pointer.<br>\nIn modern C++ it is very rare to see RAW pointers (as they have no concept of ownership). And they are prone to leaking. you should be using either <code>smart pointers</code> or containers to hold your dynamically allocated memory.</p>\n\n<p>In this case a container would have been better.</p>\n\n<pre><code> std::vector&lt;double&gt; A(m*n);\n</code></pre>\n\n<p>All memory management now handled correctly.<br>\nThis can then be used in your C code with</p>\n\n<pre><code> double* Ap = &amp;A[0]; // get the address of the first element.\n</code></pre>\n\n<p>This is not going to go well:</p>\n\n<pre><code> Q = (double*)realloc(Q_E.data(), m*minmn*sizeof(double));\n\n // Q_E.data() better not only return you a pointer allocated with malloc.\n // But it better set the internal pointers to NULL or some\n // other safe value. As soon as the realloc() finishes the\n // old pointer is no longer valid.\n</code></pre>\n\n<p>Also this is not the correct way to use realloc.</p>\n\n<pre><code> size_t size = /* Calc Size */;\n double* data = (double*)malloc(size);\n ...\n size_t newSiz = /* New Space needed */;\n double* resize = (double*)realloc(data, newSize); \n if (resize != NULL)\n {\n data = resize; // if realloc() returns NULL the original array\n size = newSiz; // is unaffected. You should check this after\n } // the call and only reassign the original\n // value if the resize worked correctly.\n</code></pre>\n\n<p>Major Points:</p>\n\n<p>I don't know what is happening inside <code>MatrixXd</code> but it looks like it is exposing its memory management outside the class. That is not a good idea. An object should know how to handle its memory in all situation (and do its own resizing as appropriate).</p>\n\n<p>Two don't use RAW pointers (use C++ ownership symantics).</p>\n\n<p>Learn the <code>Rule of Three/Five</code> so that objects manage their own memory.</p>\n\n<p>Don't write C code and definately don't write C memory management code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-02T17:29:08.093", "Id": "74589", "Score": "0", "body": "A reason why I do not want to use vector is it actually slows down the computation by a few factors. That is why I want to do all the memory management myself and also give the user some responsibility on the memory management front." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-02T17:55:02.637", "Id": "74594", "Score": "0", "body": "@LeslieFaulkner: I don't believe that. We have shown several times on SO that vector is as fast (and faster when you use realloc) than manual memory management. If there is a slow down then it is because you doing something non idiomatic and causing unnecessary copies. If you want to publish your version with std::vector we can show you where you are going wrong." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-02T17:58:11.443", "Id": "74595", "Score": "0", "body": "Anyway fast and broken is not really as useful as slow and correct." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T18:36:45.260", "Id": "43158", "ParentId": "43148", "Score": "6" } }, { "body": "<blockquote>\n <p>I am wondering if there is any memory leak or undocumented behavior in my implementation</p>\n</blockquote>\n\n<p>I don't see a leak, but it's difficult to confirm there isn't one.</p>\n\n<p>This statement is dubious:</p>\n\n<pre><code>Q = (double*)realloc(Q_E.data(), m*minmn*sizeof(double));\n</code></pre>\n\n<p>If it had been this instead ...</p>\n\n<pre><code>Q = (double*)realloc(Q, m*minmn*sizeof(double));\n</code></pre>\n\n<p>... then it would have been less dubious; however if realloc fails it will return NULL, therefore overwriting a value with realloc can leak the previously-allocated value, so even that should be more like the following using a temp variable to test the result of realloc before using it to overwrite the previous value ...</p>\n\n<pre><code>double* temp = (double*)realloc(Q, m*minmn*sizeof(double));\nif (!temp) {\n ... handle error here and don't forget to free Q ...\n return;\n}\n// else realloc successful\nQ = temp;\n</code></pre>\n\n<p>However in your code I don't see how your get_QR function can be making use of the pre-allocated, passed-in <code>double* Q</code> and <code>double* R</code> arrays: and therefore I think that they're being leaked; maybe there wouldn't be a leak if you didn't allocate/initialize Q and R in main.</p>\n\n<p>Depending on which compiler you're using, there may be built-in tools to detect memory leaks: e.g. <a href=\"http://msdn.microsoft.com/en-us/library/aa271695%28v=vs.60%29.aspx\" rel=\"nofollow\">the Debug Heap for Microsoft's compiler</a>); or for Linux I recommend using <a href=\"http://en.wikipedia.org/wiki/Valgrind\" rel=\"nofollow\">valgrind</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T19:16:13.077", "Id": "43160", "ParentId": "43148", "Score": "1" } }, { "body": "<p>@Loki Astari has hit on all the important points, but I have just a few things to add:</p>\n\n<ul>\n<li><p>Make sure you're including all of the libraries here, especially if someone wants to test this code. You're missing <code>&lt;iostream&gt;</code>, <code>&lt;ctime&gt;</code>, and <code>&lt;cstdlib&gt;</code>.</p></li>\n<li><p>As Loki has mentioned, you're using a lot of C code in this C++ program. Another instance of this is some of your casting.</p>\n\n<p>Instead of casting the C way (for this instance):</p>\n\n<pre><code>double RANDMAX = double(RAND_MAX);\n</code></pre>\n\n<p>cast the C++ way:</p>\n\n<pre><code>double RANDMAX = static_cast&lt;double&gt;(RAND_MAX);\n</code></pre></li>\n<li><p>Your use of whitespace for assignments is a little unusual. Although it is okay to align a list of initialized variables (at least when you <em>must</em> have a list), I don't see the need in other instance such as this:</p>\n\n<pre><code>for (int index=0; index&lt;m*n; ++index) {\n A[index] = rand()/RANDMAX;\n}\n</code></pre>\n\n<p>That makes the loop harder to read, and there's just no point to it. In addition, you should also add a space between the operator and operands in the loop statement.</p>\n\n<p>You'll then have this:</p>\n\n<pre><code>for (int index = 0; index &lt; m*n; ++index) {\n A[index] = rand() / RANDMAX;\n}\n</code></pre></li>\n<li><p>In <code>get_QR()</code>:</p>\n\n<pre><code>void get_QR(double* A, int m, int n, double*&amp; Q, double*&amp; R) {}\n</code></pre>\n\n<p>I'd group the arguments and parameters by types, making it less-likely to mismatch the arguments when making the function call. Perhaps something like this:</p>\n\n<pre><code>void get_QR(double* A, double*&amp; Q, double*&amp; R, int m, int n) {}\n</code></pre></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T19:18:55.543", "Id": "43161", "ParentId": "43148", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T16:45:00.397", "Id": "43148", "Score": "5", "Tags": [ "c++", "memory-management", "matrix", "eigen" ], "Title": "Are there any memory issues with this Eigen QR wrapper?" }
43148
<p>I have recently adapted the popular <a href="http://leanmodal.finelysliced.com.au/" rel="nofollow">leanmodal</a> plugin (with permission). Being "intermediate" with JS (need to learn more), I was wondering if anyone would like to review my code for efficiency.</p> <ul> <li><strong>jQuery &amp; JS</strong> - bad practice?</li> <li><strong>Functions</strong> - structured correctly? </li> <li><strong>Repetition</strong> - When using logic, I repeat nearly exact code - bad? Better way to do it?</li> <li><strong>External</strong> - <code>$(document).ajax_load();</code> is external script</li> </ul> <p><strong>Functionality</strong></p> <pre><code>#Initialize $('a[rel*=leanModal]').leanModal({ overlay: 0.9, removeModal: true, ajax: true }); </code></pre> <p>Process:</p> <ul> <li>Link clicked, leanModal triggered</li> <li>LeanModal checks for "type" of link (ajax / normal)</li> <li>If Ajax OR image, uses special vars</li> <li>If normal, loads overlay &amp; modal</li> <li>Binds click event to over to close</li> <li>Binds click event to close button</li> <li>If user clicks close elements, modal removed</li> </ul> <hr> <pre><code>(function( $ ){ $.fn.leanModal = function(options) { //Defaults var defaults = { overlay: 0.5, closeButton: null, delay: null, drag: ".modal_title", removeModal: null, autoLoad: null, ajax: false }; //Definitions var plugin = this; var options = $.extend(defaults, options); //Init plugin.init = function() { if(options.autoLoad){ $.extend(options, {modal_id: $(this)}); create(); }else{ return this.each(function() { $(this).click(function(e) { e.preventDefault(); var href = $(this).attr("href"); var image = CheckImg(href); var random = Math.floor(Math.random()*90000) + 10000; var extras = (options.ajax || image) ? {modal_id: "#modal_" + random, ajax: href.replace(/\/$/, '')} : {modal_id: href}; $.extend(options, extras); create(); }); }); } } ////////////////// // Actions // ////////////////// //Build var create = function() { if(options.ajax){ //Loading Loader(); //Image switch (true) { case CheckImg(options.ajax): append("img", options.modal_id.substring(1), options.ajax); show(); break; default: fetch(options.ajax, function(data){ append("modal", options.modal_id.substring(1), options.ajax, data); show(); }, function(data){ Loader(); alert("Sorry, there was an error!"); }); break; } }else{ show(); } } //Ajax var fetch = function(link, success, error) { $.ajax({ url: link, success: function(data) { success(data); }, error: function(data) { error(data); } }); } //Overlay var olay = function(modal_id, removeModal, closeButton) { var overlay = document.createElement("div"); overlay.setAttribute("id", "lean_overlay"); document.body.appendChild(overlay); overlay.onclick = function() { close(modal_id, removeModal, $(closeButton)); return false; }; } //Show var show = function() { /* Vars */ var id = options.modal_id var removeModal = options.removeModal var closeButton = options.closeButton var drag = options.drag var ajax = options.ajax var overlay = options.overlay var modal = $(id); var overlay = $("#lean_overlay"); /* Overlay */ olay(id, removeModal, closeButton); /* Options */ if (closeButton) { $(closeButton).css("z-index", "10300"); $(closeButton).on("click", function (e) { e.preventDefault(); close(id, removeModal, $(closeButton)); return false; }); } /* Loading */ if (ajax) { modal.load(function() { Loader() }); } /* Styling */ overlay.css({ "display": "block", opacity: 0 }); modal.css({ "display": "block", "position": "fixed", "opacity": 0, "z-index": 10200, "left": 0, "right": 0, "top": 0, "bottom": 0, "margin": "auto" }); /* Init */ overlay.fadeTo(150, options.overlay); modal.fadeTo(200, 1); if(drag.length &gt; 0) { modal.draggable({ handle: drag }); } } //Close var close = function(modal, removeModal, closeButton, ajax) { if(ajax){ xhr.abort(); } $("#lean_overlay").fadeOut(150, function(){ $(this).remove(); if(closeButton) { closeButton.off("click"); closeButton.removeAttr('style'); } }); $(modal).fadeOut(150, function(){ if (removeModal) { $(this).remove(); } }); } //Go plugin.init(); }; ////////////////// // Dependencies // ////////////////// var Loader = function() { $(document).ajax_load(); } var CheckImg = function(url) { return(url.match(/\.(jpeg|jpg|gif|png)/) != null); } var append = function(type, id, src, data) { //Definitions var style = element = type; if (type == "modal") { var style = "ajax"; var element = "div"; } //Element var el = document.createElement(element); el.setAttribute("id", id); el.setAttribute("src", src); el.className = 'modal ' + style; //Ajax if (data) { el.innerHTML = data; } //Append document.body.appendChild(el); } })( jQuery ); </code></pre>
[]
[ { "body": "<h1>Messy code?</h1>\n\n<p>Nah! It really depends on the developer. But I highly suggest you follow certain conventions for clean code, especially the parts regarding indentation, one-liners etc. There are quick tools online for cleaning up code, like JSBeautifier. There are also formatters for code, via Grunt, which formats your code on save (don't know which though, I use a pre-made script).</p>\n\n<h1>Never forget <code>;</code></h1>\n\n<p>Although JS does forgive you for missing <code>;</code> at certain cases, but in practice, you should never forget them. You will have issues especially when you minify the code. </p>\n\n<p>Poorly created minifiers may not insert <code>;</code> and you'll end up with something like </p>\n\n<pre><code>`var foo = 'test'var bar='test'`. \n</code></pre>\n\n<p>Concat scripts might not merge files and separate them with <code>;</code>. You'd end up with these at the joining. The compiler might think the previous is a function wrapped in a <code>()</code> and you're trying to execute it (via the second <code>()</code>) and passing it a function... or something like that. Happens every time I forget to <code>;</code>.</p>\n\n<pre><code>(function(){\n...\n}(jQuery))(function(){\n ...\n}(jQuery))\n</code></pre>\n\n<h1><code>switch(true)</code></h1>\n\n<p>This is an odd use for <code>switch</code></p>\n\n<pre><code>switch (true) {\n case CheckImg(options.ajax):\n append(\"img\", options.modal_id.substring(1), options.ajax);\n show();\n break;\n default:\n fetch(options.ajax, function(data){\n append(\"modal\", options.modal_id.substring(1), options.ajax, data);\n show();\n }, function(data){\n Loader();\n alert(\"Sorry, there was an error!\");\n });\n break;\n}\n</code></pre>\n\n<p>Normally, people would do <code>switch(variable)</code>. Though this could work, but it looks weird at first. Not good for usability. Also, one bad thing about <code>switch</code> is the <code>break</code>. Forgetting it would spell disaster. I'd rather go for <code>if-else</code> instead.</p>\n\n<pre><code>if(CheckImg(...)){\n append(\"img\", options.modal_id.substring(1), options.ajax);\n show();\n} else {\n fetch(options.ajax, function(data){\n append(\"modal\", options.modal_id.substring(1), options.ajax, data);\n show();\n }, function(data){\n Loader();\n alert(\"Sorry, there was an error!\");\n });\n}\n</code></pre>\n\n<h1>Using jQuery? Use it all the way!</h1>\n\n<p>I noticed this in your code:</p>\n\n<pre><code>var overlay = document.createElement(\"div\");\n overlay.setAttribute(\"id\", \"lean_overlay\");\n\ndocument.body.appendChild(overlay);\noverlay.onclick = function() { close(modal_id, removeModal, $(closeButton)); return false; };\n</code></pre>\n\n<p>I thought you used jQuery? You could have gone with something much more elegant:</p>\n\n<pre><code>$('&lt;div/&gt;',{\n 'id' : 'lean_overlay'\n}).on('click',function(){\n close(modal_id, removeModal, $(closeButton);\n}).appendTo('body');\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T19:36:50.887", "Id": "74481", "Score": "0", "body": "Thanks Joseph! I really appreciate all the feedback. RE the semicolons - Ruby / Rails has spoilt me. Switch true was to make it simpler (I had multiple if/else before & didn't like it). Again - thanks +1" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T19:24:12.200", "Id": "43162", "ParentId": "43155", "Score": "2" } } ]
{ "AcceptedAnswerId": "43162", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T17:41:15.027", "Id": "43155", "Score": "4", "Tags": [ "javascript", "jquery", "plugin" ], "Title": "Leanmodel plugin" }
43155
<p>I have code that works perfectly, but it uses too much memory.</p> <p>Essentially this code takes an input file (lets call it an index, that is 2 column tab-separated) that searches in a second input file (lets call it data, that is 4-column tab separated) for a corresponding term in the 1st column which it then replaces with the information from the index file.</p> <p>An example of the index is:</p> <pre><code>amphibian anm|art|art|art|art anaconda anm aardvark anm </code></pre> <p>An example of the data is :</p> <pre><code>amphibian-n is green 10 anaconda-n is green 2 anaconda-n eats mice 1 aardvark-n eats plants 1 </code></pre> <p>Thus, when replacing the value in Col 1 of data with the corresponding information from Index, the results are as follows:</p> <pre><code>anm-n is green art-n is green anm-n eats mice anm-n eats plants </code></pre> <p>I divided the code in steps because the idea is to calculate average of the values given a replaced item (Col 4 in data) of Cols 2 and 3 in the data file. This code takes the total number of slot-fillers in the data file and sums the values which is used in Step 3.</p> <p>The desired results are the following:</p> <pre><code>anm second hello 1.0 anm eats plants 1.0 anm first heador 0.333333333333 art first heador 0.666666666667 </code></pre> <p>I open the same input file many times (i.e. 3 times) in Steps 1, 2 and 3 because I need to create several dictionaries that need to be created in a certain order. However, the bottleneck is definitely between Steps 2 and 3. If I remove the function in Step 2, I can process the entire file (13GB of ram in approx. 30 minutes). However, the necessary addition of Step 2 consumes all memory before beginning Step 3.</p> <p>Is there a way to optimize how many times I open the same input file?</p> <pre><code>#!/usr/bin/python # -*- coding: utf-8 -*- from __future__ import division from collections import defaultdict import datetime print "starting:", print datetime.datetime.now() mapping = dict() with open('input-map', "rb") as oSenseFile: for line in oSenseFile: uLine = unicode(line, "utf8") concept, conceptClass = uLine.split() if len(concept) &gt; 2: mapping[concept + '-n'] = conceptClass print "- step 1:", print datetime.datetime.now() lemmas = set() with open('input-data', "rb") as oIndexFile: for line in oIndexFile: uLine = unicode(line, "latin1") lemma = uLine.split()[0] if mapping.has_key(lemma): lemmas.add(lemma) print "- step 2:", print datetime.datetime.now() featFreqs = defaultdict(lambda: defaultdict(float)) with open('input-data', "rb") as oIndexFile: for line in oIndexFile: uLine = unicode(line, "latin1") lemmaTAR, slot, filler, freq = uLine.split() featFreqs[slot][filler] += int(freq) print "- step 3:", print datetime.datetime.now() classFreqs = defaultdict(lambda: defaultdict(lambda: defaultdict(float))) with open('input-data', "rb") as oIndexFile: for line in oIndexFile: uLine = unicode(line, "latin1") lemmaTAR, slot, filler, freq = uLine.split() if lemmaTAR in lemmas: senses = mapping[lemmaTAR].split(u'|') for sense in senses: classFreqs[sense][slot][filler] += (int(freq) / len(senses)) / featFreqs[slot][filler] else: pass print "- step 4:", print datetime.datetime.now() with open('output', 'wb') as oOutFile: for sense in sorted(classFreqs): for slot in classFreqs[sense]: for fill in classFreqs[sense][slot]: outstring = '\t'.join([sense, slot, fill,\ str(classFreqs[sense][slot][fill])]) oOutFile.write(outstring.encode("utf8") + '\n') </code></pre> <p>Any suggestions on how to optimize this code to process large text files (e.g. >4GB)?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-02T10:20:41.747", "Id": "74558", "Score": "1", "body": "Why does `anaconda` become `art` in the example? The index maps it to `anm`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-02T12:26:39.237", "Id": "74561", "Score": "0", "body": "`anaconda` does not become `art`, you are referring to `amphibian` that is mapped to `art`. The example demonstrates that for each possible mapping, the Col. inof in Cols 2 and 3 are repeated." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-02T19:30:54.050", "Id": "74606", "Score": "0", "body": "The example is still not quite clear, but anyway, perhaps you should use a database." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-03T13:56:32.813", "Id": "74730", "Score": "5", "body": "I noticed [the same question on stackoverflow.com](http://stackoverflow.com/q/22117818/222914), which has an accepted answer already." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T18:08:21.363", "Id": "43156", "Score": "1", "Tags": [ "python", "optimization", "memory-management", "python-2.x" ], "Title": "Optimize Python script for memory which opens and reads multiple times the same files" }
43156